From a406626f50d66eb5e294ac7c16987f4d2a280c57 Mon Sep 17 00:00:00 2001 From: Sir Tobi Date: Sun, 6 Sep 2026 09:27:58 +0200 Subject: [PATCH 001/514] Correct DOS_CMD_COPY_FILE in ultimate_dos-1.1 --- doc/ultimate_dos-1.1.docx | Bin 23159 -> 23228 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/doc/ultimate_dos-1.1.docx b/doc/ultimate_dos-1.1.docx index 7043c24f93613c6413e04dcba8cfaf2273bf4c31..df2ce2967776fe742cf04015f83371bd285c3c4e 100644 GIT binary patch delta 10604 zcmYLvWl)_xv^9Eg_u}sEPI32Q#a#;r_XmnQ6p9or?(XhVIJir(;_h1b`rdnIzWiBP zJ1aALXLd3>lRPv+cQ!%S>d+&X)>m5IGeAKJbtjwBlLGbo?>^DUQ_-Y0lcphqLtDQ$ z=sAX+Ca;}{*F^*FS7s;+VH#Ozn%RbLYwpl*Y;q&r-c$!Whedw*ejBS~GQz|*C7xSm zlOqh(E>|kQ9-q+E+0T97GjmMxJN7NM0M@n875ze2+bz=XFL!@CUAXsj%ZZpYpg~+6 zpTW+uU4ZB{d+ys>Zi!rY0fL473tV|^SHY3=dn^C--!YB4!y{^;#m1fK0F3?gw#Ro)jeXUZvQuY zazJT7{*(1)qcQ;UNV7NNogC@vZAy^Fd(nuv1X8JgQ(ocy-macw>)Df54{FkLFM|(o zadfs+-7yns;%gN^W^Oa#i+rhTA`pcsy6&`b*|FDpjAk}0c>(pH_D9R^uz~SP!w(v$kT_U*Jqv{a-i{&1E+<~W>@0}cK z9*?GEz-@$Ss_W*$OVzum*n4?L#d}&yi~g&wj^vM#*^Y4}hXQRs0Sx7|eh#zBN-6W% z{_Q{V4R=Yq*aNq(zehxaBt(Sb<0lIW0AkNS8M{$3HKYlDcN_t=sZv3bC-R5+a?Ogx zh3I;@XLrk0&?PUkt>7~$@8eHCH<%uamQt%a9O^laQV2TlxNEU4)L1HLz2vlxOjhL^ zf{tx?u8gPMjyGNZr2c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J5&g#-cZ<|4JG^nqXF_G|WI$TnIYb z<9byR%+p=W?H}hZjgRZ19ejJ{{1 zG+r;^Zzn+YWR6NJIz`ATo%$emG2J4&`e46G^$*o4wa;rnRRjGzhN2w*?!aF$)d1_p zQlz)Ei%~A&&@Xa6hn^-A@C#r2$o2HjgEb;Ahw(hVz!l!YkPa0>hG&YkIDoL-kFV`D0Y%`DwBdJFC++P{5a(8hxi!_qApqPpA-r{(0h zh}h{f2VjjC-X6toGQsLPH`<8ceamzGP)4l}C;oTG8@S?!a+|smV(b7op{t zf Date: Sun, 6 Sep 2026 09:28:00 +0200 Subject: [PATCH 002/514] Correct DOS_CMD_COPY_FILE in ultimate_dos-1.2 --- doc/ultimate_dos-1.2.docx | Bin 34349 -> 31016 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/doc/ultimate_dos-1.2.docx b/doc/ultimate_dos-1.2.docx index ccddbb9868db8d5959708d3b02e9ae9a8938c27b..14142c69afa995c65b7437deb0024caa0d122396 100644 GIT binary patch literal 31016 zcmZ6zV{m4{w=bMb>`ZLiwr$(CZA@(2nAo;$=ZS6G$({c>=hpk4`=M7?ckk6z`?pr@ zTHFfKAfPBfKtPcH1|d*1MsrvYFc45R1P~DNza4F1dpj3XI~RQwPX|+HT{;h2o92{B zt3d`t(U*|#pm{ccR0qZ1q4B~vQ*4WO;7Hb3*=mS|!>1SA(O62-7$IbP*ypM4muQpp zJD17|3%Hpyu~M64SWQqa=7y!oWZxP60|+!v6s^b!3yC#&o-8>#`;mtnF#H6qk7U&F z=LF|G)cj!iXfWB7O%Bp{y{$y;1m6hK+s?h)TyrsEi|G1igQPp=LnBqg$A-VNa1lWh zji=?7RgFqyRn-$R1j}z)llqj7S@H2sI|oq<@4&1Kek=twpSW}9+h-O!l!Td3VfI3b z=sOtX?JR3j2~3=}&cTa^o*9CrwOdupm>%-xH5J8`6pH79;li~`zi=pP5f(Hd2zjol zZdb`IdwOLX`K)ZfTQ7eD}FK{{5c%SX9JAdx~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OGvBuK*5+v8(>1|wq`rOe!7TsMzEBAbvK&jJEW~NJ z980IY0Le95fCB`-;*>9SU(qTQqzyT@fOop^;M_;o78Ow<`YaTL%Q2VurJC5Jl)enl z{2EuH&P4T>%Es#&-{&st|MqK0du~NI|E#(G+?w7ZG@0mVlxJau zx19!-6-dGPNxEBmg?&u519L0*F;5+@mX@iyklDpqcIdG;7)Eade7-9yTRb515X^#V zyHtF{Uw$>kQPZRBgiWNfdxF%lk$X7zpziuANMZ(uVjQ_iSsr`A|p_dGu##7w4r+ z{*;<@A6FH_%ojY(p*Rv@JhJS+n%cy!AW`rhV5{&8uk5j$3!PK|n;axe$EyXtM`F&5 zPpTQ|GXF6zT_OxGp%W8K@QX2Q#R`cd#j_~i7u89Cc~*G)9KHu%pb*lgKn6*+ncY_q zy|&nUCZfpgK}b}*L-UXvv%Ws%QLkf0Z;u#E-VCH~Mc2g^hjs8pB|#g&_pE#Jm>Ho{ zMGO_D|ErKqpLYoDkUke|$Naa+&FsRjzLp&;9g1!xkE(%*79I8T)~p1l4^z#LiJC=L zZf8d<92)*6kwY2DR1>Fjmb|$1{lh~p{eoYS@yM7F-eNbArAzr;E&xxZ#y!L|YKq>$ z!*8q=rcaztduKFYbfn(E{?-scAlgrZ8ZZEe&wri}AOfQyIP6nLDn32NkpJur|2}96 z*;qS%CePMUah{Vx&!wo3gS z{=1piKk&wHf5Cq<`ubhM?}kqQNO<_9<^JqP|Cl}f4*s1t{s+8o{TJByQw9E)MgATC zpA_FeXaE2=I{<+Hi}3p${yT^Aj{sH2zfS)jjLPr$|D56eK?49hfB)C%|C;aQq(DD4 T>yNn*0pRUZIkElz`1OAPL!3g? From dddd29b25d64c79d3a8cab95d8b86e1f8cafb816 Mon Sep 17 00:00:00 2001 From: Gideon Date: Sat, 12 Sep 2026 08:38:38 +0200 Subject: [PATCH 003/514] Bump version to 3.15a --- software/application/versions.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/software/application/versions.h b/software/application/versions.h index 9043fcc43..f04929d2a 100644 --- a/software/application/versions.h +++ b/software/application/versions.h @@ -41,7 +41,7 @@ #define RELEASE_TYPE_BETA 1 #define RELEASE_TYPE_ALPHA 2 -#define APPL_VERSION_NUMBER "3.15" +#define APPL_VERSION_NUMBER "3.15a" #define APPL_RELEASE_TYPE RELEASE_TYPE_NORMAL #define BOOT_VERSION "V3.2" #define FPGA_VERSION "FPGA U2 V116" From 8d0f311c22d3b53cc64e50081916238907752b0a Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Thu, 3 Sep 2026 20:54:47 +0200 Subject: [PATCH 004/514] Check what a G64 says about its tracks before believing it GcrImage::load() took each track's length straight from the image, masked it to 14 bits and stored it. That mask admits 16383, while GCRIMAGE_MAXTRACKLEN is 7928, and nothing compared the length against the space left in the buffer behind the track's own offset. insert_disk() then programs that length into the drive engine's parameter RAM, and floppy_mem.vhd both reads and writes memory bounded by it, so a crafted image could point the hardware about 8 KB past the end of the allocation. Three smaller holes on the same path: the offset test admitted offset == GCRIMAGE_MAXSIZE, so tr[0] and tr[1] were read one and two bytes past the buffer; the offset was never compared against how much the file actually delivered, so a length could be taken from a part of the buffer no read had filled; and a track declared zero bytes long reached insert_disk()'s division by track_length. A track whose metadata does not survive these checks is now left as invalidate() left it -- absent -- so add_blank_tracks() gives it a blank track and the mount goes on. add_blank_tracks() in the same file already bound-checks this way, so the missing check in load() was an omission rather than a choice. The checks live in a new header of free functions over plain integers rather than in load() itself, because none of the drive headers can be compiled on a build host and this is the part worth testing there. Reported in GideonZ/1541ultimate#823, problems 2 and 4. --- software/drive/disk_image.cc | 36 +++--- software/drive/gcr_track_bounds.h | 60 ++++++++++ software/drive/tests/Makefile | 15 +++ .../drive/tests/gcr_track_bounds_test.cpp | 108 ++++++++++++++++++ 4 files changed, 206 insertions(+), 13 deletions(-) create mode 100644 software/drive/gcr_track_bounds.h create mode 100644 software/drive/tests/Makefile create mode 100644 software/drive/tests/gcr_track_bounds_test.cpp diff --git a/software/drive/disk_image.cc b/software/drive/disk_image.cc index 05fad24c8..f20aeccef 100644 --- a/software/drive/disk_image.cc +++ b/software/drive/disk_image.cc @@ -20,6 +20,7 @@ extern "C" { #include "user_file_interaction.h" #include "blockdev_file.h" #include "endianness.h" +#include "gcr_track_bounds.h" #define HARDWARE_ENCODING 1 @@ -709,23 +710,32 @@ bool GcrImage :: load(File *f) // track offsets start at 0x000c for(int i=0;i GCRIMAGE_MAXSIZE) { + if(offset >= GCRIMAGE_MAXSIZE) { printf("Error. Track pointer outside GCR memory range.\n"); return false; } + // Offset zero means the track is absent. A non-zero one still has to + // point at two bytes the file actually delivered, since reading the + // length word is itself an access into the image buffer. + if(!gcr_track_header_is_readable(offset, bytes_read)) { + continue; + } tr = gcr_data + offset; - if(offset) { - w = tr[0] | (uint16_t(tr[1]) << 8); - tracks[i].track_address = tr + 2; - tracks[i].track_length = (int)(w & 0x3FFF); - tracks[i].track_used = true; - tracks[i].in_image_file = true; - tracks[i].track_is_mfm = (w & 0x8000); -// printf("Set track %d.%d to 0x%6x / 0x%4x.\n", (i>>1)+1, (i&1)?5:0, tracks[i].track_address, w); - if (i >= GCRIMAGE_FIRSTTRACKSIDE1) { - double_sided = true; - } - } + w = tr[0] | (uint16_t(tr[1]) << 8); + int length = gcr_validated_track_length(w, offset, GCRIMAGE_MAXSIZE, GCRIMAGE_MAXTRACKLEN); + if(!length) { + printf("Track %d: declared length %d does not fit the image. Track skipped.\n", + i, (int)(w & 0x3FFF)); + continue; // invalidate() left this entry unused; leave it that way + } + tracks[i].track_address = tr + 2; + tracks[i].track_length = length; + tracks[i].track_used = true; + tracks[i].in_image_file = true; + tracks[i].track_is_mfm = (w & 0x8000); + if (i >= GCRIMAGE_FIRSTTRACKSIDE1) { + double_sided = true; + } } // Track speed zone info starts after the track offsets uint8_t reported_tracks = gcr_data[9]; diff --git a/software/drive/gcr_track_bounds.h b/software/drive/gcr_track_bounds.h new file mode 100644 index 000000000..a48c1ed98 --- /dev/null +++ b/software/drive/gcr_track_bounds.h @@ -0,0 +1,60 @@ +/* + * gcr_track_bounds.h -- what a G64 says about its tracks, checked. + * + * The track lengths in a G64 file are not decoration: insert_disk() programs + * them into the drive engine's parameter RAM, and floppy_mem.vhd both reads + * and writes memory bounded by them. So a length taken from the file decides + * how far the hardware reaches into a buffer, and a track that is not in the + * image at all still has to be given a parameter pair the engine can survive. + * + * These are free functions over plain integers, deliberately: none of the + * drive headers can be compiled on a build host, and this is the part that is + * worth testing there. See software/drive/tests/. + */ +#ifndef DRIVE_GCR_TRACK_BOUNDS_H +#define DRIVE_GCR_TRACK_BOUNDS_H + +#include + +/* A track table entry points at a two-byte length word followed by the track + * data. Reading that word is itself an access into the image buffer, so it has + * to lie inside the part of the buffer the file actually filled. Offset zero + * means the track is absent. */ +static inline bool gcr_track_header_is_readable(uint32_t offset, uint32_t bytes_read) +{ + if (offset == 0 || offset > bytes_read) { + return false; + } + return (bytes_read - offset) >= 2; +} + +/* Returns the track length to use, or 0 when the track cannot be used and has + * to be left marked absent. + * + * declared the 16-bit word from the image, flag bits included + * offset byte offset of that word within the buffer + * capacity size of the buffer + * max_length longest track the format allows + * + * The masked field holds 14 bits, so it admits lengths more than twice the + * longest legitimate track, and a track near the end of the buffer can declare + * a length that runs off it. Both are rejected here rather than programmed. + */ +static inline int gcr_validated_track_length(uint16_t declared, uint32_t offset, + uint32_t capacity, int max_length) +{ + int length = (int)(declared & 0x3FFF); + + if (length <= 0 || length > max_length) { + return 0; /* zero would also divide by zero in insert_disk() */ + } + if (offset > capacity || (capacity - offset) < 2) { + return 0; + } + if ((uint32_t)length > (capacity - offset - 2)) { + return 0; + } + return length; +} + +#endif /* DRIVE_GCR_TRACK_BOUNDS_H */ diff --git a/software/drive/tests/Makefile b/software/drive/tests/Makefile new file mode 100644 index 000000000..e9669a892 --- /dev/null +++ b/software/drive/tests/Makefile @@ -0,0 +1,15 @@ +CXX ?= g++ +CXXFLAGS := -std=c++14 -g -Wall -Wextra -I. -I.. -I../../io/usb/tests +OUTPUT_DIR := output +GCR_TRACK_BOUNDS_TEST := $(OUTPUT_DIR)/gcrTrackBoundsTest + +.PHONY: all gcr-track-bounds clean + +all: gcr-track-bounds + +gcr-track-bounds: + mkdir -p $(OUTPUT_DIR) + $(CXX) $(CXXFLAGS) gcr_track_bounds_test.cpp ../../io/usb/tests/host_test_main.cpp -lpthread -o $(GCR_TRACK_BOUNDS_TEST) && $(GCR_TRACK_BOUNDS_TEST) + +clean: + rm -rf $(OUTPUT_DIR) diff --git a/software/drive/tests/gcr_track_bounds_test.cpp b/software/drive/tests/gcr_track_bounds_test.cpp new file mode 100644 index 000000000..fdcd7c38e --- /dev/null +++ b/software/drive/tests/gcr_track_bounds_test.cpp @@ -0,0 +1,108 @@ +// Regression tests for GideonZ/1541ultimate#823: a G64's track metadata used to +// program the drive engine's memory bounds without ever being checked against +// the buffer that holds the image. +// +// Two of the four problems in that issue are pinned down here; the parameter +// RAM side follows in its own change. +// +// 2. track length never validated against the buffer -> ValidatedLength +// 4. divide by zero on a zero-length track -> ValidatedLength + +#include "../../io/usb/tests/host_test/host_test.h" +#include "../gcr_track_bounds.h" + +namespace { + +// The real constants, so the numbers here are the ones the firmware uses. +const uint32_t kMaxSize = (0x1EF8 * 80) + (12 + (168 * 10)); // GCRIMAGE_MAXSIZE +const int kMaxTrackLen = 0x1EF8; // GCRIMAGE_MAXTRACKLEN + +} // namespace + +// ---------------------------------------------------------------- problem 2 -- + +TEST(ValidatedLength, AcceptsALegitimateTrack) +{ + EXPECT_EQ(gcr_validated_track_length(0x1E0C, 0x2000, kMaxSize, kMaxTrackLen), 0x1E0C); +} + +TEST(ValidatedLength, KeepsTheLongestLegalTrack) +{ + EXPECT_EQ(gcr_validated_track_length(kMaxTrackLen, 0x2000, kMaxSize, kMaxTrackLen), kMaxTrackLen); +} + +TEST(ValidatedLength, IgnoresTheFlagBitsAboveTheLength) +{ + // Bit 15 is the MFM marker; it must not be read as part of the length. + EXPECT_EQ(gcr_validated_track_length(0x8000 | 0x1E0C, 0x2000, kMaxSize, kMaxTrackLen), 0x1E0C); +} + +TEST(ValidatedLength, RejectsALengthAboveTheFormatMaximum) +{ + // 14 bits admit 16383, more than twice the longest real track. Before the + // fix this was programmed as-is and the engine read and wrote past the + // allocation. + EXPECT_EQ(gcr_validated_track_length(0x3FFF, 0x2000, kMaxSize, kMaxTrackLen), 0); +} + +TEST(ValidatedLength, RejectsATrackRunningOffTheEndOfTheBuffer) +{ + // Legal length, but placed so that it does not fit behind its own header. + const uint32_t offset = kMaxSize - 100; + EXPECT_EQ(gcr_validated_track_length(0x1E0C, offset, kMaxSize, kMaxTrackLen), 0); +} + +TEST(ValidatedLength, AcceptsATrackEndingExactlyAtTheBufferEnd) +{ + const uint32_t offset = kMaxSize - 0x1E0C - 2; + EXPECT_EQ(gcr_validated_track_length(0x1E0C, offset, kMaxSize, kMaxTrackLen), 0x1E0C); +} + +TEST(ValidatedLength, RejectsATrackOneByteTooLongForTheBuffer) +{ + const uint32_t offset = kMaxSize - 0x1E0C - 1; + EXPECT_EQ(gcr_validated_track_length(0x1E0C, offset, kMaxSize, kMaxTrackLen), 0); +} + +TEST(ValidatedLength, SurvivesAnOffsetPastTheBuffer) +{ + // The caller rejects these first, but the arithmetic here must not wrap. + EXPECT_EQ(gcr_validated_track_length(0x1E0C, kMaxSize + 1, kMaxSize, kMaxTrackLen), 0); + EXPECT_EQ(gcr_validated_track_length(0x1E0C, 0xFFFFFFFFu, kMaxSize, kMaxTrackLen), 0); + EXPECT_EQ(gcr_validated_track_length(0x1E0C, kMaxSize - 1, kMaxSize, kMaxTrackLen), 0); +} + +// ---------------------------------------------------------------- problem 4 -- + +TEST(ValidatedLength, RejectsAZeroLengthTrack) +{ + // insert_disk() divides the rotation speed by the track length, so a track + // declared zero bytes long used to reach a division by zero. + EXPECT_EQ(gcr_validated_track_length(0x0000, 0x2000, kMaxSize, kMaxTrackLen), 0); + EXPECT_EQ(gcr_validated_track_length(0x8000, 0x2000, kMaxSize, kMaxTrackLen), 0); +} + +// ------------------------------------------------------- the header itself -- + +TEST(HeaderReadable, RejectsTheAbsentTrackMarker) +{ + EXPECT_FALSE(gcr_track_header_is_readable(0, 4096)); +} + +TEST(HeaderReadable, AcceptsAHeaderWhollyInsideWhatWasRead) +{ + EXPECT_TRUE(gcr_track_header_is_readable(4094, 4096)); +} + +TEST(HeaderReadable, RejectsAHeaderStraddlingTheEndOfWhatWasRead) +{ + // One byte of the length word is in the file, the other is stale buffer. + EXPECT_FALSE(gcr_track_header_is_readable(4095, 4096)); + EXPECT_FALSE(gcr_track_header_is_readable(4096, 4096)); +} + +TEST(HeaderReadable, RejectsAPointerPastWhatWasRead) +{ + EXPECT_FALSE(gcr_track_header_is_readable(8192, 4096)); + EXPECT_FALSE(gcr_track_header_is_readable(0xFFFFFFFFu, 4096)); +} From 3475e9eea3dde2d4ebdd730fccbdc20b3e7ad270 Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Thu, 3 Sep 2026 21:05:09 +0200 Subject: [PATCH 005/514] Never program the drive from a track parameter nobody wrote insert_disk() declared bit_time and track_len without initialisers, assigned them only inside the branch taken for a track that is present, and read them in the branch taken for one that is not. Two consequences. The first is reachable with nothing but a malformed file. GcrImage::load() returns false on a bad signature after invalidate() has zeroed the whole track table, but mount_g64() ignored what it returned and inserted the image anyway. Mounting any .g64 whose first eight bytes are not GCR-1541 or GCR-1571 therefore programmed all 84 parameter slots with dummy_track -- 7692 bytes, no slack -- paired with whatever those two stack slots happened to hold. A stale length above that points the drive engine, which reads and writes there, past the end of the heap block. The second is on every image. add_blank_tracks() fills only even indices, so every odd one takes the absent branch and was handed dummy_track together with the preceding track's length. That is safe today by exactly zero margin: the largest entry in track_lengths[] equals GCRIMAGE_DUMMYTRACKLEN. Both loops now build their parameter pair through one function, which gives an absent track the dummy address with the same short, safe length init() and remove_disk() already program, and which cannot see a neighbour at all. A zero or negative length is treated as absent there too, so the division has no way to reach a zero divisor even if a length slips past the checks at load time. mount_g64() now acts on load()'s answer: the file is closed and the drive is left empty, which is the state remove_disk() has already put it in. Reported in GideonZ/1541ultimate#823, problems 1 and 3. --- .github/workflows/build.yml | 6 ++ software/drive/c1541.cc | 52 ++++++------- software/drive/gcr_track_bounds.h | 30 ++++++++ .../drive/tests/gcr_track_bounds_test.cpp | 75 ++++++++++++++++++- 4 files changed, 135 insertions(+), 28 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 534962da0..1f1d9b6c6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -105,6 +105,12 @@ jobs: -v /opt/build-tools:/mnt/build-tools:ro \ -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -B -C target/pc/linux/test_http_target test-integer-widths" + - name: Test G64 track bounds + run: | + docker run --rm \ + -v /opt/build-tools:/mnt/build-tools:ro \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -C software/drive/tests" + - name: Test UCI Palette Commands run: | docker run --rm \ diff --git a/software/drive/c1541.cc b/software/drive/c1541.cc index 84cdb03ae..0e5bffb9a 100644 --- a/software/drive/c1541.cc +++ b/software/drive/c1541.cc @@ -3,6 +3,7 @@ #include #include #include +#include "gcr_track_bounds.h" #include "itu.h" #include "dump_hex.h" @@ -461,40 +462,30 @@ void C1541 :: insert_disk(bool protect, GcrImage *image) uint32_t rotation_speed = (CLOCK_FREQ / 20); // 2 (half clocks) * 1/8 (bytes) * clocks per track. 300 RPM = 5 RPS. (5 * 8 / 2) = 20 // side 0 - uint32_t bit_time; - uint32_t track_len; volatile uint32_t *param = (volatile uint32_t *)®isters[C1541_PARAM_RAM]; for(int i=0; i < GCRIMAGE_FIRSTTRACKSIDE1; i++) { GcrTrack *tr = &image->tracks[i]; - if (tr->track_address) { - bit_time = rotation_speed / tr->track_length; - track_len = tr->track_length; - // printf("Side0: %2d %08x %08x %d\n", i, tr->track_address, track_len, bit_time); - *(param++) = (uint32_t)tr->track_address; - *(param++) = (track_len-1) | (bit_time << 16); - } else { - // printf("Side0: %2d %08x %08x %d\n", i, tr->track_address, track_len, bit_time); - *(param++) = (uint32_t)dummy_track; - *(param++) = (track_len-1) | (bit_time << 16); - } + uint32_t track_addr, track_param; + gcr_track_parameters((uint32_t)tr->track_address, tr->track_length, + (uint32_t)dummy_track, GCRIMAGE_DUMMYTRACKLEN, + rotation_speed, &track_addr, &track_param); + // printf("Side0: %2d %08x %08x\n", i, track_addr, track_param); + *(param++) = track_addr; + *(param++) = track_param; registers[C1541_DIRTYFLAGS + i/2] = 0; - } + } // Side 1 param = (volatile uint32_t *)®isters[C1541_PARAM_RAM + 0x400]; // side 1 for(int i=GCRIMAGE_FIRSTTRACKSIDE1; i < GCRIMAGE_MAXHDRTRACKS; i++) { GcrTrack *tr = &image->tracks[i]; - if (tr->track_address) { - bit_time = rotation_speed / tr->track_length; - track_len = tr->track_length; - // printf("Side1: %2d %08x %08x %d\n", i, tr->track_address, tr->track_length, bit_time); - *(param++) = (uint32_t)tr->track_address; - *(param++) = (track_len-1) | (bit_time << 16); - } else { - // printf("Side1: %2d %08x %08x %d\n", i, tr->track_address, tr->track_length, bit_time); - *(param++) = (uint32_t)dummy_track; - *(param++) = (track_len-1) | (bit_time << 16); - } + uint32_t track_addr, track_param; + gcr_track_parameters((uint32_t)tr->track_address, tr->track_length, + (uint32_t)dummy_track, GCRIMAGE_DUMMYTRACKLEN, + rotation_speed, &track_addr, &track_param); + // printf("Side1: %2d %08x %08x\n", i, track_addr, track_param); + *(param++) = track_addr; + *(param++) = track_param; registers[C1541_DIRTYFLAGS + i/2] = 0; } @@ -615,7 +606,16 @@ void C1541 :: mount_g64(bool protect, File *file) return; } printf("Loading..."); - gcr_image->load(file); + if (!gcr_image->load(file)) { + // load() has already invalidated the image, so its track table holds + // nothing that may be programmed. remove_disk() ran above, so an empty + // drive is the state the machine is already in. + printf("Failed. Not a G64 image, or its track table does not fit.\n"); + fm->fclose(mount_file); + mount_file = NULL; + drive_reset(0); // do not reset, but restore the freeze + return; + } printf("Inserting..."); insert_disk(protect, gcr_image); printf("Done\n"); diff --git a/software/drive/gcr_track_bounds.h b/software/drive/gcr_track_bounds.h index a48c1ed98..45f00f1d3 100644 --- a/software/drive/gcr_track_bounds.h +++ b/software/drive/gcr_track_bounds.h @@ -16,6 +16,11 @@ #include +/* The low half of a parameter word is the last valid offset in the track, so + * this is a 257-byte empty track. init() and remove_disk() already program it + * for a drive with nothing in it. */ +#define GCR_EMPTY_TRACK_PARAM 0x100 + /* A track table entry points at a two-byte length word followed by the track * data. Reading that word is itself an access into the image buffer, so it has * to lie inside the part of the buffer the file actually filled. Offset zero @@ -57,4 +62,29 @@ static inline int gcr_validated_track_length(uint16_t declared, uint32_t offset, return length; } +/* Builds one entry of the drive's track parameter RAM: the address the engine + * works at, and a word carrying the last valid offset in the low half and the + * bit time in the high half. + * + * A track that is not in the image gets the dummy track together with the same + * short, safe length init() and remove_disk() use -- not whatever length the + * previous track happened to leave in a local. + */ +static inline void gcr_track_parameters(uint32_t track_address, int track_length, + uint32_t dummy_address, int dummy_length, + uint32_t rotation_speed, + uint32_t *out_address, uint32_t *out_param) +{ + if (track_address != 0 && track_length > 0) { + uint32_t bit_time = rotation_speed / (uint32_t)track_length; + *out_address = track_address; + *out_param = (uint32_t)(track_length - 1) | (bit_time << 16); + return; + } + + uint32_t bit_time = (dummy_length > 0) ? (rotation_speed / (uint32_t)dummy_length) : 0; + *out_address = dummy_address; + *out_param = GCR_EMPTY_TRACK_PARAM | (bit_time << 16); +} + #endif /* DRIVE_GCR_TRACK_BOUNDS_H */ diff --git a/software/drive/tests/gcr_track_bounds_test.cpp b/software/drive/tests/gcr_track_bounds_test.cpp index fdcd7c38e..3b90c95e3 100644 --- a/software/drive/tests/gcr_track_bounds_test.cpp +++ b/software/drive/tests/gcr_track_bounds_test.cpp @@ -2,10 +2,11 @@ // program the drive engine's memory bounds without ever being checked against // the buffer that holds the image. // -// Two of the four problems in that issue are pinned down here; the parameter -// RAM side follows in its own change. +// The four problems in that issue, and where each is pinned down below: // +// 1. parameter RAM programmed from uninitialised locals -> TrackParameters // 2. track length never validated against the buffer -> ValidatedLength +// 3. half-tracks inherit the previous track's length -> TrackParameters // 4. divide by zero on a zero-length track -> ValidatedLength #include "../../io/usb/tests/host_test/host_test.h" @@ -16,6 +17,8 @@ namespace { // The real constants, so the numbers here are the ones the firmware uses. const uint32_t kMaxSize = (0x1EF8 * 80) + (12 + (168 * 10)); // GCRIMAGE_MAXSIZE const int kMaxTrackLen = 0x1EF8; // GCRIMAGE_MAXTRACKLEN +const int kDummyLen = 0x1E0C; // GCRIMAGE_DUMMYTRACKLEN +const uint32_t kRotationSpeed = 50000000 / 20; // CLOCK_FREQ / 20 on the U64 } // namespace @@ -106,3 +109,71 @@ TEST(HeaderReadable, RejectsAPointerPastWhatWasRead) EXPECT_FALSE(gcr_track_header_is_readable(8192, 4096)); EXPECT_FALSE(gcr_track_header_is_readable(0xFFFFFFFFu, 4096)); } + +// ------------------------------------------------------------- problems 1+3 -- + +TEST(TrackParameters, ProgramsARealTrackFromItsOwnLength) +{ + uint32_t address = 0, param = 0; + gcr_track_parameters(0x00800000, 0x1E0C, 0x00900000, kDummyLen, kRotationSpeed, + &address, ¶m); + EXPECT_EQ(address, 0x00800000u); + EXPECT_EQ(param & 0xFFFFu, 0x1E0Bu); // last valid offset + EXPECT_EQ(param >> 16, kRotationSpeed / 0x1E0C); // bit time +} + +TEST(TrackParameters, GivesAnAbsentTrackTheDummyAndASafeLength) +{ + // Problem 1: before the fix the else branch read two locals that the if + // branch had never written, so the first track of an image whose tracks + // are all absent programmed dummy_track with whatever was on the stack. + uint32_t address = 0, param = 0; + gcr_track_parameters(0, 0, 0x00900000, kDummyLen, kRotationSpeed, &address, ¶m); + EXPECT_EQ(address, 0x00900000u); + EXPECT_EQ(param & 0xFFFFu, (uint32_t)GCR_EMPTY_TRACK_PARAM); + EXPECT_EQ(param >> 16, kRotationSpeed / (uint32_t)kDummyLen); +} + +TEST(TrackParameters, DoesNotCarryTheNeighbourLengthIntoAnAbsentTrack) +{ + // Problem 3: add_blank_tracks() fills only even indices, so every odd one + // takes the absent path on every image. It used to be handed the dummy + // track's address together with the length left behind by the preceding + // track, a pairing that is safe only because the longest entry in + // track_lengths[] happens to equal GCRIMAGE_DUMMYTRACKLEN exactly. + // + // What has to hold is that the absent case does not depend on what came + // before it. So: program a long real track, then an absent one, and + // require the same answer as an absent track programmed on its own. + uint32_t alone_address = 0, alone_param = 0; + gcr_track_parameters(0, 0, 0x00900000, kDummyLen, kRotationSpeed, + &alone_address, &alone_param); + + uint32_t address = 0, param = 0; + gcr_track_parameters(0x00800000, kMaxTrackLen, 0x00900000, kDummyLen, kRotationSpeed, + &address, ¶m); + gcr_track_parameters(0, 0, 0x00900000, kDummyLen, kRotationSpeed, &address, ¶m); + + EXPECT_EQ(address, alone_address); + EXPECT_EQ(param, alone_param); + EXPECT_TRUE((int)((param & 0xFFFFu) + 1) <= kDummyLen); +} + +TEST(TrackParameters, TreatsAZeroLengthTrackAsAbsent) +{ + // Problem 4 again, one layer down: an address with a zero length must not + // reach the division either. + uint32_t address = 0, param = 0; + gcr_track_parameters(0x00800000, 0, 0x00900000, kDummyLen, kRotationSpeed, + &address, ¶m); + EXPECT_EQ(address, 0x00900000u); + EXPECT_EQ(param & 0xFFFFu, (uint32_t)GCR_EMPTY_TRACK_PARAM); +} + +TEST(TrackParameters, TreatsANegativeLengthAsAbsent) +{ + uint32_t address = 0, param = 0; + gcr_track_parameters(0x00800000, -1, 0x00900000, kDummyLen, kRotationSpeed, + &address, ¶m); + EXPECT_EQ(address, 0x00900000u); +} From b1e604097b9207c2e44292093e395ac2dcbfe800 Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Wed, 16 Sep 2026 03:21:13 +0200 Subject: [PATCH 006/514] Bound a G64 track by what the file delivered, not by the buffer The first version of this fix compared a declared track length against GCRIMAGE_MAXSIZE, so a track only had to fit the allocation. It did not have to be in the file. A 14 byte GCR-1541 image whose track 0 points at offset 12 and declares 0x1E0C passed both the header check and the length check, and then gcr_data+14 through gcr_data+7705 were programmed into the drive engine -- bytes no read ever wrote, holding whatever the previous mount left behind, since the buffer is zeroed at allocation and not between images. gcr_validated_track_length() now takes bytes_read instead of the capacity and requires offset + 2 + length <= bytes_read, written as subtractions so nothing can wrap, and load() passes what f->read() reported. Since bytes_read never exceeds GCRIMAGE_MAXSIZE, this is strictly the stronger bound and the buffer cases the earlier tests pin down still hold. Five cases added under TruncatedImage, including the reported 14 byte file. Against this commit the suite is 23 green; against a header restored to the capacity bound, 4 of the 5 fail -- the fifth is the positive boundary, a track ending exactly where the file does, which must stay accepted either way. Reported by @chrisgleissner in review of GideonZ/1541ultimate#840. --- software/drive/disk_image.cc | 4 +- software/drive/gcr_track_bounds.h | 20 ++++--- .../drive/tests/gcr_track_bounds_test.cpp | 52 +++++++++++++++++++ 3 files changed, 67 insertions(+), 9 deletions(-) diff --git a/software/drive/disk_image.cc b/software/drive/disk_image.cc index f20aeccef..d56230984 100644 --- a/software/drive/disk_image.cc +++ b/software/drive/disk_image.cc @@ -722,9 +722,9 @@ bool GcrImage :: load(File *f) } tr = gcr_data + offset; w = tr[0] | (uint16_t(tr[1]) << 8); - int length = gcr_validated_track_length(w, offset, GCRIMAGE_MAXSIZE, GCRIMAGE_MAXTRACKLEN); + int length = gcr_validated_track_length(w, offset, bytes_read, GCRIMAGE_MAXTRACKLEN); if(!length) { - printf("Track %d: declared length %d does not fit the image. Track skipped.\n", + printf("Track %d: declared length %d was not delivered by the file. Track skipped.\n", i, (int)(w & 0x3FFF)); continue; // invalidate() left this entry unused; leave it that way } diff --git a/software/drive/gcr_track_bounds.h b/software/drive/gcr_track_bounds.h index 45f00f1d3..c1bc06e7c 100644 --- a/software/drive/gcr_track_bounds.h +++ b/software/drive/gcr_track_bounds.h @@ -38,25 +38,31 @@ static inline bool gcr_track_header_is_readable(uint32_t offset, uint32_t bytes_ * * declared the 16-bit word from the image, flag bits included * offset byte offset of that word within the buffer - * capacity size of the buffer + * bytes_read how much of the buffer the file actually filled * max_length longest track the format allows * - * The masked field holds 14 bits, so it admits lengths more than twice the - * longest legitimate track, and a track near the end of the buffer can declare - * a length that runs off it. Both are rejected here rather than programmed. + * The bound is what was read, not how large the buffer is. A truncated image + * can declare a track whose header is present but whose data never arrived, + * and the buffer behind it holds whatever the previous mount left there. So + * the whole track, header word included, has to lie inside what was read: + * offset + 2 + length <= bytes_read, written as subtractions so that no sum + * can wrap. + * + * The masked field holds 14 bits, so it also admits lengths more than twice + * the longest legitimate track. Rejected here rather than programmed. */ static inline int gcr_validated_track_length(uint16_t declared, uint32_t offset, - uint32_t capacity, int max_length) + uint32_t bytes_read, int max_length) { int length = (int)(declared & 0x3FFF); if (length <= 0 || length > max_length) { return 0; /* zero would also divide by zero in insert_disk() */ } - if (offset > capacity || (capacity - offset) < 2) { + if (offset > bytes_read || (bytes_read - offset) < 2) { return 0; } - if ((uint32_t)length > (capacity - offset - 2)) { + if ((uint32_t)length > (bytes_read - offset - 2)) { return 0; } return length; diff --git a/software/drive/tests/gcr_track_bounds_test.cpp b/software/drive/tests/gcr_track_bounds_test.cpp index 3b90c95e3..bedafbccf 100644 --- a/software/drive/tests/gcr_track_bounds_test.cpp +++ b/software/drive/tests/gcr_track_bounds_test.cpp @@ -8,6 +8,10 @@ // 2. track length never validated against the buffer -> ValidatedLength // 3. half-tracks inherit the previous track's length -> TrackParameters // 4. divide by zero on a zero-length track -> ValidatedLength +// +// And what checking the buffer alone still let through, found in review of the +// first fix: a truncated file whose track header arrived but whose track data +// did not -> TruncatedImage. #include "../../io/usb/tests/host_test/host_test.h" #include "../gcr_track_bounds.h" @@ -23,6 +27,11 @@ const uint32_t kRotationSpeed = 50000000 / 20; // CLOCK_FREQ } // namespace // ---------------------------------------------------------------- problem 2 -- +// +// The third argument is how much of the buffer the file filled. Passing +// kMaxSize here models an image that filled it completely, which is what the +// buffer-overrun cases below are about; the truncated cases further down pass +// the smaller number a short file leaves behind. TEST(ValidatedLength, AcceptsALegitimateTrack) { @@ -75,6 +84,49 @@ TEST(ValidatedLength, SurvivesAnOffsetPastTheBuffer) EXPECT_EQ(gcr_validated_track_length(0x1E0C, kMaxSize - 1, kMaxSize, kMaxTrackLen), 0); } +// ------------------------------------------------------------ truncation -- +// +// Reported by @chrisgleissner against the first version of this fix, which +// bounded the track by the size of the buffer rather than by what the file +// delivered. The buffer is not zeroed between mounts, so what lies past the +// end of a short file is the previous image. + +TEST(TruncatedImage, RejectsATrackWhoseDataNeverArrived) +{ + // The reported case, exactly: a 14-byte GCR-1541 file. Track 0 points at + // offset 12, the two length bytes are there, and they declare a full + // 0x1E0C track. Against the buffer this passes; against the file it must + // not, or gcr_data+14 .. gcr_data+7705 go to the drive unread. + EXPECT_EQ(gcr_validated_track_length(0x1E0C, 12, 14, kMaxTrackLen), 0); +} + +TEST(TruncatedImage, RejectsATrackCutShortByOneByte) +{ + const uint32_t bytes_read = 12 + 2 + 0x1E0C - 1; + EXPECT_EQ(gcr_validated_track_length(0x1E0C, 12, bytes_read, kMaxTrackLen), 0); +} + +TEST(TruncatedImage, AcceptsATrackEndingExactlyWhereTheFileDoes) +{ + const uint32_t bytes_read = 12 + 2 + 0x1E0C; + EXPECT_EQ(gcr_validated_track_length(0x1E0C, 12, bytes_read, kMaxTrackLen), 0x1E0C); +} + +TEST(TruncatedImage, DoesNotCareHowLargeTheBufferIs) +{ + // Same track, same short file. The only difference between these two calls + // used to be the answer: the buffer was the bound, so the whole image was + // judged by memory that had nothing to do with it. + EXPECT_EQ(gcr_validated_track_length(0x1E0C, 12, kMaxSize, kMaxTrackLen), 0x1E0C); + EXPECT_EQ(gcr_validated_track_length(0x1E0C, 12, 14, kMaxTrackLen), 0); +} + +TEST(TruncatedImage, SurvivesAnEmptyRead) +{ + EXPECT_EQ(gcr_validated_track_length(0x1E0C, 12, 0, kMaxTrackLen), 0); + EXPECT_EQ(gcr_validated_track_length(0x1E0C, 0, 0, kMaxTrackLen), 0); +} + // ---------------------------------------------------------------- problem 4 -- TEST(ValidatedLength, RejectsAZeroLengthTrack) From 3e37859d1cde2204b8bcd0c2dbabb6490432f8c0 Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Thu, 3 Sep 2026 21:48:53 +0200 Subject: [PATCH 007/514] Release the USB mutex when a setup packet is the wrong length control_exchange() takes the mutex on entry and gives it back on every path out except one: a setup length other than 8 returns -10 while still holding it. Every later USB operation would then wait its full five seconds and fail, which on this device means the keyboard, mass storage and the Ethernet adapter all stop at once. Latent today, because no caller passes anything but 8. Found by reading, in the sweep in GideonZ/1541ultimate#822, problem 5. --- software/io/usb/usb_base.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/software/io/usb/usb_base.cc b/software/io/usb/usb_base.cc index 625a7220c..b39d71ec9 100644 --- a/software/io/usb/usb_base.cc +++ b/software/io/usb/usb_base.cc @@ -567,6 +567,7 @@ int UsbBase :: control_exchange(struct t_pipe *pipe, void *out, int outlen, void if (outlen != 8) { printf("%s Unsupported setup length.\n", pipe->name); + xSemaphoreGive(mutex); return -10; } From 937b9c47c71325eaf58819259a5eb67e9f8da76c Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Thu, 3 Sep 2026 21:49:45 +0200 Subject: [PATCH 008/514] Pad a short Ethernet frame, not just the number sent to the engine output_packet() wrote the Ethernet minimum into the length register but left the buffer alone: RMII_TX_LENGTH = (uint16_t)((pkt_len < 60)?60:pkt_len); The engine transmits as many bytes as that register names, so for a 42 byte ARP request it read 18 bytes past the frame and put them on the wire. Nothing is corrupted -- the transmit path only reads -- but those bytes leave the device, and with MEM_LIBC_MALLOC set the pbufs come from pvPortMalloc, so what goes out is the neighbouring heap block. Every ARP request the device sends does this. Short frames are now copied into a buffer this driver owns and zero filled to 60 there. Transmission is asynchronous, but the RMII_TX_BUSY test at the top of the function means the previous frame has left before that buffer is written again. Frames of 60 bytes or more are transmitted from the caller's buffer as before, so the copy costs nothing on the traffic that matters. Reported in GideonZ/1541ultimate#822, problem 4. --- software/io/network/rmii_interface.cc | 28 ++++++++++++++++++++++++++- software/io/network/rmii_interface.h | 1 + 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/software/io/network/rmii_interface.cc b/software/io/network/rmii_interface.cc index e1acd06ac..b15cef4ed 100644 --- a/software/io/network/rmii_interface.cc +++ b/software/io/network/rmii_interface.cc @@ -15,6 +15,9 @@ #define ENABLE_PCAP 0 #define NUM_BUFFERS 32 +// Ethernet's shortest legal frame on the wire, excluding the FCS. +#define ETH_MIN_FRAME_LEN 60 + static uint8_t freemap[NUM_BUFFERS]; static int freecnt; @@ -47,11 +50,13 @@ extern "C" { RmiiInterface :: RmiiInterface() { rmii_interface = this; + tx_pad_buffer = NULL; if(getFpgaCapabilities() & CAPAB_ETH_RMII) { netstack = getNetworkStack(this, RmiiInterface_output, RmiiInterface_free_buffer); link_up = false; ram_buffer = new uint8_t[(NUM_BUFFERS * 1536) + 256]; ram_base = (uint8_t *) (((uint32_t)ram_buffer + 255) & 0xFFFFFF00); + tx_pad_buffer = new uint8_t[ETH_MIN_FRAME_LEN]; RMII_FREE_BASE = (uint32_t)ram_base; @@ -192,6 +197,9 @@ RmiiInterface :: ~RmiiInterface() if(ram_buffer) { delete ram_buffer; } + if(tx_pad_buffer) { + delete[] tx_pad_buffer; + } if(netstack) { netstack->stop(); releaseNetworkStack(netstack); @@ -315,8 +323,26 @@ err_t RmiiInterface :: output_packet(uint8_t *buffer, int pkt_len) #endif //printf("Rmii Out Packet: %p %4x\n", buffer, pkt_len); //dump_hex_relative(buffer, (pkt_len > 64)?64:pkt_len); + // The engine transmits as many bytes as the length register names, and + // Ethernet's minimum frame is 60. Padding only the length made it read past + // a short frame and put whatever follows it in memory on the wire; with + // MEM_LIBC_MALLOC the pbufs come from pvPortMalloc, so that is the + // neighbouring heap block. A 42 byte ARP request leaked 18 such bytes. + // Pad the data as well, in a buffer this driver owns. Transmission is + // asynchronous, but the RMII_TX_BUSY test above means the previous frame + // has left before this buffer is filled again. + if (pkt_len < ETH_MIN_FRAME_LEN) { + if (pkt_len < 0) { + return ERR_ARG; + } + memcpy(tx_pad_buffer, buffer, pkt_len); + memset(tx_pad_buffer + pkt_len, 0, ETH_MIN_FRAME_LEN - pkt_len); + buffer = tx_pad_buffer; + pkt_len = ETH_MIN_FRAME_LEN; + } + RMII_TX_ADDRESS = (uint32_t)buffer; - RMII_TX_LENGTH = (uint16_t)((pkt_len < 60)?60:pkt_len); + RMII_TX_LENGTH = (uint16_t)pkt_len; RMII_TX_START = 1; return ERR_OK; diff --git a/software/io/network/rmii_interface.h b/software/io/network/rmii_interface.h index 0b622c3e0..6bf9e6393 100644 --- a/software/io/network/rmii_interface.h +++ b/software/io/network/rmii_interface.h @@ -38,6 +38,7 @@ class RmiiInterface NetworkInterface *netstack; uint8_t *ram_buffer; uint8_t *ram_base; + uint8_t *tx_pad_buffer; bool link_up; uint8_t addr; uint8_t local_mac[6]; From 7d64c70d04b09acf78776dd731660d7109f87ef1 Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Thu, 3 Sep 2026 21:50:26 +0200 Subject: [PATCH 009/514] Build the AX88772 length header in a buffer this driver owns output_packet() wrote the adapter's four byte length header in front of the buffer it was handed: uint8_t *size = buffer - 4; That holds for a buffer from this driver's own receive pool, because the receive path gives the stack usb_buffer + 4 and keeps those four bytes as headroom. Neither buffer the stack supplies on transmit has any. lwip_output_callback() passes a static uint8_t[1536] for a chained pbuf, so the write lands in whatever precedes that array in .bss, and pbuf->payload for a single one, where ETH_PAD_SIZE is 0 and PBUF_LINK_ENCAPSULATION_HLEN is left at its default of 0, so it lands in the pbuf's own metadata or the neighbouring pool entry. It is a plain CPU write, so no DMA behaviour is needed to trigger it, and where it lands depends on the link order. Header and frame are now assembled in a driver-owned buffer. bulk_out() holds the USB mutex until the transfer has completed, so one buffer is enough. The length is checked against it rather than trusted. Incidentally that buffer comes from the allocator, so what reaches bulk_out() is word aligned, which the two stack buffers were not required to be. Reported in GideonZ/1541ultimate#822, problem 1. --- software/io/usb/usb_ax88772.cc | 31 +++++++++++++++++++++++++------ software/io/usb/usb_ax88772.h | 7 +++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/software/io/usb/usb_ax88772.cc b/software/io/usb/usb_ax88772.cc index 80a820553..716d273fa 100644 --- a/software/io/usb/usb_ax88772.cc +++ b/software/io/usb/usb_ax88772.cc @@ -102,6 +102,10 @@ UsbAx88772Driver :: UsbAx88772Driver(UsbInterface *intf, uint16_t prodID) : UsbD this->prodID = prodID; dataBuffersBlock = new uint8_t[1536 * NUM_AX_BUFFERS]; + // Reached through BIT31 like the receive pool, so that it lands in + // uncached space on any target that turns the data cache on. + txBufferBlock = new uint8_t[AX_HEADER_LEN + AX_MAX_PACKET_LEN]; + txBuffer = &txBufferBlock[BIT31]; for (int i=0; i < NUM_AX_BUFFERS; i++) { freeBuffers.push(&dataBuffersBlock[BIT31 + 1536 * i]); // set bit 31, so that it is non-cacheable @@ -113,6 +117,7 @@ UsbAx88772Driver :: ~UsbAx88772Driver() if(netstack) releaseNetworkStack(netstack); delete[] dataBuffersBlock; + delete[] txBufferBlock; } UsbDriver * UsbAx88772Driver :: test_driver(UsbInterface *intf) @@ -604,13 +609,27 @@ err_t UsbAx88772Driver :: output_packet(uint8_t *buffer, int pkt_len) return ERR_CONN; //dump_hex(buffer, 32); - uint8_t *size = buffer - 4; - size[0] = uint8_t(pkt_len & 0xFF); - size[1] = uint8_t(pkt_len >> 8); - size[2] = size[0] ^ 0xFF; - size[3] = size[1] ^ 0xFF; + if ((pkt_len < 0) || (pkt_len > AX_MAX_PACKET_LEN)) { + return ERR_ARG; + } - host->bulk_out(&bulk_out_pipe, size, pkt_len + 4); + // The adapter wants a four byte length header immediately in front of the + // frame. Writing it at buffer - 4 only works for a buffer that came back + // from this driver's own receive pool, which keeps four bytes of headroom + // because the receive path hands the stack usb_buffer + 4. Neither buffer + // the stack supplies on transmit has any: the chained-pbuf path passes a + // static array, so the write lands in whatever precedes it in .bss, and the + // single-pbuf path passes pbuf->payload, where ETH_PAD_SIZE is 0 and + // PBUF_LINK_ENCAPSULATION_HLEN is left at its default, so it lands in the + // pbuf's own metadata or the neighbouring pool entry. Assemble header and + // frame in a buffer this driver owns instead. + txBuffer[0] = uint8_t(pkt_len & 0xFF); + txBuffer[1] = uint8_t(pkt_len >> 8); + txBuffer[2] = txBuffer[0] ^ 0xFF; + txBuffer[3] = txBuffer[1] ^ 0xFF; + memcpy(txBuffer + AX_HEADER_LEN, buffer, pkt_len); + + host->bulk_out(&bulk_out_pipe, txBuffer, pkt_len + AX_HEADER_LEN); return ERR_OK; } diff --git a/software/io/usb/usb_ax88772.h b/software/io/usb/usb_ax88772.h index 1045fcc5a..f56eb4d36 100644 --- a/software/io/usb/usb_ax88772.h +++ b/software/io/usb/usb_ax88772.h @@ -8,6 +8,11 @@ #define NUM_AX_BUFFERS 64 +// The adapter prefixes every frame it is given with a four byte length +// header. 1536 is the buffer size the receive pool uses. +#define AX_HEADER_LEN 4 +#define AX_MAX_PACKET_LEN 1536 + class UsbAx88772Driver : public UsbDriver { int irq_transaction; @@ -23,6 +28,8 @@ class UsbAx88772Driver : public UsbDriver Fifo freeBuffers; uint8_t *dataBuffersBlock; + uint8_t *txBufferBlock; + uint8_t *txBuffer; UsbBase *host; UsbDevice *device; From aa7d7b1564bf2d14b12fa6664b9dd7c5914e4b21 Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Thu, 3 Sep 2026 22:22:34 +0200 Subject: [PATCH 010/514] Free the RMII receive block with delete[] `ram_buffer` is `new uint8_t[(NUM_BUFFERS * 1536) + 256]` and was released with plain `delete`, which is undefined behaviour for an array. Noticed only because the previous change puts a correct `delete[]` on the line below it. Nothing to do with GideonZ/1541ultimate#822; it is a one word correction in a destructor that this branch already touches. --- software/io/network/rmii_interface.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/software/io/network/rmii_interface.cc b/software/io/network/rmii_interface.cc index b15cef4ed..065268579 100644 --- a/software/io/network/rmii_interface.cc +++ b/software/io/network/rmii_interface.cc @@ -195,7 +195,7 @@ void RmiiInterface :: rmiiTask(void) RmiiInterface :: ~RmiiInterface() { if(ram_buffer) { - delete ram_buffer; + delete[] ram_buffer; } if(tx_pad_buffer) { delete[] tx_pad_buffer; From 6a15ed2a6c65a5f5a4602b46a599f0376393e041 Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Wed, 16 Sep 2026 03:54:32 +0200 Subject: [PATCH 011/514] Pin the transmit framing decisions with host tests Both fixes in this PR are about what leaves the device, and neither could be checked anywhere but on the machine, because the decision lived inline in a driver method that only builds for the target. Lift the two decisions into free functions over plain integers, the way software/drive/gcr_track_bounds.h does it, and pin them down on a build host. eth_tx_frame_to_send() chooses the buffer and length to transmit: a frame of 60 bytes or more goes out of the caller's buffer untouched, a shorter one is copied into the driver's pad buffer and zero filled. ax88772_tx_block() assembles the four byte length header and the frame in the driver's own buffer and returns how much to send, or -1 for a frame that does not fit. The tests state the property rather than the implementation: fill the memory around the frame with a sentinel byte, then require that no sentinel is inside what the function says to transmit. That is exactly the leak -- 18 bytes of the neighbouring heap block on every 42 byte ARP request -- and it is checked for every short length from 0 to 59. The AX88772 case guards the eight bytes in front of both buffers, since the header used to be written in front of the one the network stack owns. Ten cases, wired into the build workflow next to the UCI palette test. Against this commit all ten pass. Against a header restored to the two pre-fix behaviours -- pad the length but not the data, and write the header at frame - 4 -- nine of the ten fail; the tenth is the path that does not change, a frame of 60 bytes or more transmitted from the caller's buffer. Still not covered here, and still needing the machine: the sentinel word in front of the driver's transmit buffer on a live system, and an ARP capture off the LAN showing the padding bytes are zero. --- .github/workflows/build.yml | 6 + software/io/network/eth_tx_frame.h | 86 ++++++++ software/io/network/rmii_interface.cc | 14 +- software/io/network/tests/Makefile | 15 ++ .../io/network/tests/eth_tx_frame_test.cpp | 205 ++++++++++++++++++ software/io/usb/usb_ax88772.cc | 16 +- software/io/usb/usb_ax88772.h | 5 +- 7 files changed, 325 insertions(+), 22 deletions(-) create mode 100644 software/io/network/eth_tx_frame.h create mode 100644 software/io/network/tests/Makefile create mode 100644 software/io/network/tests/eth_tx_frame_test.cpp diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index afdefbc3d..5375d6f65 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -123,6 +123,12 @@ jobs: -v /opt/build-tools:/mnt/build-tools:ro \ -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -B -C target/pc/linux/test_http_target test-body-removal" + - name: Test Ethernet Transmit Framing + run: | + docker run --rm \ + -v /opt/build-tools:/mnt/build-tools:ro \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -C software/io/network/tests" + - name: Cache U2 FPGA id: cache-u2 uses: actions/cache@v6 diff --git a/software/io/network/eth_tx_frame.h b/software/io/network/eth_tx_frame.h new file mode 100644 index 000000000..f5f532a77 --- /dev/null +++ b/software/io/network/eth_tx_frame.h @@ -0,0 +1,86 @@ +/* + * eth_tx_frame.h -- what a driver hands the hardware on transmit, checked. + * + * Two transmit paths take a buffer from the network stack and have to give the + * hardware something else: the RMII engine sends exactly as many bytes as its + * length register names, so a frame shorter than Ethernet's 60 byte minimum has + * to be padded in memory and not only in the number, and the AX88772 wants a + * four byte length header immediately in front of the frame, which cannot be + * written in front of a buffer the stack owns. + * + * Both were getting that wrong by reaching outside the caller's buffer. The + * decisions are free functions over plain integers so they can be pinned down + * on a build host; see software/io/network/tests/. + */ +#ifndef IO_NETWORK_ETH_TX_FRAME_H +#define IO_NETWORK_ETH_TX_FRAME_H + +#include +#include + +/* Ethernet's shortest legal frame on the wire, excluding the FCS. */ +#define ETH_MIN_FRAME_LEN 60 + +/* The AX88772 prefixes every frame with a four byte length header. */ +#define AX_HEADER_LEN 4 + +/* Chooses the buffer and length to transmit. + * + * A frame of ETH_MIN_FRAME_LEN or more goes out of the caller's buffer + * untouched, which is every frame carrying real payload. A shorter one is + * copied into pad and zero filled to the minimum, because padding the length + * alone makes the engine read past the frame and put whatever follows it in + * memory on the wire -- an ARP request is 42 bytes, so 18 bytes of the + * neighbouring heap block left the device on every one of them. + * + * Returns false when the frame cannot be transmitted at all, in which case + * neither output is written. + */ +static inline bool eth_tx_frame_to_send(uint8_t *frame, int pkt_len, + uint8_t *pad, int pad_size, + uint8_t **out_frame, int *out_len) +{ + if (frame == NULL || pkt_len < 0) { + return false; + } + if (pkt_len >= ETH_MIN_FRAME_LEN) { + *out_frame = frame; + *out_len = pkt_len; + return true; + } + if (pad == NULL || pad_size < ETH_MIN_FRAME_LEN) { + return false; + } + memcpy(pad, frame, (size_t)pkt_len); + memset(pad + pkt_len, 0, (size_t)(ETH_MIN_FRAME_LEN - pkt_len)); + *out_frame = pad; + *out_len = ETH_MIN_FRAME_LEN; + return true; +} + +/* Assembles the AX88772 length header and the frame in a buffer the driver + * owns, and returns how many bytes to send, or -1 when the frame does not fit. + * + * The header used to be written at frame - 4. That is only inside an + * allocation for a buffer from this driver's own receive pool; the buffers the + * stack supplies on transmit have no headroom, so the write landed in whatever + * preceded them. + */ +static inline int ax88772_tx_block(const uint8_t *frame, int pkt_len, + uint8_t *tx, int tx_size) +{ + if (frame == NULL || tx == NULL || pkt_len < 0) { + return -1; + } + if (tx_size < AX_HEADER_LEN || pkt_len > (tx_size - AX_HEADER_LEN)) { + return -1; + } + tx[0] = (uint8_t)(pkt_len & 0xFF); + tx[1] = (uint8_t)((pkt_len >> 8) & 0xFF); + tx[2] = (uint8_t)(tx[0] ^ 0xFF); + tx[3] = (uint8_t)(tx[1] ^ 0xFF); + memcpy(tx + AX_HEADER_LEN, frame, (size_t)pkt_len); + return pkt_len + AX_HEADER_LEN; +} + +#endif /* IO_NETWORK_ETH_TX_FRAME_H */ diff --git a/software/io/network/rmii_interface.cc b/software/io/network/rmii_interface.cc index 065268579..5bfdeac6b 100644 --- a/software/io/network/rmii_interface.cc +++ b/software/io/network/rmii_interface.cc @@ -15,8 +15,7 @@ #define ENABLE_PCAP 0 #define NUM_BUFFERS 32 -// Ethernet's shortest legal frame on the wire, excluding the FCS. -#define ETH_MIN_FRAME_LEN 60 +#include "eth_tx_frame.h" static uint8_t freemap[NUM_BUFFERS]; static int freecnt; @@ -331,14 +330,9 @@ err_t RmiiInterface :: output_packet(uint8_t *buffer, int pkt_len) // Pad the data as well, in a buffer this driver owns. Transmission is // asynchronous, but the RMII_TX_BUSY test above means the previous frame // has left before this buffer is filled again. - if (pkt_len < ETH_MIN_FRAME_LEN) { - if (pkt_len < 0) { - return ERR_ARG; - } - memcpy(tx_pad_buffer, buffer, pkt_len); - memset(tx_pad_buffer + pkt_len, 0, ETH_MIN_FRAME_LEN - pkt_len); - buffer = tx_pad_buffer; - pkt_len = ETH_MIN_FRAME_LEN; + if (!eth_tx_frame_to_send(buffer, pkt_len, tx_pad_buffer, ETH_MIN_FRAME_LEN, + &buffer, &pkt_len)) { + return ERR_ARG; } RMII_TX_ADDRESS = (uint32_t)buffer; diff --git a/software/io/network/tests/Makefile b/software/io/network/tests/Makefile new file mode 100644 index 000000000..dbbaf472c --- /dev/null +++ b/software/io/network/tests/Makefile @@ -0,0 +1,15 @@ +CXX ?= g++ +CXXFLAGS := -std=c++14 -g -Wall -Wextra -I. -I.. -I../../usb/tests +OUTPUT_DIR := output +ETH_TX_FRAME_TEST := $(OUTPUT_DIR)/ethTxFrameTest + +.PHONY: all eth-tx-frame clean + +all: eth-tx-frame + +eth-tx-frame: + mkdir -p $(OUTPUT_DIR) + $(CXX) $(CXXFLAGS) eth_tx_frame_test.cpp ../../usb/tests/host_test_main.cpp -lpthread -o $(ETH_TX_FRAME_TEST) && $(ETH_TX_FRAME_TEST) + +clean: + rm -rf $(OUTPUT_DIR) diff --git a/software/io/network/tests/eth_tx_frame_test.cpp b/software/io/network/tests/eth_tx_frame_test.cpp new file mode 100644 index 000000000..ba3bbce13 --- /dev/null +++ b/software/io/network/tests/eth_tx_frame_test.cpp @@ -0,0 +1,205 @@ +// Regression tests for GideonZ/1541ultimate#822: two transmit paths reached +// outside the buffer the network stack gave them. +// +// problem 1 the AX88772 length header was written at buffer - 4, which is +// inside the allocation only for this driver's own receive +// buffers -> Ax88772TxBlock +// problem 4 a frame shorter than 60 bytes was padded in the length register +// but not in memory, so the engine read past it and sent what it +// found -- 18 bytes of the neighbouring heap block on every ARP +// request -> ShortFrame +// +// Both are about what leaves the device, so the checks here are written the +// same way: fill the memory around the frame with a sentinel, then require +// that no sentinel byte is inside what the function says to transmit. + +#include "../../usb/tests/host_test/host_test.h" +#include "../eth_tx_frame.h" + +namespace { + +const uint8_t kSentinel = 0xA5; // what "not ours" looks like +const int kArpFrameLen = 42; // an ARP request on the wire +const int kMaxFrameLen = 1514; // Ethernet MTU 1500 plus the header + +// A caller buffer with the frame at the front and neighbouring memory behind +// it, exactly the shape the leak needs. +struct CallerBuffer { + uint8_t bytes[256]; + + explicit CallerBuffer(int frame_len) + { + memset(bytes, kSentinel, sizeof(bytes)); + for (int i = 0; i < frame_len; i++) { + bytes[i] = (uint8_t)(0x10 + i); // recognisable, never the sentinel + } + } +}; + +bool contains_sentinel(const uint8_t *p, int len) +{ + for (int i = 0; i < len; i++) { + if (p[i] == kSentinel) { + return true; + } + } + return false; +} + +} // namespace + +// ---------------------------------------------------------------- problem 4 -- + +TEST(ShortFrame, SendsALongFrameFromTheCallersBufferUntouched) +{ + CallerBuffer caller(ETH_MIN_FRAME_LEN); + uint8_t pad[ETH_MIN_FRAME_LEN]; + memset(pad, 0, sizeof(pad)); + + uint8_t *out = NULL; + int out_len = 0; + EXPECT_TRUE(eth_tx_frame_to_send(caller.bytes, ETH_MIN_FRAME_LEN, pad, sizeof(pad), + &out, &out_len)); + EXPECT_EQ(out, caller.bytes); // no copy on the path that carries payload + EXPECT_EQ(out_len, ETH_MIN_FRAME_LEN); +} + +TEST(ShortFrame, PadsAnArpRequestWithZeroAndNotWithTheNeighbour) +{ + CallerBuffer caller(kArpFrameLen); + uint8_t pad[ETH_MIN_FRAME_LEN]; + memset(pad, kSentinel, sizeof(pad)); // the pad buffer is dirty too + + uint8_t *out = NULL; + int out_len = 0; + EXPECT_TRUE(eth_tx_frame_to_send(caller.bytes, kArpFrameLen, pad, sizeof(pad), + &out, &out_len)); + EXPECT_EQ(out_len, ETH_MIN_FRAME_LEN); + EXPECT_EQ(memcmp(out, caller.bytes, kArpFrameLen), 0); + + // The 18 bytes that used to be the neighbouring heap block. + for (int i = kArpFrameLen; i < ETH_MIN_FRAME_LEN; i++) { + EXPECT_EQ((int)out[i], 0); + } +} + +TEST(ShortFrame, NothingBehindTheFrameEverLeavesTheDevice) +{ + // The property, stated once for every short length: what is transmitted + // may not contain a byte the caller did not put in the frame. + for (int len = 0; len < ETH_MIN_FRAME_LEN; len++) { + CallerBuffer caller(len); + uint8_t pad[ETH_MIN_FRAME_LEN]; + memset(pad, kSentinel, sizeof(pad)); + + uint8_t *out = NULL; + int out_len = 0; + EXPECT_TRUE(eth_tx_frame_to_send(caller.bytes, len, pad, sizeof(pad), + &out, &out_len)); + EXPECT_EQ(out_len, ETH_MIN_FRAME_LEN); + EXPECT_FALSE(contains_sentinel(out, out_len)); + } +} + +TEST(ShortFrame, KeepsTheBoundaryWhereEthernetPutsIt) +{ + CallerBuffer caller(ETH_MIN_FRAME_LEN); + uint8_t pad[ETH_MIN_FRAME_LEN]; + uint8_t *out = NULL; + int out_len = 0; + + // 59 is copied, 60 is not. + EXPECT_TRUE(eth_tx_frame_to_send(caller.bytes, 59, pad, sizeof(pad), &out, &out_len)); + EXPECT_EQ(out, pad); + EXPECT_TRUE(eth_tx_frame_to_send(caller.bytes, 60, pad, sizeof(pad), &out, &out_len)); + EXPECT_EQ(out, caller.bytes); +} + +TEST(ShortFrame, RefusesWhatItCannotPad) +{ + CallerBuffer caller(kArpFrameLen); + uint8_t pad[ETH_MIN_FRAME_LEN]; + uint8_t *out = NULL; + int out_len = 0; + + EXPECT_FALSE(eth_tx_frame_to_send(caller.bytes, -1, pad, sizeof(pad), &out, &out_len)); + EXPECT_FALSE(eth_tx_frame_to_send(NULL, kArpFrameLen, pad, sizeof(pad), &out, &out_len)); + EXPECT_FALSE(eth_tx_frame_to_send(caller.bytes, kArpFrameLen, pad, ETH_MIN_FRAME_LEN - 1, + &out, &out_len)); + EXPECT_FALSE(eth_tx_frame_to_send(caller.bytes, kArpFrameLen, NULL, ETH_MIN_FRAME_LEN, + &out, &out_len)); +} + +// ---------------------------------------------------------------- problem 1 -- + +TEST(Ax88772TxBlock, WritesTheHeaderInFrontOfTheFrameInTheDriversOwnBuffer) +{ + CallerBuffer caller(kArpFrameLen); + uint8_t tx[AX_HEADER_LEN + 1536]; + + const int sent = ax88772_tx_block(caller.bytes, kArpFrameLen, tx, sizeof(tx)); + EXPECT_EQ(sent, kArpFrameLen + AX_HEADER_LEN); + EXPECT_EQ((int)tx[0], kArpFrameLen); + EXPECT_EQ((int)tx[1], 0); + EXPECT_EQ((int)tx[2], kArpFrameLen ^ 0xFF); + EXPECT_EQ((int)tx[3], 0xFF); + EXPECT_EQ(memcmp(tx + AX_HEADER_LEN, caller.bytes, kArpFrameLen), 0); +} + +TEST(Ax88772TxBlock, WritesNothingInFrontOfEitherBuffer) +{ + // The defect itself: the header used to go to buffer - 4, where buffer is + // the frame the network stack owns. So both are guarded here -- the eight + // bytes in front of the frame, which is where the header used to land, and + // the eight in front of the destination. + uint8_t src_block[8 + kMaxFrameLen]; + memset(src_block, kSentinel, sizeof(src_block)); + uint8_t *frame = src_block + 8; + memset(frame, 0x5A, kMaxFrameLen); + + uint8_t dst_block[8 + AX_HEADER_LEN + 1536]; + memset(dst_block, kSentinel, sizeof(dst_block)); + uint8_t *tx = dst_block + 8; + + EXPECT_EQ(ax88772_tx_block(frame, kMaxFrameLen, tx, AX_HEADER_LEN + 1536), + kMaxFrameLen + AX_HEADER_LEN); + for (int i = 0; i < 8; i++) { + EXPECT_EQ((int)src_block[i], (int)kSentinel); + EXPECT_EQ((int)dst_block[i], (int)kSentinel); + } +} + +TEST(Ax88772TxBlock, CarriesBothLengthBytesAndTheirComplements) +{ + uint8_t frame[1500]; + memset(frame, 0x33, sizeof(frame)); + uint8_t tx[AX_HEADER_LEN + 1536]; + + EXPECT_EQ(ax88772_tx_block(frame, 1500, tx, sizeof(tx)), 1504); + EXPECT_EQ((int)tx[0], 1500 & 0xFF); + EXPECT_EQ((int)tx[1], 1500 >> 8); + EXPECT_EQ((int)tx[2], (1500 & 0xFF) ^ 0xFF); + EXPECT_EQ((int)tx[3], (1500 >> 8) ^ 0xFF); +} + +TEST(Ax88772TxBlock, TakesTheLargestFrameThatFitsAndRefusesOneMore) +{ + uint8_t frame[1537]; + memset(frame, 0x77, sizeof(frame)); + uint8_t tx[AX_HEADER_LEN + 1536]; + + EXPECT_EQ(ax88772_tx_block(frame, 1536, tx, sizeof(tx)), 1540); + EXPECT_EQ(ax88772_tx_block(frame, 1537, tx, sizeof(tx)), -1); +} + +TEST(Ax88772TxBlock, RefusesWhatItCannotAssemble) +{ + uint8_t frame[64]; + memset(frame, 0x11, sizeof(frame)); + uint8_t tx[AX_HEADER_LEN + 64]; + + EXPECT_EQ(ax88772_tx_block(frame, -1, tx, sizeof(tx)), -1); + EXPECT_EQ(ax88772_tx_block(NULL, 42, tx, sizeof(tx)), -1); + EXPECT_EQ(ax88772_tx_block(frame, 42, NULL, sizeof(tx)), -1); + EXPECT_EQ(ax88772_tx_block(frame, 0, tx, AX_HEADER_LEN - 1), -1); +} diff --git a/software/io/usb/usb_ax88772.cc b/software/io/usb/usb_ax88772.cc index 716d273fa..417ec32da 100644 --- a/software/io/usb/usb_ax88772.cc +++ b/software/io/usb/usb_ax88772.cc @@ -9,6 +9,7 @@ #include "FreeRTOS.h" #include "task.h" #include "endianness.h" +#include "eth_tx_frame.h" #define DEBUG_RAW_PKT 0 #define DEBUG_INVALID_PKT 0 @@ -609,9 +610,6 @@ err_t UsbAx88772Driver :: output_packet(uint8_t *buffer, int pkt_len) return ERR_CONN; //dump_hex(buffer, 32); - if ((pkt_len < 0) || (pkt_len > AX_MAX_PACKET_LEN)) { - return ERR_ARG; - } // The adapter wants a four byte length header immediately in front of the // frame. Writing it at buffer - 4 only works for a buffer that came back @@ -623,13 +621,13 @@ err_t UsbAx88772Driver :: output_packet(uint8_t *buffer, int pkt_len) // PBUF_LINK_ENCAPSULATION_HLEN is left at its default, so it lands in the // pbuf's own metadata or the neighbouring pool entry. Assemble header and // frame in a buffer this driver owns instead. - txBuffer[0] = uint8_t(pkt_len & 0xFF); - txBuffer[1] = uint8_t(pkt_len >> 8); - txBuffer[2] = txBuffer[0] ^ 0xFF; - txBuffer[3] = txBuffer[1] ^ 0xFF; - memcpy(txBuffer + AX_HEADER_LEN, buffer, pkt_len); + int to_send = ax88772_tx_block(buffer, pkt_len, txBuffer, + AX_HEADER_LEN + AX_MAX_PACKET_LEN); + if (to_send < 0) { + return ERR_ARG; + } - host->bulk_out(&bulk_out_pipe, txBuffer, pkt_len + AX_HEADER_LEN); + host->bulk_out(&bulk_out_pipe, txBuffer, to_send); return ERR_OK; } diff --git a/software/io/usb/usb_ax88772.h b/software/io/usb/usb_ax88772.h index f56eb4d36..c933e7c22 100644 --- a/software/io/usb/usb_ax88772.h +++ b/software/io/usb/usb_ax88772.h @@ -8,9 +8,8 @@ #define NUM_AX_BUFFERS 64 -// The adapter prefixes every frame it is given with a four byte length -// header. 1536 is the buffer size the receive pool uses. -#define AX_HEADER_LEN 4 +// AX_HEADER_LEN lives in eth_tx_frame.h, next to the code that writes it. +// 1536 is the buffer size the receive pool uses. #define AX_MAX_PACKET_LEN 1536 class UsbAx88772Driver : public UsbDriver From ca07243b9d0a735251ddf7fb68d14f8630ae21c9 Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Thu, 17 Sep 2026 08:39:14 +0200 Subject: [PATCH 012/514] Measure the transmit framing at the lengths the review named, red and green The suite pinned the two decisions but not at every length #843 asked for, and it guarded only the memory in front of each buffer. A leak past the end is what problem 4 actually was, so that was the wrong side to watch. Both contracts are now checked with eight sentinel bytes in front of the frame and eight behind it, at the lengths from the review: 0, 1, 1500, 1536 and 1537 for the AX88772 block, where 1537 is one byte too many and has to be refused, and 42, 59 and 60 for the RMII path. Each case asserts the four byte header, length little endian then each byte complemented, the payload byte for byte, that the padding is zero and not the neighbour, and that the caller's buffer comes back exactly as it went in. The red half is new. eth_tx_frame_legacy.h models what the two drivers did to memory before the fix -- the AX88772 header at frame - 4, and a short frame whose length register was raised to 60 while the data was not -- and the same suite runs against it. It is a model of the defect, not of the device, and no firmware builds it. against this commit 12 passed against the pre-fix behaviour 11 failed The one that stays green either way is the control case: a frame of 60 bytes or more goes out of the caller's buffer untouched in both versions, and must. `make -C software/io/network/tests` now runs both halves, and the red one fails the build if it ever passes, so a later change that guts the checks is caught here instead of going quiet. --- software/io/network/tests/Makefile | 18 ++- .../io/network/tests/eth_tx_frame_legacy.h | 68 +++++++++ .../io/network/tests/eth_tx_frame_test.cpp | 139 ++++++++++++++++++ 3 files changed, 223 insertions(+), 2 deletions(-) create mode 100644 software/io/network/tests/eth_tx_frame_legacy.h diff --git a/software/io/network/tests/Makefile b/software/io/network/tests/Makefile index dbbaf472c..2e4b3abc4 100644 --- a/software/io/network/tests/Makefile +++ b/software/io/network/tests/Makefile @@ -2,14 +2,28 @@ CXX ?= g++ CXXFLAGS := -std=c++14 -g -Wall -Wextra -I. -I.. -I../../usb/tests OUTPUT_DIR := output ETH_TX_FRAME_TEST := $(OUTPUT_DIR)/ethTxFrameTest +ETH_TX_FRAME_RED := $(OUTPUT_DIR)/ethTxFrameTestLegacy -.PHONY: all eth-tx-frame clean +.PHONY: all eth-tx-frame eth-tx-frame-red clean -all: eth-tx-frame +all: eth-tx-frame eth-tx-frame-red eth-tx-frame: mkdir -p $(OUTPUT_DIR) $(CXX) $(CXXFLAGS) eth_tx_frame_test.cpp ../../usb/tests/host_test_main.cpp -lpthread -o $(ETH_TX_FRAME_TEST) && $(ETH_TX_FRAME_TEST) +# The same suite against a model of the two drivers as they were before the fix. +# It has to fail: this target succeeds only when it does, so a later change that +# guts the checks is caught here rather than passing quietly. +eth-tx-frame-red: + mkdir -p $(OUTPUT_DIR) + $(CXX) $(CXXFLAGS) -DETH_TX_FRAME_LEGACY eth_tx_frame_test.cpp ../../usb/tests/host_test_main.cpp -lpthread -o $(ETH_TX_FRAME_RED) + @if $(ETH_TX_FRAME_RED) > $(OUTPUT_DIR)/red.log 2>&1; then \ + echo "eth-tx-frame-red: the suite passed against the pre-fix behaviour -- it no longer catches the defect"; \ + exit 1; \ + else \ + echo "eth-tx-frame-red: $$(tail -1 $(OUTPUT_DIR)/red.log) against the pre-fix behaviour, as required"; \ + fi + clean: rm -rf $(OUTPUT_DIR) diff --git a/software/io/network/tests/eth_tx_frame_legacy.h b/software/io/network/tests/eth_tx_frame_legacy.h new file mode 100644 index 000000000..5c5a2ef0a --- /dev/null +++ b/software/io/network/tests/eth_tx_frame_legacy.h @@ -0,0 +1,68 @@ +/* + * eth_tx_frame_legacy.h -- the two transmit paths as they were before + * GideonZ/1541ultimate#843, so the same suite can be run against them. + * + * This is the red half of red/green. It is a model of the defect and not of the + * device: it reproduces what the old code did to memory, which is what the + * tests measure, and nothing else. Neither function is built into any firmware. + * + * Kept beside the tests rather than in the driver directory for that reason. + */ +#ifndef IO_NETWORK_ETH_TX_FRAME_LEGACY_H +#define IO_NETWORK_ETH_TX_FRAME_LEGACY_H + +#include +#include + +#define ETH_MIN_FRAME_LEN 60 +#define AX_HEADER_LEN 4 + +/* rmii_interface.cc before the fix: + * + * RMII_TX_LENGTH = (pkt_len < 60) ? 60 : pkt_len; + * + * The number was raised to the Ethernet minimum, the data was not. The engine + * sends exactly as many bytes as the register names, reading them from the + * caller's buffer, so a 42 byte ARP request put the 18 bytes that happened to + * follow it on the wire. + */ +static inline bool eth_tx_frame_to_send(uint8_t *frame, int pkt_len, + uint8_t *pad, int pad_size, + uint8_t **out_frame, int *out_len) +{ + (void)pad; + (void)pad_size; + if (frame == NULL || pkt_len < 0) { + return false; + } + *out_frame = frame; /* no copy */ + *out_len = (pkt_len < ETH_MIN_FRAME_LEN) ? ETH_MIN_FRAME_LEN : pkt_len; + return true; +} + +/* usb_ax88772.cc before the fix: + * + * buffer[-4] = ...; buffer[-3] = ...; buffer[-2] = ...; buffer[-1] = ...; + * bulk_out(&bulk_out_pipe, buffer - 4, pkt_len + 4); + * + * The header went immediately in front of the frame the network stack owns, + * which has no headroom, and the transfer started there. The driver's own + * buffer was not involved at all -- which is why the checks on it go red. + */ +static inline int ax88772_tx_block(const uint8_t *frame, int pkt_len, + uint8_t *tx, int tx_size) +{ + (void)tx; + (void)tx_size; + if (frame == NULL || pkt_len < 0) { + return -1; + } + uint8_t *header = const_cast(frame) - AX_HEADER_LEN; + header[0] = (uint8_t)(pkt_len & 0xFF); + header[1] = (uint8_t)((pkt_len >> 8) & 0xFF); + header[2] = (uint8_t)(header[0] ^ 0xFF); + header[3] = (uint8_t)(header[1] ^ 0xFF); + return pkt_len + AX_HEADER_LEN; +} + +#endif /* IO_NETWORK_ETH_TX_FRAME_LEGACY_H */ diff --git a/software/io/network/tests/eth_tx_frame_test.cpp b/software/io/network/tests/eth_tx_frame_test.cpp index ba3bbce13..9359be8a4 100644 --- a/software/io/network/tests/eth_tx_frame_test.cpp +++ b/software/io/network/tests/eth_tx_frame_test.cpp @@ -14,7 +14,13 @@ // that no sentinel byte is inside what the function says to transmit. #include "../../usb/tests/host_test/host_test.h" +#ifdef ETH_TX_FRAME_LEGACY +#include "eth_tx_frame_legacy.h" // the pre-fix behaviour: the red half +#else #include "../eth_tx_frame.h" +#endif + +#include namespace { @@ -203,3 +209,136 @@ TEST(Ax88772TxBlock, RefusesWhatItCannotAssemble) EXPECT_EQ(ax88772_tx_block(frame, 42, NULL, sizeof(tx)), -1); EXPECT_EQ(ax88772_tx_block(frame, 0, tx, AX_HEADER_LEN - 1), -1); } + +// --------------------------------------------------- the review's cases -- +// +// GideonZ/1541ultimate#843 asked for the two contracts to be pinned at the +// lengths where they break, with a canary on both sides of every buffer rather +// than only in front of it. A leak past the end is what problem 4 actually was, +// so the tail guard is the one that matters most here. + +namespace { + +// A frame with eight sentinel bytes in front of it and eight behind, so a write +// or a read on either side of the frame is visible. The frame itself is filled +// with a pattern that is never the sentinel. +struct GuardedFrame { + static const int kGuard = 8; + + std::vector block; + int len; + + explicit GuardedFrame(int frame_len) + : block((size_t)(2 * kGuard + (frame_len > 0 ? frame_len : 1)), kSentinel), + len(frame_len) + { + for (int i = 0; i < frame_len; i++) { + bytes()[i] = (uint8_t)(0x10 + (i & 0x7F)); // 0x10..0x8F, never 0xA5 + } + } + + uint8_t *bytes() { return &block[kGuard]; } + + bool guards_intact() const + { + for (int i = 0; i < kGuard; i++) { + if (block[i] != kSentinel) { + return false; + } + if (block[block.size() - 1 - i] != kSentinel) { + return false; + } + } + return true; + } + + bool unchanged() const + { + for (int i = 0; i < len; i++) { + if (block[kGuard + i] != (uint8_t)(0x10 + (i & 0x7F))) { + return false; + } + } + return guards_intact(); + } +}; + +} // namespace + +TEST(Ax88772TxBlock, AssemblesEveryLengthTheReviewNamedWithBothGuardsIntact) +{ + // 1537 is one byte more than the block can carry and has to be refused; + // every other length is assembled whole. + const int lengths[] = { 0, 1, 1500, 1536, 1537 }; + + for (int i = 0; i < 5; i++) { + const int len = lengths[i]; + GuardedFrame frame(len); + + std::vector dst((size_t)(2 * GuardedFrame::kGuard + AX_HEADER_LEN + 1536), + kSentinel); + uint8_t *tx = &dst[GuardedFrame::kGuard]; + + const int sent = ax88772_tx_block(frame.bytes(), len, tx, AX_HEADER_LEN + 1536); + + if (len > 1536) { + EXPECT_EQ(sent, -1); + } else { + EXPECT_EQ(sent, len + AX_HEADER_LEN); + // The four byte header: length little endian, then each byte + // complemented. + EXPECT_EQ((int)tx[0], len & 0xFF); + EXPECT_EQ((int)tx[1], (len >> 8) & 0xFF); + EXPECT_EQ((int)tx[2], (len & 0xFF) ^ 0xFF); + EXPECT_EQ((int)tx[3], ((len >> 8) & 0xFF) ^ 0xFF); + // The payload, byte for byte, and nothing else. + EXPECT_EQ(memcmp(tx + AX_HEADER_LEN, frame.bytes(), (size_t)len), 0); + } + + // Nothing on either side of either buffer moved. The header used to be + // written at frame - 4, which is the front guard here. + EXPECT_TRUE(frame.unchanged()); + for (int g = 0; g < GuardedFrame::kGuard; g++) { + EXPECT_EQ((int)dst[g], (int)kSentinel); + EXPECT_EQ((int)dst[dst.size() - 1 - g], (int)kSentinel); + } + } +} + +TEST(ShortFrame, LeavesTheCallersBufferAloneAtEveryLengthTheReviewNamed) +{ + // 42 is an ARP request, 59 the last length that needs padding, 60 the first + // that does not. None of the three may change the buffer the stack owns. + const int lengths[] = { 42, 59, 60 }; + + for (int i = 0; i < 3; i++) { + const int len = lengths[i]; + GuardedFrame frame(len); + + std::vector pad_block((size_t)(2 * GuardedFrame::kGuard + ETH_MIN_FRAME_LEN), + kSentinel); + uint8_t *pad = &pad_block[GuardedFrame::kGuard]; + + uint8_t *out = NULL; + int out_len = 0; + EXPECT_TRUE(eth_tx_frame_to_send(frame.bytes(), len, pad, ETH_MIN_FRAME_LEN, + &out, &out_len)); + EXPECT_EQ(out_len, len < ETH_MIN_FRAME_LEN ? ETH_MIN_FRAME_LEN : len); + + // What goes on the wire starts with the frame and continues with zeros, + // never with whatever was next to it. + EXPECT_EQ(memcmp(out, frame.bytes(), (size_t)len), 0); + for (int j = len; j < out_len; j++) { + EXPECT_EQ((int)out[j], 0); + } + + // The caller's buffer is untouched, guards included. + EXPECT_TRUE(frame.unchanged()); + + // And the pad buffer is written only as far as the minimum frame. + for (int g = 0; g < GuardedFrame::kGuard; g++) { + EXPECT_EQ((int)pad_block[g], (int)kSentinel); + EXPECT_EQ((int)pad_block[pad_block.size() - 1 - g], (int)kSentinel); + } + } +} From 6720894a4f72b2e50289bd2ba65c3d14f897dcd5 Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Thu, 17 Sep 2026 10:44:46 +0200 Subject: [PATCH 013/514] Revert "Release the USB mutex when a setup packet is the wrong length" This reverts commit 3e37859d1cde2204b8bcd0c2dbabb6490432f8c0. Problem 5 of #822 is USB, not networking, and it only travelled in this PR because the sweep that found it also found the two transmit defects. It now has its own branch, where it is joined by the change that makes the class of defect impossible -- a single exit for the mutex -- and by the red/green measurement from a C64 Ultimate that the two together deserve. Reverted here rather than dropped, so this PR stays a fast-forward and the review on it keeps its anchors. What remains in this PR is the network half: the AX88772 length header, the short-frame padding, the delete[], and the host tests that pin all of it. --- software/io/usb/usb_base.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/software/io/usb/usb_base.cc b/software/io/usb/usb_base.cc index b39d71ec9..625a7220c 100644 --- a/software/io/usb/usb_base.cc +++ b/software/io/usb/usb_base.cc @@ -567,7 +567,6 @@ int UsbBase :: control_exchange(struct t_pipe *pipe, void *out, int outlen, void if (outlen != 8) { printf("%s Unsupported setup length.\n", pipe->name); - xSemaphoreGive(mutex); return -10; } From ad56e8e835c1338adc964e6b1f4463d95c612a18 Mon Sep 17 00:00:00 2001 From: Enver Haase Date: Fri, 18 Sep 2026 19:16:04 +0200 Subject: [PATCH 014/514] Do not read an MFM header out of a track too short to hold one Length and MFM marker share one word in a G64, so 0x8001 -- one byte of track, marked MFM -- is a legal thing to put in an image, and the bound added in the previous commit passes it: the one declared byte really was delivered. map_gcr_image_to_mfm() then believed the marker and read the whole 162 byte metadata area out of that one byte. Placed at the end of the buffer, as in the reported case -- a file of exactly GCRIMAGE_MAXSIZE with track 0 pointing at GCRIMAGE_MAXSIZE - 3 and a sector count of 32 in the final byte -- the sector loop runs past the allocation. The space behind the area was taken as a subtraction into reservedSpace, a uint32_t that gates every track write, where 1 - 162 cannot come out negative. MFM_TRACK_HEADER_SIZE was also unparenthesised, so x - MFM_TRACK_HEADER_SIZE expanded to x - 2 + 160. Every mapped track reserved 320 bytes more than it had, and the underflow above never happened because the subtraction was not one. The macro's three other uses -- an addition, a comparison, and - 2 -- come out right either way, which is why this stayed hidden. The static_assert beside it fails if the brackets are lost again; comparing the macro against 162 would not, since 2 + 160 equals 162. disk_image.h now includes mfmdisk.h, which defines the WD_MAX_SECTORS_PER_TRACK the macro has always used. A track shorter than the metadata area is left as init() zeroed it: no sectors, no reserved space, so UpdateTrack() admits no write for it. Six cases added under MfmHeader, including the reported end of buffer file. Against this commit the suite is 29 green; with gcr_mfm_reserved_space() restored to a bare subtraction the short track reserves 4294967135 bytes, and with the header check restored to believing the marker the reported case is mapped. Reported by @chrisgleissner in review of GideonZ/1541ultimate#840. --- software/drive/c1541.cc | 9 ++- software/drive/disk_image.h | 10 ++- software/drive/gcr_track_bounds.h | 35 +++++++++ .../drive/tests/gcr_track_bounds_test.cpp | 72 +++++++++++++++++++ 4 files changed, 124 insertions(+), 2 deletions(-) diff --git a/software/drive/c1541.cc b/software/drive/c1541.cc index 0e5bffb9a..74f752015 100644 --- a/software/drive/c1541.cc +++ b/software/drive/c1541.cc @@ -518,7 +518,14 @@ void C1541 :: map_gcr_image_to_mfm(void) if (!gcr || !mtr) { continue; } - mtr->reservedSpace = gtr->track_length - MFM_TRACK_HEADER_SIZE; + // A track shorter than the metadata area cannot carry one, whatever + // its marker says, and there is no space behind an area that does + // not fit. Leave the entry as init() zeroed it: no sectors, no + // reserved space, so UpdateTrack() admits no write for this track. + if (!gcr_track_can_hold_mfm_header(gtr->track_length, MFM_TRACK_HEADER_SIZE)) { + continue; + } + mtr->reservedSpace = gcr_mfm_reserved_space(gtr->track_length, MFM_TRACK_HEADER_SIZE); mtr->offsetInFile = (int)gcr - (int)gcr_image->gcr_data; mtr->offsetInFile += MFM_TRACK_HEADER_SIZE; diff --git a/software/drive/disk_image.h b/software/drive/disk_image.h index 8111b9bd4..19adf4f84 100644 --- a/software/drive/disk_image.h +++ b/software/drive/disk_image.h @@ -10,6 +10,7 @@ #include "menu.h" #include "filemanager.h" #include "subsys.h" +#include "mfmdisk.h" // WD_MAX_SECTORS_PER_TRACK, used by MFM_TRACK_HEADER_SIZE below #define GCR_DECODER_GCR_IN (*(volatile uint8_t *)(GCR_CODER_BASE + 0x00)) #define GCR_DECODER_BIN_OUT0 (*(volatile uint8_t *)(GCR_CODER_BASE + 0x00)) @@ -48,7 +49,14 @@ #define C1541_MIN_D71_SIZE (2*C1541_MAX_D64_35_NO_ERRORS) #define C1541_D71_SIZE_WITH_ERRORS (C1541_MIN_D71_SIZE + 1366) -#define MFM_TRACK_HEADER_SIZE 2 + (WD_MAX_SECTORS_PER_TRACK * 5) +/* Parenthesised because it is subtracted: without the outer brackets + * "x - MFM_TRACK_HEADER_SIZE" expanded to "x - 2 + 160", which is x + 158 + * rather than x - 162, and map_gcr_image_to_mfm() reserved 320 bytes more + * than the track had. The static_assert below fails if they are lost again; + * comparing the macro against 162 would not, since 2 + 160 equals 162. */ +#define MFM_TRACK_HEADER_SIZE (2 + (WD_MAX_SECTORS_PER_TRACK * 5)) +static_assert(0 - MFM_TRACK_HEADER_SIZE == -162, + "MFM_TRACK_HEADER_SIZE must survive being subtracted"); class BinImage; diff --git a/software/drive/gcr_track_bounds.h b/software/drive/gcr_track_bounds.h index c1bc06e7c..2a6a62fa5 100644 --- a/software/drive/gcr_track_bounds.h +++ b/software/drive/gcr_track_bounds.h @@ -68,6 +68,41 @@ static inline int gcr_validated_track_length(uint16_t declared, uint32_t offset, return length; } +/* An MFM track carries a metadata area at its front: a sector count, a version + * byte, and five bytes for each of up to WD_MAX_SECTORS_PER_TRACK sectors. + * map_gcr_image_to_mfm() reads that area whole for a track marked MFM, and + * reserves what lies behind it for sector data. Neither exists unless the + * track is at least as long as the area itself. + * + * Length and MFM marker share one word in a G64, so 0x8001 -- a one-byte track + * marked MFM -- is a legal thing to put in an image. The declared extent then + * checks out: one byte was delivered. The mapping used to believe the marker + * anyway, read the full metadata area from that one byte, and take the space + * behind it as a subtraction in an unsigned field, where it cannot come out + * negative. + * + * track_length the validated length of the track + * header_size bytes of metadata at the front of an MFM track + */ +static inline bool gcr_track_can_hold_mfm_header(int track_length, int header_size) +{ + if (header_size <= 0 || track_length <= 0) { + return false; + } + return track_length >= header_size; +} + +/* Bytes behind the metadata area, or 0 for a track with no room for one. The + * caller keeps this in an unsigned field that gates every track write, so it + * must never be reached by underflow. */ +static inline uint32_t gcr_mfm_reserved_space(int track_length, int header_size) +{ + if (!gcr_track_can_hold_mfm_header(track_length, header_size)) { + return 0; + } + return (uint32_t)(track_length - header_size); +} + /* Builds one entry of the drive's track parameter RAM: the address the engine * works at, and a word carrying the last valid offset in the low half and the * bit time in the high half. diff --git a/software/drive/tests/gcr_track_bounds_test.cpp b/software/drive/tests/gcr_track_bounds_test.cpp index bedafbccf..3b0432e1f 100644 --- a/software/drive/tests/gcr_track_bounds_test.cpp +++ b/software/drive/tests/gcr_track_bounds_test.cpp @@ -12,6 +12,10 @@ // And what checking the buffer alone still let through, found in review of the // first fix: a truncated file whose track header arrived but whose track data // did not -> TruncatedImage. +// +// And what checking the declared extent still let through, found in review of +// the second fix: a track short enough that the MFM mapping's own, larger +// assumption about it does not hold -> MfmHeader. #include "../../io/usb/tests/host_test/host_test.h" #include "../gcr_track_bounds.h" @@ -23,6 +27,7 @@ const uint32_t kMaxSize = (0x1EF8 * 80) + (12 + (168 * 10)); // GCRIMAGE_M const int kMaxTrackLen = 0x1EF8; // GCRIMAGE_MAXTRACKLEN const int kDummyLen = 0x1E0C; // GCRIMAGE_DUMMYTRACKLEN const uint32_t kRotationSpeed = 50000000 / 20; // CLOCK_FREQ / 20 on the U64 +const int kMfmHeaderSize = 2 + (32 * 5); // MFM_TRACK_HEADER_SIZE } // namespace @@ -229,3 +234,70 @@ TEST(TrackParameters, TreatsANegativeLengthAsAbsent) &address, ¶m); EXPECT_EQ(address, 0x00900000u); } + +// --------------------------------------------------------- the MFM header -- +// +// Reported by @chrisgleissner against the second version of this fix. The +// length check above proves that the bytes a track declares were delivered. +// map_gcr_image_to_mfm() then makes a second and larger assumption about the +// same track: that it is long enough to carry the MFM metadata area, which it +// reads whole and reserves the remainder behind. + +TEST(MfmHeader, RejectsATrackTooShortToCarryTheMetadata) +{ + EXPECT_FALSE(gcr_track_can_hold_mfm_header(1, kMfmHeaderSize)); + EXPECT_FALSE(gcr_track_can_hold_mfm_header(kMfmHeaderSize - 1, kMfmHeaderSize)); +} + +TEST(MfmHeader, AcceptsATrackExactlyAsLongAsTheMetadata) +{ + EXPECT_TRUE(gcr_track_can_hold_mfm_header(kMfmHeaderSize, kMfmHeaderSize)); + EXPECT_EQ(gcr_mfm_reserved_space(kMfmHeaderSize, kMfmHeaderSize), 0u); +} + +TEST(MfmHeader, ReservesWhatLiesBehindTheMetadata) +{ + EXPECT_EQ(gcr_mfm_reserved_space(0x1E0C, kMfmHeaderSize), (uint32_t)(0x1E0C - 162)); + EXPECT_EQ(gcr_mfm_reserved_space(1000, kMfmHeaderSize), 838u); +} + +TEST(MfmHeader, NeverUnderflowsTheReservedSpace) +{ + // The field is a uint32_t and gates every track write. A short track used + // to reach it as a subtraction, so "1 - 162" became 4294967135 and + // UpdateTrack() admitted a write of any size at all. + EXPECT_EQ(gcr_mfm_reserved_space(1, kMfmHeaderSize), 0u); + EXPECT_EQ(gcr_mfm_reserved_space(0, kMfmHeaderSize), 0u); + EXPECT_EQ(gcr_mfm_reserved_space(-1, kMfmHeaderSize), 0u); + for (int len = -4; len < kMfmHeaderSize; len++) { + EXPECT_EQ(gcr_mfm_reserved_space(len, kMfmHeaderSize), 0u); + } +} + +TEST(MfmHeader, TheReportedEndOfBufferCase) +{ + // @chrisgleissner's file, exactly: GCRIMAGE_MAXSIZE bytes long, track 0 + // pointing at GCRIMAGE_MAXSIZE - 3, declaring 0x8001 -- one byte of track, + // marked MFM -- with a sector count of 32 in the final byte of the file. + const uint32_t offset = kMaxSize - 3; + const uint16_t declared = 0x8001; + + // The header is readable and the one declared byte really was delivered, + // so the length check passes it. That is correct and not the bug. + EXPECT_TRUE(gcr_track_header_is_readable(offset, kMaxSize)); + EXPECT_EQ(gcr_validated_track_length(declared, offset, kMaxSize, kMaxTrackLen), 1); + + // The mapping is where it has to stop. Believing the marker would read the + // full 162-byte metadata area from a track holding one byte at the very end + // of the buffer, so the sector loop runs past the allocation. + const int length = gcr_validated_track_length(declared, offset, kMaxSize, kMaxTrackLen); + EXPECT_FALSE(gcr_track_can_hold_mfm_header(length, kMfmHeaderSize)); + EXPECT_EQ(gcr_mfm_reserved_space(length, kMfmHeaderSize), 0u); +} + +TEST(MfmHeader, TreatsAnAbsurdHeaderSizeAsNoHeader) +{ + EXPECT_FALSE(gcr_track_can_hold_mfm_header(0x1E0C, 0)); + EXPECT_FALSE(gcr_track_can_hold_mfm_header(0x1E0C, -162)); + EXPECT_EQ(gcr_mfm_reserved_space(0x1E0C, 0), 0u); +} From 666773d6706324f59d283bc77a537f2faed9180d Mon Sep 17 00:00:00 2001 From: Alex Damhuis Date: Sat, 19 Sep 2026 19:01:18 +0200 Subject: [PATCH 015/514] Save a cartridge without modifying the running one save_crt() swapped the original EAPI back into cartridge memory, wrote the file, and patched our EAPI in again. The overlay menu and REST reach Save Cartridge with the C64 running, so a game calling EAPI during the save ran the EasyFlash 3 original against flash hardware the emulation does not have. Every save also leaked 768 bytes, since patching allocates a new copy of the original each time. The chunk holding the EAPI is now written in three parts, with the original bytes taken from the saved copy; memory is not touched. Save Cartridge runs inside a stopped session, so the file is one consistent image even when the menu did not freeze the machine. From the C64 menu the machine is already frozen and the session does nothing. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01TXJJcXhem7KALtF1pMSxk5 --- software/io/c64/c64_crt.cc | 35 ++++++++++++++++++++--------------- software/io/c64/c64_crt.h | 1 - software/io/c64/c64_subsys.cc | 3 +++ 3 files changed, 23 insertions(+), 16 deletions(-) diff --git a/software/io/c64/c64_crt.cc b/software/io/c64/c64_crt.cc index 047ad80a6..e1954c66d 100644 --- a/software/io/c64/c64_crt.cc +++ b/software/io/c64/c64_crt.cc @@ -412,18 +412,6 @@ void C64_CRT::patch_easyflash_eapi() } } -void C64_CRT::unpatch_easyflash_eapi() -{ - if (!original_eapi) - return; - if (local_type != CART_EASYFLASH) - return; - - uint8_t* eapi = cart_memory + 0x3800; - memcpy(eapi, original_eapi, 768); - printf("EAPI successfully un-patched!\n"); -} - SubsysResultCode_e C64_CRT::read_crt(File *file, cart_def *def) { clear_cart_mem(); @@ -701,7 +689,13 @@ SubsysResultCode_e C64_CRT::save_crt(File *fo) return SSRET_DISK_ERROR; } - crt->unpatch_easyflash_eapi(); + // Memory holds our EAPI; the file gets the one it came with. Written from the saved copy, because + // restoring it in place would change code that a running C64 may be executing. + uint8_t *eapi = NULL; + if (crt->original_eapi && (crt->local_type == CART_EASYFLASH)) { + eapi = crt->cart_memory + 0x3800; + } + for (int i=0; ichip_chunks.get_elements(); i++) { t_crt_chip_chunk *cc = crt->chip_chunks[i]; uint16_t size = get_word(cc->header + CRTCHP_SIZE); @@ -737,12 +731,23 @@ SubsysResultCode_e C64_CRT::save_crt(File *fo) break; } - res = fo->write(cc->ram_location, size, &written); + uint8_t *data = cc->ram_location; + if (eapi && (eapi >= data) && (eapi + 768 <= data + size)) { + uint32_t before = eapi - data; + res = fo->write(data, before, &written); + if (res == FR_OK) { + res = fo->write(crt->original_eapi, 768, &written); + } + if (res == FR_OK) { + res = fo->write(eapi + 768, size - before - 768, &written); + } + } else { + res = fo->write(data, size, &written); + } if (res != FR_OK) { break; } } - crt->patch_easyflash_eapi(); if (res == FR_OK) { return SSRET_OK; diff --git a/software/io/c64/c64_crt.h b/software/io/c64/c64_crt.h index 36b177452..377df6139 100644 --- a/software/io/c64/c64_crt.h +++ b/software/io/c64/c64_crt.h @@ -93,7 +93,6 @@ class C64_CRT SubsysResultCode_e read_chip_packet(File *f, t_crt_chip_chunk *chunk); void clear_cart_mem(void); void patch_easyflash_eapi(); - void unpatch_easyflash_eapi(); void regenerate_easyflash_chunks(); SubsysResultCode_e read_crt(File *file, cart_def *def); void configure_cart(cart_def *def); diff --git a/software/io/c64/c64_subsys.cc b/software/io/c64/c64_subsys.cc index bccf16f1b..4ed9f1e39 100644 --- a/software/io/c64/c64_subsys.cc +++ b/software/io/c64/c64_subsys.cc @@ -363,7 +363,10 @@ SubsysResultCode_e C64_Subsys::executeCommand(SubsysCommand *cmd) res = create_file_ask_if_exists(fm, cmd->user_interface, cmd->path.c_str(), buffer, &f); if (res == FR_OK) { + // Overlay and REST get here with the C64 running; stopped, the file is one image. + bool stopped = c64->begin_stopped_session(); SubsysResultCode_e retval = C64_CRT::save_crt(f); + c64->end_stopped_session(stopped); fm->fclose(f); if (retval != SSRET_OK) { cmd->user_interface->popup(SubsysCommand::error_string(retval), BUTTON_OK); From 7a47589a977e22ba2f222362ded847c7d1e94894 Mon Sep 17 00:00:00 2001 From: Alex Damhuis Date: Sun, 20 Sep 2026 15:30:57 +0200 Subject: [PATCH 016/514] Check in the host test that saving leaves memory alone The loader test already builds c64_crt.cc on its own, so the saved file can be inspected there. The host File gained a writing mode for it. After a save the file carries the EAPI the cartridge came with, while cartridge memory still holds the patched one, and the bytes on both sides of it match memory. 537 checks, up from 529. Co-Authored-By: Claude Opus 5 (1M context) --- software/io/c64/tests/c64_crt_host.h | 17 ++++++-- software/io/c64/tests/c64_crt_test.cc | 63 +++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 3 deletions(-) diff --git a/software/io/c64/tests/c64_crt_host.h b/software/io/c64/tests/c64_crt_host.h index 97fa306a1..0c5d588f6 100644 --- a/software/io/c64/tests/c64_crt_host.h +++ b/software/io/c64/tests/c64_crt_host.h @@ -34,12 +34,16 @@ typedef int FRESULT; class FileInfo {}; -// A read-only file over bytes the test registered by name. +// A file over bytes the test registered by name for reading, or over a buffer +// the test owns for writing, so a saved cartridge can be inspected. class File { + static const std::vector &no_data() { static const std::vector e; return e; } const std::vector &data; + std::vector *sink; size_t pos; public: - explicit File(const std::vector &d) : data(d), pos(0) {} + explicit File(const std::vector &d) : data(d), sink(NULL), pos(0) {} + explicit File(std::vector *out) : data(no_data()), sink(out), pos(0) {} FRESULT read(void *buffer, uint32_t len, uint32_t *transferred) { size_t n = (pos < data.size()) ? std::min(len, data.size() - pos) : 0; memcpy(buffer, data.data() + pos, n); @@ -47,7 +51,14 @@ class File { *transferred = (uint32_t)n; return FR_OK; } - FRESULT write(const void *, uint32_t len, uint32_t *transferred) { *transferred = len; return FR_OK; } + FRESULT write(const void *buffer, uint32_t len, uint32_t *transferred) { + if (sink) { + const uint8_t *p = (const uint8_t *)buffer; + sink->insert(sink->end(), p, p + len); + } + *transferred = len; + return FR_OK; + } FRESULT seek(uint32_t offset) { pos = offset; return FR_OK; } }; diff --git a/software/io/c64/tests/c64_crt_test.cc b/software/io/c64/tests/c64_crt_test.cc index ee2406750..b8e2ef5b6 100644 --- a/software/io/c64/tests/c64_crt_test.cc +++ b/software/io/c64/tests/c64_crt_test.cc @@ -353,6 +353,68 @@ static void test_mirroring(void) CHECK(all_ff(r.at(3 * 32 * K), 4 * MB - 3 * 32 * K), "C128: memory after the image is not $FF"); } +// The chip packet for one bank and load address in a saved CRT file. +static const uint8_t *saved_chip(const std::vector &file, uint16_t bank, uint16_t load, uint16_t *size_out) +{ + size_t pos = 0x40; + while (pos + 16 <= file.size()) { + const uint8_t *h = file.data() + pos; + if (memcmp(h, "CHIP", 4)) { + break; + } + uint32_t packet = (uint32_t(h[4]) << 24) | (uint32_t(h[5]) << 16) | (uint32_t(h[6]) << 8) | h[7]; + if ((packet < 16) || (pos + packet > file.size())) { + break; + } + if ((((h[10] << 8) | h[11]) == bank) && (((h[12] << 8) | h[13]) == load)) { + *size_out = (h[14] << 8) | h[15]; + return h + 16; + } + pos += packet; + } + return NULL; +} + +// Saving must leave the cartridge the C64 is running alone, and the file must +// carry the EAPI the cartridge came with, not the one the firmware patched in. +static void test_save_keeps_memory(void) +{ + for (int i = 0; i < 768; i++) { + _eapi_65_start[i] = uint8_t(0x10 + (i & 7)); + } + Crt crt(32); + crt.header(1, 0, 0); + crt.chip(0, 0x8000, 0x2000).chip(0, 0xA000, 0x2000).chip(1, 0x8000, 0x2000).chip(1, 0xA000, 0x2000); + + // The EAPI of the cartridge sits at $B800, which is bank 0 at $A000 plus $1800. + std::vector &romh = crt.chips[1].data; + const uint8_t signature[4] = { 'e', 'a', 'p', 'i' }; + memcpy(&romh[0x1800], signature, 4); + for (int i = 4; i < 768; i++) { + romh[0x1800 + i] = uint8_t(0xC0 + (i & 0x1F)); + } + std::vector original_eapi(romh.begin() + 0x1800, romh.begin() + 0x1800 + 768); + + Loaded r = load(crt, MB); + CHECK(r.rc == SSRET_OK, "EasyFlash with EAPI: load returned %d", r.rc); + CHECK(!memcmp(r.at(0x3800), _eapi_65_start, 768), "the firmware's EAPI is not in cartridge memory after loading"); + + std::vector file; + File out(&file); + SubsysResultCode_e rc = C64_CRT::save_crt(&out); + CHECK(rc == SSRET_OK, "save returned %d", rc); + CHECK(!memcmp(r.at(0x3800), _eapi_65_start, 768), "saving replaced the EAPI in cartridge memory"); + + uint16_t size = 0; + const uint8_t *chip = saved_chip(file, 0, 0xA000, &size); + CHECK(chip && (size == 0x2000), "the saved file has no bank 0 chip at $A000"); + if (chip && (size == 0x2000)) { + CHECK(!memcmp(chip + 0x1800, original_eapi.data(), 768), "the saved file carries the patched EAPI, not the original"); + CHECK(!memcmp(chip, r.at(0x2000), 0x1800), "the bytes before the EAPI are not the ones in memory"); + CHECK(!memcmp(chip + 0x1B00, r.at(0x3B00), 0x2000 - 0x1B00), "the bytes after the EAPI are not the ones in memory"); + } +} + int main() { test_cartridge_types(); @@ -360,6 +422,7 @@ int main() test_packets(); test_chip_placement(); test_mirroring(); + test_save_keeps_memory(); fprintf(stderr, "c64_crt_test: %s (%d checks, %d failed)\n", failures ? "FAIL" : "OK", checks, failures); return failures ? 1 : 0; } From ec45176e78f505800a56d060836f89c6c8b98529 Mon Sep 17 00:00:00 2001 From: Alex Damhuis Date: Sun, 20 Sep 2026 23:33:19 +0200 Subject: [PATCH 017/514] Keep the GMod2 EEPROM change until it is saved get_eeprom_dirty() cleared the hardware flag on every read, so whoever looked at it first took the change with it. System Info (F4) reads it to print the EEPROM's state; a Save Cartridge afterwards saw a clean EEPROM, skipped fetching it, and wrote the contents from load time. The game's save was lost, without a word. The flag now says what it is named after: it stays set until the contents are taken, which get_eeprom_data() and set_eeprom_data() already do. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01U21kGQdwyaC5cfTfKNGSa8 --- software/io/c64/c64.cc | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/software/io/c64/c64.cc b/software/io/c64/c64.cc index f7a6728c8..eb966e295 100644 --- a/software/io/c64/c64.cc +++ b/software/io/c64/c64.cc @@ -1653,10 +1653,11 @@ void C64 :: set_eeprom_data(uint8_t *buffer) bool C64 :: get_eeprom_dirty(void) { + // Reading does not clear: the flag stays set until the contents are taken, in + // get_eeprom_data() or set_eeprom_data(). Clearing it here lost the change to + // whoever looked at it first, which System Info does. volatile uint8_t *eeprom = (volatile uint8_t *)(EEPROM_BASE); - bool dirty = (*eeprom != 0) ? true : false; - *eeprom = 1; // clear dirty flag - return dirty; + return (*eeprom != 0); } void C64 :: list_crts(ConfigItem *it, IndexedList& strings) From 9cbdd9e2ebdad665304def0b3ad9a586f89cbdd1 Mon Sep 17 00:00:00 2001 From: Alex Damhuis Date: Sun, 20 Sep 2026 21:58:14 +0200 Subject: [PATCH 018/514] Cover the GMod2 EEPROM flag end to end Reading the flag used to clear it in hardware, so any screen that looked first took the game's save with it. System Info is that screen, and it is also where the effect can be seen: it has to report the EEPROM as changed every time it is opened, not only the first time. The suite builds its own GMod2 cartridge rather than shipping a ROM, and drives the EEPROM from RAM with the runtime in software/6502, because the chip select in bit 6 of $DE00 switches the ROM off with it. The harness asks for the write over machine:writemem, so the EEPROM's state is read once before one as well. The EEPROM is an optional part of the FPGA build; System Info says so, and the suite reports SKIP on a machine without one. Co-Authored-By: Claude Opus 5 (1M context) --- run-tests | 16 + tests/README.md | 5 +- tests/e2e/io/c64/gmod2_eeprom_dirty_test.py | 340 ++++++++++++++++++++ tests/e2e/io/c64/gmod2_eeprom_write.asm | 80 +++++ 4 files changed, 439 insertions(+), 2 deletions(-) create mode 100644 tests/e2e/io/c64/gmod2_eeprom_dirty_test.py create mode 100644 tests/e2e/io/c64/gmod2_eeprom_write.asm diff --git a/run-tests b/run-tests index d0791073a..7c19db4a6 100755 --- a/run-tests +++ b/run-tests @@ -500,6 +500,22 @@ SUITES: Sequence[Suite] = ( # the machine afterwards to remove the cartridge. Suite("e2e", "easyflash-cartridge", "tests/e2e/io/c64/easyflash_cartridge_test.py", "-H @HOST@ -p @PASS@ -t @TIMEOUT@"), + # A GMod2 game's save lives in the cartridge's serial EEPROM, and the + # hardware flag that says it changed used to be cleared by reading it. Any + # screen that looked first took the save with it: System Info reads the flag + # to print the EEPROM's state, and a Save Cartridge afterwards wrote the + # EEPROM as it was when the cartridge was loaded. The suite builds a type 60 + # CRT, has it write one EEPROM word from RAM with the repository's own + # runtime, and opens System Info twice. It reboots the machine afterwards to + # remove the cartridge, and reports SKIP where the FPGA build has no EEPROM. + Suite("e2e", "gmod2-eeprom-dirty", "tests/e2e/io/c64/gmod2_eeprom_dirty_test.py", + "-H @HOST@ -p @PASS@ -t @TIMEOUT@"), + # RoboCop 2 and Shadow of the Beast read Ocean banks 16 to 31 at $A000, but + # every type 5 CRT was started in 8K mode, where $A000 never shows the + # cartridge, so they started to a black screen. The suite builds a 32-bank + # type 5 CRT in code with banks 16 to 31 listed at $A000, and reads each + # bank's marker byte back from screen RAM. It reboots the machine + # afterwards to remove the cartridge. # RoboCop 2 and Shadow of the Beast read Ocean banks 16 to 31 at $A000, but # every type 5 CRT was started in 8K mode, where $A000 never shows the # cartridge, so they started to a black screen. The suite builds a 32-bank diff --git a/tests/README.md b/tests/README.md index 01697fb3c..f98fab8b0 100644 --- a/tests/README.md +++ b/tests/README.md @@ -289,6 +289,7 @@ e2e: freezer-audio . x x x x ftp-client . x x x x ftp-server x x x x x + gmod2-eeprom-dirty . . x x x ident-service-switch . . x x x iec-dos-commands . . x x x input x x x x x @@ -350,8 +351,8 @@ soak: usb-keyboard-repeat . . . x x ------ ------ ------ ------ ------ - suites 14 29 63 77 77 - suite runs 14 29 63 154 231 + suites 14 29 64 78 78 + suite runs 14 29 64 156 234 Scenario and check counts, and durations, are not shown here: the registry does not know them. They depend on the machine and are diff --git a/tests/e2e/io/c64/gmod2_eeprom_dirty_test.py b/tests/e2e/io/c64/gmod2_eeprom_dirty_test.py new file mode 100644 index 000000000..af669928a --- /dev/null +++ b/tests/e2e/io/c64/gmod2_eeprom_dirty_test.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +"""E2E: reading the GMod2 EEPROM's changed flag does not throw the change away. + +A GMod2 game saves into the cartridge's serial EEPROM. The hardware sets a +flag when the C64 writes to it, and *Save Cartridge* copies the EEPROM out of +the hardware only when that flag is set. Reading the flag used to clear it in +hardware, so anything that looked at it first took the change with it: System +Info (F4) reads it to print the EEPROM's state, and a save taken afterwards +wrote the EEPROM as it was when the cartridge was loaded, silently losing the +game's save. + +The flag is now held in firmware until the data is actually taken, which makes +reading it free of side effects. That is what this suite checks, through the +one screen that reads it: System Info has to report the EEPROM as changed every +time it is opened, not only the first time. + +The suite builds its own GMod2 cartridge (CRT type 60) rather than shipping a +ROM, and drives the EEPROM with the repository's own runtime, from RAM, the way +a GMod2 game does. The harness asks for the write over machine:writemem, so the +EEPROM's state is read once before it too. + +The EEPROM is an optional part of the FPGA build; System Info says so, and the +suite reports SKIP on a machine without one. +""" + +from __future__ import annotations + +import argparse +import sys +import time +from pathlib import Path + +# The one stanza that puts the shared library on sys.path; see tests/lib/bootstrap.py. +sys.path.insert(0, str(next(p for p in Path(__file__).resolve().parents + if (p / "tests" / "lib").is_dir()) / "tests" / "lib")) +import bootstrap # noqa: E402,F401 + +import cli # noqa: E402 +import pacing # noqa: E402 +from api import UltimateApi # noqa: E402 +from assembler import assemble # noqa: E402 +from report import (Failure, check, check_ok, check_skip, # noqa: E402 + check_start, detail, format_exception, section, + suite_fail, suite_ok, suite_skip, teardown_step) + +SUITE = "gmod2_eeprom_dirty_test" + +SOURCE = Path(__file__).resolve().parent / "gmod2_eeprom_write.asm" + +# Addresses the stimulus and the harness share; see gmod2_eeprom_write.asm. +DONE = 0x0400 +GO = 0x0402 +RUNNING = 0x0405 + +GMOD2_TYPE = 60 + +# This cartridge is uploaded over REST and therefore runs from /Temp, which +# cartridge auto-save cannot write back: once the game has written the EEPROM, +# that feature greets every menu open with a notice, over the screen this suite +# is reading. The setting is absent on a firmware without the feature. +AUTOSAVE_CATEGORY = "C64 and Cartridge Settings" +AUTOSAVE_ITEM = "Save Changed Cartridge" + +ROUTINE_TIMEOUT_SECONDS = 15.0 +WRITE_TIMEOUT_SECONDS = 15.0 +SYSINFO_TIMEOUT_SECONDS = 20.0 +# How long a key is given to show on screen before it is sent again. +KEY_WATCH_SECONDS = 2.0 + +EEPROM_LINE = "EEPROM:" +DIRTY = "Dirty" +CLEAN = "Clean" +UNSUPPORTED = "Not Supported" +TITLE = "System Information" + +# F4 opens System Info, and a C64 keyboard makes F4 from shift and F3. +SYSINFO_KEYS = ("left_shift", "f3") + +# CLR/HOME puts a text view back on its first line (editor.cc, KEY_HOME). Not +# F2, which the user interface maps to its settings before an editor sees it. +HOME_KEYS = ("clr_home",) + +# System Info is longer than one screen, and the EEPROM sits in the cartridge +# section below the fold. +SYSINFO_PAGES = 8 + + +def chip(bank: int, load: int, rom: bytes) -> bytes: + """One CHIP chunk, as the CRT format has it.""" + return (b"CHIP" + (0x10 + len(rom)).to_bytes(4, "big") + + (0).to_bytes(2, "big") + bank.to_bytes(2, "big") + + load.to_bytes(2, "big") + len(rom).to_bytes(2, "big") + rom) + + +def gmod2_crt() -> bytes: + """A one-bank type 60 CRT that starts the stimulus. + + No EEPROM chunk: the firmware creates an empty one on load and clears the + EEPROM in hardware with it (c64_crt.cc, find_eeprom), which is the state + this suite wants to start from. + """ + header = bytearray(0x40) + header[0x00:0x10] = b"C64 CARTRIDGE " + header[0x10:0x14] = (0x40).to_bytes(4, "big") + header[0x14:0x16] = b"\x01\x00" + header[0x16:0x18] = GMOD2_TYPE.to_bytes(2, "big") + header[0x18] = 0 # EXROM low, GAME high: 8K + header[0x19] = 1 + header[0x20:0x2B] = b"GMOD2-EEPROM"[:11] + return bytes(header) + chip(0, 0x8000, assemble(SOURCE)[2:]) + + +class Device: + """The device under test, and the screens this suite reads.""" + + def __init__(self, args) -> None: + self.api = UltimateApi(args.host, args.password or None, args.timeout) + + def quiet_cartridge_autosave(self) -> None: + """Hold cartridge auto-save off while this suite runs, where it exists. + + Not put back here: writing a setting leaves the firmware holding a user + interface object that closing the menu only hides, and the gate that + follows a suite then reports the root browser as not on top. The runner + captures every setting before a run and restores what changed + (tests/lib/config_snapshot.py), so the one write below is undone there. + A suite run on its own leaves the setting Off. + """ + try: + current = str(self.api.configs.current(AUTOSAVE_CATEGORY, AUTOSAVE_ITEM)) + except Failure: + return # a firmware without the feature + if current != "Off": + self.api.configs.set(AUTOSAVE_CATEGORY, AUTOSAVE_ITEM, "Off") + + def start_cartridge(self) -> None: + code, _, body = self.api.runners.upload("run_crt", gmod2_crt()) + if code != 200: + raise Failure(f"starting the cartridge returned HTTP {code}: {body[:160]!r}") + deadline = time.monotonic() + ROUTINE_TIMEOUT_SECONDS + while self.api.machine.readmem(RUNNING, 1)[0] != 0x01: + if time.monotonic() >= deadline: + raise Failure("the cartridge did not reach its routine within " + f"{ROUTINE_TIMEOUT_SECONDS:.0f} s") + time.sleep(0.25) + + def write_eeprom(self) -> None: + """Have the C64 write one word into the EEPROM, and wait for it.""" + self.api.machine.writemem(GO, bytes([0x01])) + deadline = time.monotonic() + WRITE_TIMEOUT_SECONDS + while self.api.machine.readmem(DONE, 1)[0] != 0x01: + if time.monotonic() >= deadline: + raise Failure("the cartridge did not finish writing the EEPROM") + time.sleep(0.25) + + def set_menu(self, want_open: bool) -> None: + """Press the menu button until the menu is open, or closed, as asked.""" + deadline = time.monotonic() + pacing.MENU_TOGGLE_TIMEOUT_SECONDS + while self.api.machine.menu_open() != want_open: + if time.monotonic() >= deadline: + raise Failure("the menu did not " + + ("open" if want_open else "close")) + self.api.machine.menu_button() + time.sleep(pacing.MENU_TOGGLE_SETTLE_SECONDS) + + def open_menu(self) -> None: + """Leave the menu freshly open, whatever it held before. + + Closed and opened with the menu button alone, and both states are read + back. Backing out with F8 instead leaves the overlay reporting an open + menu that no user interface object has focus in, and every key sent + into that goes to the C64 rather than to the firmware. + """ + self.set_menu(False) + self.set_menu(True) + + def eeprom_state(self) -> str: + """Open System Info, read its EEPROM line, and close it again. + + Every reading in this suite goes through here, so each one is a fresh + open of the screen that reads the flag. + """ + self.open_menu() + self.open_sysinfo() + rows: list[str] = [] + for _ in range(SYSINFO_PAGES): + rows = self.api.machine.menu_rows() + for row in rows: + if EEPROM_LINE in row: + self.close_sysinfo() + return row.split(EEPROM_LINE, 1)[1].strip() + self.api.machine.press("f7") # the report is longer than one screen + time.sleep(pacing.MENU_TOGGLE_SETTLE_SECONDS) + detail("last screen the harness read:") + for row in rows: + if row.strip(): + detail(f" {row}") + raise Failure(f"System Info showed no {EEPROM_LINE} line in " + f"{SYSINFO_PAGES} screens") + + def open_sysinfo(self) -> None: + """Open System Info over the browser, and leave it on its first line. + + The key is sent once per screen change, not repeatedly: a second F4 + while the view is already up pages it, and the title then scrolls off + the top, which is the one thing this waits on. A key that reached + nothing leaves the screen as it was, and only then is it sent again. + """ + deadline = time.monotonic() + SYSINFO_TIMEOUT_SECONDS + while True: + before = self.api.machine.menu_rows() + self.api.machine.press(*SYSINFO_KEYS) + if self.wait_screen_change(before, KEY_WATCH_SECONDS): + break + if time.monotonic() >= deadline: + self.report_screen() + raise Failure(f"{TITLE!r} did not open within " + f"{SYSINFO_TIMEOUT_SECONDS:.0f} s") + self.press_home() + + def press_home(self) -> None: + """Put the open text view back on its first line, so the title shows.""" + deadline = time.monotonic() + SYSINFO_TIMEOUT_SECONDS + while not any(TITLE in row for row in self.api.machine.menu_rows()): + if time.monotonic() >= deadline: + self.report_screen() + raise Failure(f"{TITLE!r} did not come back into view") + self.api.machine.press(*HOME_KEYS) + time.sleep(pacing.MENU_TOGGLE_SETTLE_SECONDS) + + def wait_screen_change(self, before: list[str], timeout: float) -> bool: + """Whether the screen became something other than `before` in time.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + time.sleep(pacing.MENU_TOGGLE_SETTLE_SECONDS) + if self.api.machine.menu_rows() != before: + return True + return False + + def report_screen(self) -> None: + rows = self.api.machine.menu_rows() + detail(f"menu_open={self.api.machine.menu_open()} rows={len(rows)}") + for row in rows: + if row.strip(): + detail(f" |{row.rstrip()}") + + def close_sysinfo(self) -> None: + """Leave the text view again, so the browser is back on top. + + RUN/STOP is what closes it; F8 does not reach an editor. A view left + open survives the menu being closed and reopened, and the next reading + would then page through the old one instead of opening a new one, so + this waits for the title to go rather than pressing once. + """ + self.press_home() # reading the EEPROM line pages down + deadline = time.monotonic() + SYSINFO_TIMEOUT_SECONDS + while any(TITLE in row for row in self.api.machine.menu_rows()): + if time.monotonic() >= deadline: + raise Failure("System Info stayed open after RUN/STOP") + self.api.machine.press("run_stop") + time.sleep(pacing.MENU_TOGGLE_SETTLE_SECONDS) + + def close_menu(self) -> None: + """Pop every level and leave the menu closed. + + RUN/STOP leaves a text view, and leaves the menu once the browser has + focus, so pressing it until the menu is gone takes the stack down one + object at a time. F8 would be one press, but it exits the user + interface instead of unwinding it, and the gate that follows a suite + then finds a menu that will not close from the browser. + """ + deadline = time.monotonic() + SYSINFO_TIMEOUT_SECONDS + while self.api.machine.menu_open(): + if time.monotonic() >= deadline: + raise Failure("the menu would not close") + self.api.machine.press("run_stop") + time.sleep(pacing.MENU_TOGGLE_SETTLE_SECONDS) + + +def run(args) -> str | None: + device = Device(args) + try: + section("a GMod2 cartridge whose game saves into the EEPROM") + device.quiet_cartridge_autosave() + with check("the cartridge starts and its EEPROM routine is ready"): + device.start_cartridge() + + check_start("the machine has an EEPROM") + state = device.eeprom_state() + if UNSUPPORTED in state: + reason = "this FPGA build carries no GMod2 EEPROM" + check_skip(reason) + return reason + check_ok(f"System Info reports {state!r}") + + with check("the EEPROM starts out unchanged"): + if CLEAN not in state: + raise Failure(f"System Info reports {state!r} before the game wrote " + "anything; the cartridge was loaded with a clean EEPROM") + + with check("System Info reports the EEPROM as changed after the game saved"): + device.write_eeprom() + state = device.eeprom_state() + if DIRTY not in state: + raise Failure(f"System Info reports {state!r} after the C64 wrote " + "a word into the EEPROM") + + with check("opening System Info again still reports the change"): + state = device.eeprom_state() + if DIRTY not in state: + raise Failure(f"the second reading reports {state!r}: reading the flag " + "took the change with it, and a save would now write the " + "EEPROM as it was loaded") + return None + finally: + teardown_step("close the menu", device.close_menu) + # A reboot removes the cartridge; a reset would boot straight back into it. + teardown_step("restore the configured cartridge", device.api.machine.reboot) + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Check that reading the GMod2 EEPROM's changed flag does not " + "clear it.") + cli.add_device_arguments(parser) + args = parser.parse_args() + try: + skipped = run(args) + except Exception as exc: # noqa: BLE001 + suite_fail(SUITE, format_exception(exc)) + return 1 + if skipped: + suite_skip(SUITE, skipped) + return 0 + suite_ok(SUITE) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/e2e/io/c64/gmod2_eeprom_write.asm b/tests/e2e/io/c64/gmod2_eeprom_write.asm new file mode 100644 index 000000000..8f4989182 --- /dev/null +++ b/tests/e2e/io/c64/gmod2_eeprom_write.asm @@ -0,0 +1,80 @@ +; GMod2 EEPROM stimulus for gmod2_eeprom_dirty_test.py. +; +; A GMod2 cartridge saves into a serial EEPROM driven bit by bit through its +; register at $DE00. Bit 6 of that register is the EEPROM's chip select and at +; the same time switches the ROM off (all_carts_v5.vhd:326-332), so the code +; that drives the EEPROM cannot run from the cartridge. The ROM at $8000 copies +; it into RAM and jumps into it, the way a GMod2 game does. +; +; The EEPROM runtime is the repository's own, so this drives the hardware +; exactly as the reference code in software/6502 does. +; +; The harness asks for the write rather than having it happen at boot, so it +; can read the EEPROM's state before and after one. +; +; $0400 $01 once the word has been written +; $0402 written by the harness to ask for the word +; $0405 $01 once the routine is up + +DONE = $0400 +GO = $0402 +RUNNING = $0405 +PAYLOAD = $0900 +WORD_HIGH = $00 ; the top two bits of the EEPROM word address +WORD_LOW = 100 ; and its low eight +VALUE_HIGH = $a5 +VALUE_LOW = $5a + + * = $8000 + + .word coldstart ; cold start vector + .word coldstart ; warm start vector + .byte $c3, $c2, $cd, $38, $30 ; CBM80, so the KERNAL starts the cartridge + +coldstart + sei + ldx #$ff + txs + cld + lda #$00 + sta DONE + + ldx #$00 ; two pages, because the runtime is longer than one +copy lda payload_rom,x + sta PAYLOAD,x + lda payload_rom + $100,x + sta PAYLOAD + $100,x + inx + bne copy + jmp PAYLOAD + +payload_rom + .logical PAYLOAD + + lda #$00 + sta GO + lda #$01 + sta RUNNING +wait lda GO + beq wait + + jsr eeprom_reset + jsr eeprom_ewen + + ldy #WORD_LOW + ldx #WORD_HIGH + jsr eeprom_write_begin + lda #VALUE_HIGH + jsr eeprom_write_byte + lda #VALUE_LOW + jsr eeprom_write_byte + jsr eeprom_write_end + + lda #$01 + sta DONE +spin jmp spin + + .include "../../../../software/6502/unsorted/eeprom.tas" + + .here + .fill $a000 - *, $ff From 6817777d2962c541dfee5ffab7a106f151042b24 Mon Sep 17 00:00:00 2001 From: Alex Damhuis Date: Mon, 21 Sep 2026 22:44:57 +0200 Subject: [PATCH 019/514] Use the shared helpers to drive the menu here too The same three patterns chrisgleissner found in the cartridge auto-save suite are in this one: the menu button pressed in a loop although it is a toggle, and polling written out rather than taken from the library. menu.toggle_menu presses once and polls, wait.wait_until paces itself from the shared values and writes what it waited for into the interaction log. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01TXJJcXhem7KALtF1pMSxk5 --- tests/e2e/io/c64/gmod2_eeprom_dirty_test.py | 37 ++++++++++----------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/tests/e2e/io/c64/gmod2_eeprom_dirty_test.py b/tests/e2e/io/c64/gmod2_eeprom_dirty_test.py index af669928a..b4483d64d 100644 --- a/tests/e2e/io/c64/gmod2_eeprom_dirty_test.py +++ b/tests/e2e/io/c64/gmod2_eeprom_dirty_test.py @@ -36,7 +36,9 @@ import bootstrap # noqa: E402,F401 import cli # noqa: E402 +import menu as menu_lib # noqa: E402 import pacing # noqa: E402 +import wait # noqa: E402 from api import UltimateApi # noqa: E402 from assembler import assemble # noqa: E402 from report import (Failure, check, check_ok, check_skip, # noqa: E402 @@ -137,31 +139,28 @@ def start_cartridge(self) -> None: code, _, body = self.api.runners.upload("run_crt", gmod2_crt()) if code != 200: raise Failure(f"starting the cartridge returned HTTP {code}: {body[:160]!r}") - deadline = time.monotonic() + ROUTINE_TIMEOUT_SECONDS - while self.api.machine.readmem(RUNNING, 1)[0] != 0x01: - if time.monotonic() >= deadline: - raise Failure("the cartridge did not reach its routine within " - f"{ROUTINE_TIMEOUT_SECONDS:.0f} s") - time.sleep(0.25) + wait.wait_until(lambda: self.api.machine.readmem(RUNNING, 1)[0] == 0x01, + "the cartridge reaches its routine", + timeout=ROUTINE_TIMEOUT_SECONDS) def write_eeprom(self) -> None: """Have the C64 write one word into the EEPROM, and wait for it.""" self.api.machine.writemem(GO, bytes([0x01])) - deadline = time.monotonic() + WRITE_TIMEOUT_SECONDS - while self.api.machine.readmem(DONE, 1)[0] != 0x01: - if time.monotonic() >= deadline: - raise Failure("the cartridge did not finish writing the EEPROM") - time.sleep(0.25) + wait.wait_until(lambda: self.api.machine.readmem(DONE, 1)[0] == 0x01, + "the cartridge finishes writing the EEPROM", + timeout=WRITE_TIMEOUT_SECONDS) def set_menu(self, want_open: bool) -> None: - """Press the menu button until the menu is open, or closed, as asked.""" - deadline = time.monotonic() + pacing.MENU_TOGGLE_TIMEOUT_SECONDS - while self.api.machine.menu_open() != want_open: - if time.monotonic() >= deadline: - raise Failure("the menu did not " - + ("open" if want_open else "close")) - self.api.machine.menu_button() - time.sleep(pacing.MENU_TOGGLE_SETTLE_SECONDS) + """Open or close the menu, with one press of its button. + + menu_lib.toggle_menu presses once and then polls, which is the only + safe way to drive a toggle: pressing again because the state has not + changed yet closes a menu that was still on its way open. + """ + if not menu_lib.toggle_menu(self.api.machine.menu_button, + self.api.machine.menu_open, want_open): + raise Failure("the menu did not " + + ("open" if want_open else "close")) def open_menu(self) -> None: """Leave the menu freshly open, whatever it held before. From ef9937a73c7db391d5434bfda08e96216d7099cc Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Tue, 22 Sep 2026 12:17:50 +0100 Subject: [PATCH 020/514] Software IEC: C64 OS / CMD DOS compatibility, crash fixes and logs (#881) * fix(iec): keep the parameter byte that looks like a terminator CBM DOS drops the carriage return PRINT# appends, which the 1541 ROM does at $C2B3. C followed by a shifted P carries its partition number as a byte and that byte can be 13, so it keeps it. G-P reported its type in the reserved byte, named the partition by its root path and answered one byte short. B-A and B-F take the three parameters both manuals document. The partition directory filters by type. * refactor(iec): move the CMD partition types out of the file system layer The generic FileSystem base class no longer knows what a CMD partition type is. It reports its track and sector geometry, in the terms read_sector() already uses, and the Software IEC drive maps that to the CMD type code and the three character name the partition directory prints. * feat(iec): log every Software IEC operation under a SOFTIEC-TRACE prefix Diagnostics for #877: one line per completed operation, never one per bus byte. Covered are the drive's configuration, OPEN, CLOSE, the addressing of a data channel, every command channel command, the error channel reads the host makes, the binary replies the drive queues, and the first fault on a channel. Each line carries the raw bytes in hex and in an escaped readable form, the parsed operation, the result and the resulting error channel response. A transfer is summarised by its length and its first and last sixteen bytes rather than by its contents. Every line starts with SOFTIEC-TRACE, and -DSOFTIEC_TRACE_ENABLED=0 compiles the whole thing out. * fix(iec): count the bytes the host took, not the bytes it was offered The transferred byte count in a SOFTIEC-TRACE CLOSE line was taken where the channel prefetches, so a channel the host addressed again counted the prefetched bytes it had not taken a second time: a 400 byte block read reported 433. It is now taken where the channel is told the bytes were accepted. Rewinding the read pointer would not have worked, because a buffer position command moves the same pointer as a retry does. * docs(iec): specify CMD DOS, sd2iec and C64 OS compatibility * docs(iec): decide every open question in the compatibility spec * docs(iec): keep the relative file layout and read both instead * docs(iec): correct the citations the spec review found * feat(system): report stack overflows and stack and heap head room The hook is in software/system/assert.c rather than ultimate.cc because every FreeRTOS image links assert.c, and the updaters would not link without it. Host test: target/pc/linux/rtosdiag. * fix(iec): answer the CBM DOS syntax error numbers Unrecognised commands answer 31, unknown sub-commands 30, illegal names 33, missing names 34, and a block outside the disk 66. Adds Suite11 to testdrive. * fix(iec): scratch, I, V and the partition directory answer as CBM DOS A scratch that matches nothing answers 01, I closes open channels and answers OK, V answers OK, and $=P has no blocks free line and shows the partition count. * feat(iec): add R-P, R-H, U0>, S-8/S-9/S-D, W-0/W-1 and M-R/M-W/M-E L is left for later: the file system layer has no call to set an attribute. software/test/stubs/iec_interface.cc gains the stub of the new IecInterface::readdress(). * fix(iec): hold 254 byte commands and names, refuse longer ones A command that fills the buffer answers 32 instead of running cut short, a carriage return second to last ends a command, and P keeps a last byte of 13. * fix(iec): left arrow is the parent only in the name position A path component may carry wildcards and has no depth limit, MD requires a colon and RD refuses a path. tests/e2e/io/iec/dos_command_test.py removes its directory with RD:name, since RD no longer takes a path. * fix(iec): directory listings load at $0401 and carry sizes and names Each line's link low byte is the size remainder, H is a flag and not a type, and the header names the listed directory. * fix(iec): write opens, G-P size, raw image names, rename and P on writes FileSystem::get_total and FileManager::get_total are added in software/filesystem and software/filemanager because G-P has to report a directory partition's volume size and nothing returned it. * feat(iec): N creates and formats D64, D71, D81 and DNP images It answered OK and did nothing. * fix(iec): map shifted spaces, * and ? to host names the same on every CPU petscii_to_fat compares the byte value and tests the byte that ended the run, escapes * and ?, and uses sd2iec's length guards. A wildcard scratch now scans the directory. softiec_target.cc passes the buffer size minus one like the other callers. Adds -funsigned-char builds of parse and iecdrive and device checks for the specification. * style: restore CRLF line endings in files edited since phase 1 * feat(iec): direct access buffers, attributes, raw directory, clock write and resets * feat(iec): read and write x00 files and read both relative file layouts * fix(iec): release listings, lock the drive across tasks, bound log and scratch * test(iec): find where U0> moved the drive before addressing it, accept a stale status * fix(iec): ##n opens up to nine chained buffers * refactor(iec): log only failed commands, opens and channel faults * test(uci): GET_IECNAME reads the name in an x00 header * fix(iec): four crashes found by a randomized drive soak * test(soak): Software IEC soak over the real bus with REST and FTP load * revert(system): drop the stack overflow check and the memory report * revert(iec): drop commands and modes that no report or program needs * refactor(iec): keep petscii_to_fat's length contract and log one rendering * fix(iec): P lengths, a 13 second to last, and a lone carriage return * fix(iec): N label length and inside images, scratch of locked twins and missing paths, long names * fix(iec): x00 files opened without a type, created over, copied, moved and with long names * fix(iec): run closures outside the drive lock, lock settings changes, bound the JiffyDOS spin * fix(iec): seek past the end in images, evicted listings, exponential patterns, leaks * test(soak): V is not a command, and $ on a data channel is a listing * test(soak): run without the REST and FTP lanes on request * docs(iec): record every requirement PR #881 decided against, and why * docs(iec): say what each partial implementation covers and whether C64 OS meets it * feat(iec): optional log of every Software IEC operation * docs(iec): describe the Log Every Operation setting * test(soak): compare the highest heap samples of the first and last quarter * docs(iec): say a log line shows the directory after the operation * docs(iec): note that another task's output can split a log line * docs(iec): give the split log line counts of both devices * test(soak): say a first U2+L session can pass the heap check * fix(iec): do not reset the IEC processor when only the log setting changes * test(iec): share the U0> drive move in the agent, drop unused imports * test(soak): add a realistic soak mode and a hostile stress mode * fix(iec): answer 65 NO BLOCK for B-A of an allocated block * docs(iec): record the B-A answer and the log setting reset fix * test(soak): quote the first anomalies of a phase * test(soak): open nine data channels, as many as the KERNAL table leaves * feat(iec): number every Software IEC log line * docs(iec): describe the log line sequence number * test(iec): let the agent verify its mailbox after a write * test(soak): cover the whole Software IEC surface and check the device log * test(soak): scratch the relative file grown to record 65535 whatever happens * test(soak): record a failed open as an open, count only readable sequence gaps * test(soak): pause the network lanes while a UCI step drives the target * test(soak): count sequence numbers of split lines and find split markers * test(soak): align log lines with operations by longest common subsequence * fix(iec): provide host HTTP status codes * test(iec): listing end of file and stamped line layout * fix(iec): send EOI on the last listing byte, pad stamped lines * test(iec): GEOS entry types and reads inside an image * fix(iec): list GEOS files by their own type, read the file not the CVT * docs(iec): record SI-149's read half as a 3.15 regression * Rename a subdirectory with R, as HD 9-26 and sd2iec do --- doc/softiec_compatibility_spec.md | 2186 ++++++++++++ run-tests | 8 + software/chan_fat/full/ffconf.h | 2 +- software/chan_fat/pc/ffconf.h | 2 +- software/components/pattern.cc | 90 +- software/filemanager/filemanager.cc | 87 +- software/filemanager/filemanager.h | 8 +- software/filesystem/file_info.h | 3 + software/filesystem/file_system.h | 18 +- software/filesystem/filesystem_d64.cc | 89 +- software/filesystem/filesystem_d64.h | 10 +- software/filesystem/filesystem_fat.cc | 23 + software/filesystem/filesystem_fat.h | 5 +- .../io/command_interface/softiec_target.cc | 11 +- software/io/iec/cbmdos_parser.cc | 277 +- software/io/iec/cbmdos_parser.h | 40 +- software/io/iec/cbmdos_parser_test.cc | 526 ++- software/io/iec/cbmdos_stubs.cc | 74 +- software/io/iec/iec_channel.cc | 1282 +++++-- software/io/iec/iec_channel.h | 70 +- software/io/iec/iec_drive.cc | 93 +- software/io/iec/iec_drive.h | 25 + software/io/iec/iec_interface.cc | 43 +- software/io/iec/iec_interface.h | 5 + software/io/iec/iec_log.h | 90 + software/io/iec/iec_ui.h | 1 + software/io/stream/stream_textlog.h | 12 +- software/network/syslog.cc | 6 +- software/test/iecdrive/d64.cc | 85 + software/test/iecdrive/macros.h | 1 + software/test/iecdrive/testdrive.cc | 3063 ++++++++++++++++- software/test/stubs/http_codes.h | 18 + software/test/stubs/iec_interface.cc | 7 + target/pc/linux/iecdrive_asan/Makefile | 7 + target/pc/linux/iecdrive_unsigned/Makefile | 6 + target/pc/linux/parse_unsigned/Makefile | 7 + .../io/command_interface/uci_targets_test.py | 39 + tests/e2e/io/iec/README.md | 8 +- tests/e2e/io/iec/dos_command_test.py | 349 +- tests/e2e/io/iec/iec_agent.py | 45 +- tests/soak/README.md | 4 +- tests/soak/io/iec/softiec_log.py | 907 +++++ tests/soak/io/iec/softiec_soak_test.py | 2129 ++++++++++++ 43 files changed, 11299 insertions(+), 462 deletions(-) create mode 100644 doc/softiec_compatibility_spec.md create mode 100644 software/io/iec/iec_log.h create mode 100644 software/test/stubs/http_codes.h create mode 100644 target/pc/linux/iecdrive_asan/Makefile create mode 100644 target/pc/linux/iecdrive_unsigned/Makefile create mode 100644 target/pc/linux/parse_unsigned/Makefile create mode 100644 tests/soak/io/iec/softiec_log.py create mode 100644 tests/soak/io/iec/softiec_soak_test.py diff --git a/doc/softiec_compatibility_spec.md b/doc/softiec_compatibility_spec.md new file mode 100644 index 000000000..88e268c19 --- /dev/null +++ b/doc/softiec_compatibility_spec.md @@ -0,0 +1,2186 @@ +# Software IEC: CMD DOS, sd2iec and C64 OS compatibility + +**Status: specification.** This describes what is to be built. It is not a +description of what the firmware does today, except where it cites current code by +file and symbol, and every such citation is labelled as current behaviour. A reader +who wants to know what the firmware does now should read +[software/test/iecdrive/doc.md](../software/test/iecdrive/doc.md), +[doc/filenames_design.txt](filenames_design.txt) and +[tests/e2e/io/iec/README.md](../tests/e2e/io/iec/README.md). + +PR #881 implements this specification only in part. A review of the implementation +applied one rule: a requirement is implemented when it fixes a defect, or when the +reporter of #877, #890 or #917, the C64 OS author's article "Gaps in Software IEC" (GAP) +or +the C64 OS boot trace (TRACE) names it. Every requirement that PR #881 decided not to +implement, or implemented differently from what is written here, carries a paragraph +that starts with **Decision (PR #881)** directly below it, stating what was decided, +why, and what the drive answers instead. Section 18.1 lists all of them in one table. +The "Current behaviour" statements describe the firmware before PR #881. + +The goal is that an Ultimate 64 or Ultimate II+ can be the system drive of C64 OS, +and that in doing so it also becomes a closer replacement for an sd2iec, a CMD HD, a +CMD FD, a CMD RAMLink and an IDE64 for every other program that already targets +those. Issues [#877](https://github.com/GideonZ/1541ultimate/issues/877) and +[#890](https://github.com/GideonZ/1541ultimate/issues/890) are the immediate +drivers, with [#917](https://github.com/GideonZ/1541ultimate/issues/917) added later; this document covers the whole command surface those issues sit in, so the +work can be done once rather than one report at a time. + +This is not a greenfield design. The Software IEC drive has shipped for years to a +large install base, and several of the behaviours below are already correct. Every +requirement therefore states the source of truth, what the firmware does now, and +whether anything has to change. Requirements that change nothing are kept because +they are the contract that later work must not break. + +Where a statement about current behaviour says "measured", it was obtained by running +the command against the head of PR #881, using a probe linked against the same object +files `target/pc/linux/iecdrive` links. The rest were read from the source, and each +names the file and symbol so a reader can check it. + +Nothing in this document is left open. Where the sources disagreed, section 16 states +which primary source settled it, and for two of the cases that source is the 1541 ROM +in `roms/1541.bin` rather than any manual. + +--- + +## 1. Sources of truth and how conflicts are settled + +### 1.1 Source register + +| Code | Source | +| --- | --- | +| **HD** | *CMD HD Hard Drive User's Manual*, 4th edition, January 1991. The scan linked on issue #877, `primrosebank.net/computers/pet/documents/CMD-HDD-Manual_OCR.pdf`. Page numbers are the manual's own, e.g. 9-15, B-2. | +| **HDR** | *CMD HD Manual Remaster V0.2*. Same text, cleaner typesetting. Used to resolve OCR damage in HD. | +| **FD** | *CMD FD-Series Disk Drives User's Manual*. | +| **RL** | *CMD RAMLink User's Manual*. | +| **IDE** | *The IDE64 Project user's guide*, IDEDOS 0.90, 24 February 2019. Section numbers as printed. Linked by the reporter on #877. | +| **SD** | sd2iec, the `markusC64/sd2iec` fork, at commit `9087321`. Paths are `src/...`. `SD README` is that fork's README, which the reporter named as its documentation. | +| **1541** | *1541-II Disk Drive User's Guide*, DOS error message list. Where a point needs a Commodore drive other than the 1541, the *1571* and *1581 User's Guides* are cited by name. | +| **ROM** | `roms/1541.bin` in this repository, 16384 bytes, mapping to `$C000..$FFFF`. Quoted disassembly was produced from that file. | +| **GAP** | Greg Nacu, "Gaps in Software IEC", c64os.com/post/softwareiecgap, 10 January 2023. The canonical statement of why C64 OS does not support this drive. Written against firmware 3.10a; several of its items are already fixed. | +| **GSD** | Greg Nacu, "SD2IEC User's Manual" v1.3, c64os.com/post/sd2iecdocumentation. | +| **GFN** | Greg Nacu, "Understanding SD2IEC Filenaming", c64os.com/post/sd2iecfilenames. | +| **GUG** | *C64 OS User's Guide*, File System chapter, c64os.com/c64os/usersguide/filesystem. | +| **917** | Issue [#917](https://github.com/GideonZ/1541ultimate/issues/917), "More SoftIEC compatibility issues", opened by the reporter on 18 September 2026. It carries Greg Nacu's measurements of a CMD HD and an sd2iec against this drive, and photographs of the two BASIC programs he used. The programs are transcribed in appendix C. | +| **TRACE** | `log_boot.log.txt`, attached by the reporter to #877 on 11 September 2026. 601 lines of `SOFTIEC-TRACE` output from one successful C64 OS boot on a U64 II. | +| **U** | This firmware at PR #881 head `16f7e31b`. Paths are relative to the repository root. | + +### 1.2 Precedence + +The reporter set the rule on #877, 11 September 2026: "If the sources differ, then +you have to decide on a case-by-case basis, but most of the time it will come down +to the decision I made in my SD2IEC branch, because that's where I made the +decision." + +This specification applies it as follows. + +1. Where CMD DOS defines a behaviour and every later device copied it, that + behaviour is normative. HD is the reference text, with FD and RL used for the + points where the three CMD devices differ from each other. +2. Where a behaviour exists only because a device has a host file system underneath + it, **SD** is normative, because that is the device the Ultimate most resembles + and the one the reporter maintains. +3. Where IDE and SD disagree, SD wins, and the difference is recorded in section 16. +4. Where a source disagrees with the reporter's own measurement on real hardware, + neither wins on authority. The disagreement is resolved from a primary source that + can settle it, normally the 1541 ROM in `roms/1541.bin`, and section 16 states the + evidence. Nothing in this document is left open. +5. Ultimate extensions are allowed where they cannot be mistaken for a documented + command and do not change the answer to one. + +### 1.3 Acceptance + +The specification is met when all of the following hold. + +* **A1.** C64 OS installs on, boots from and runs from a Software IEC partition, with + no error on the command channel that a CMD HD would not also produce. +* **A2.** Every requirement below has at least one automated test, in + `target/pc/linux/parse`, `target/pc/linux/iecdrive` or `tests/e2e/io/iec`, and the + test fails when the behaviour is reverted. +* **A3.** No behaviour marked "Unchanged" in section 15.2 has changed. + +--- + +## 2. The model + +### 2.1 Device, partitions, directories + +**SI-001.** The drive presents one IEC device number, configurable from 8 to 30. +Current behaviour: `U software/io/iec/iec_drive.cc`, `CFG_IEC_BUS_ID`, range 8..30, +default 11. Unchanged. GUG confirms C64 OS expects storage devices in 8..30 and +supports up to five at a time. + +**SI-002.** The drive presents partitions numbered 1 to 255. Each partition has a +name, a root directory on the host virtual file system, and its own current +directory. Partition 0 is not a partition a user can enter; as a parameter it means +"the current partition". Sources: HD 9-8 and 9-10 (1 to 254 on the HD, 0 means the +current partition), FD (1 to 31), RL (1 to 31), IDE 15.3.1 ("Partition 0 is not a +valid parameter"), GUG ("CMD devices support 255 partitions, numbered from 1 to 255. +Partition 0 is a special system partition that cannot be accessed directly"). +Current behaviour: `U iec_channel.h`, `is_valid_partition_number()` accepts 1..255 +and `IecFileSystem::GetTargetPartitionNumber()` maps any index below 1 to the +current partition. Unchanged. + +**SI-003.** A partition's root may be a directory on the host file system or a +mounted CBM disk image, because the Ultimate virtual file system mounts `.d64`, +`.d71`, `.d81` and `.dnp` images as directories. Unchanged. + +**SI-004.** The blocks free reported for any directory is the free space of the +partition, not of the directory. Source: HD 4-5, "all of the blocks within a Native +Mode partition are shared between all directories within that partition". +Current behaviour: `U IecChannel::setup_directory_read()` calls `fm->get_free()` on +the listed directory's own path. Unchanged in effect, because the host file system +reports per-volume free space. + +### 2.2 What the partition model must not do + +**SI-005.** The root of a partition is a real directory. Files can be created in it, +it can be listed, and its blocks free is that of the partition. GAP's principal +objection was that the drive presented its storage devices as directory entries of a +pseudo root that could hold no files. Current behaviour: a partition root is an +ordinary host directory, so this holds. Unchanged, and stated so that it is not +regressed. + +--- + +## 3. Command string grammar + +### 3.1 Path syntax + +**SI-010.** The grammar of a name or command argument is + +``` +[@] [partition] [path] [:] name +``` + +with `partition` a decimal number, and `path` a sequence of `/`-delimited +components. A path beginning with `//` starts at the root of the partition; a path +beginning with a single `/` starts at the current directory of the partition; a +missing path means the current directory. Every component is followed by a slash. +The final slash before a name is written, and the name is introduced by a colon. +Sources: HD 9-2 to 9-4 with the worked examples `LOAD"1/UTILITIES/COPIERS/:COPY",12`, +`LOAD"//UTILITIES/COPIERS/:COPY",12`, `LOAD"1//UTILITIES/COPIERS/:COPY",12` and +`LOAD"1//:BOOTQ",12` (HD 7-2); IDE 6.1; GUG, "The root directory is specified by two +leading front slashes. Each subdirectory is added to the path by specifying the +subdirectory name followed by a single trailing slash. The trailing slash is always +required." + +Current behaviour: `U iec_path_to_fs_path()` in `software/io/iec/iec_channel.cc` +strips a single leading slash, rewrites `_` to `..`, then collapses `//` to `/`, +which produces exactly this. GAP's complaint that a single slash meant the root is +out of date. Unchanged. + +**SI-011.** The colon is optional when the name is preceded by a slash. Source: +HD 9-19, "It is not required that you include the colon before the subdirectory +name, as long as the subdirectory name is preceded by a slash." Unchanged. + +**SI-012.** A path component may contain wildcards, and the first match is used. +Sources: SD README under CD/MD/RD, "You can use wildcards anywhere in the path"; +IDE 6.2, "These wildcards can be used in path elements or filename too, in this case +the first filename will be matched." Current behaviour: `U resolve_directory_path()` +calls `find_rendered_iec_child()` with `allow_wildcards` false for every component. +**Change required.** `.` and `..` as path components already work there and are a +deliberate extension beyond the CMD devices; GAP calls them out as "something that +none of the other devices can do". + +**SI-013.** The partition number may replace the drive number in any command that +accepts one, except the direct access commands. A direct access channel is bound to +the partition that was current when the channel was opened, and the partition +parameter of `B-R`, `B-W`, `U1`, `U2`, `B-A`, `B-F` and `B-E` is therefore always +written as 0. Source: HD 9-8 and 9-44; GSD "Partition Numbers in Disk Commands". +(IDE 15.5 does not state this rule: IDEDOS direct access addresses sectors by LBA and +has no partition parameter.) **Change required:** the current implementation resolves the partition +parameter of the block commands against the partition table +(`U IecCommandChannel::do_block_read()` and its siblings call `GETPARTITION(part,...)`), +which means a program that correctly sends 0 gets the current partition only by +accident of `GetTargetPartitionNumber()`, and a program that sends a real number +addresses a partition the channel was not opened on. + +### 3.2 The left arrow + +**SI-014.** PETSCII `$5F`, the left arrow, means the parent directory when it stands +in the *name* position, that is directly after `CD[n]` or directly after a colon. It +is an ordinary character when it stands in a *path component* position, that is +between slashes. + +| Command | Required result | Source | +| --- | --- | --- | +| `CD<-` | parent directory | HD 9-19, "you can include the back arrow immediately after `CD[n]` to move backwards one directory"; `SD do_chdir()`, `name[0]=='_' && !name[1]` | +| `CD:<-` | parent directory | `SD do_chdir()`, same branch reached through `parse_path`; Greg Nacu measured this on a real CMD HD and on an IDE64 and reported it through the reporter on #877: "cd:<- doesn't go into the directory, it goes up a directory" | +| `CD/<-` | change into the child directory literally named `<-` | Greg Nacu, same measurement, "cd/<- works to go into that directory"; `SD parse_path()` treats a component between slashes with `first_match()` | +| `MD:<-` | create a directory named `<-` | Greg Nacu, same measurement | +| `RD:<-` | remove it | Greg Nacu, same measurement | + +Current behaviour: `U iec_path_to_fs_path()` rewrites every `_` to `..` wherever it +appears, so `CD/<-` goes to the parent instead of entering the directory, and a +directory named `<-` cannot be reached at all. **Change required.** The rewrite must +happen only in the name position, which `U IecCommandChannel::do_change_dir()` +already isolates for the `CD:<-` case. + +This has one consequence for existing behaviour that has to be accepted +deliberately. `CD/<-/OTHERDIR`, going up and then down again in one command, works +today and is covered by `Suite8-CD-PARENT-OTHERDIR` in +`software/test/iecdrive/testdrive.cc`. After this change the left arrow in that +position is a directory name and the command fails. The capability itself is not +lost: `U resolve_directory_path()` also accepts `.` and `..` as path components, so +`CD/../OTHERDIR` does the same thing, and `..` is the spelling GAP singles out as +"something that none of the other devices can do". The existing test moves to `..`. + +**SI-015.** `CD/:<-` goes to the parent. The colon introduces the name, so the arrow +is in the name position and SI-014 applies unchanged. Sources: `SD do_chdir()`, which +reaches its `name[0]=='_'` branch for this spelling; HD 9-19, "The back arrow cannot +be combined with any subdirectory path information", which says the arrow is not a +path element and therefore only ever a name. The reporter wrote on #877 that this +form should enter the directory, but also that he had "no reference for `cd/:<-` +except trying in an emulator". One rule that explains both of Greg Nacu's hardware +measurements is worth more than a second rule for a spelling nothing sends: to enter +a directory named `<-` the command is `CD/<-`. See section 16, C2. + +### 3.3 The command terminator + +**SI-016.** One trailing carriage return is removed from a command before it is +parsed, and a command whose second to last byte is a carriage return is truncated at +that carriage return. This is what CBM DOS does. ROM, at `$C2B3`, reached from the +command dispatcher at `$C160`: + +``` +C2B3 A4 A3 LDY $A3 ; bytes received +C2B5 F0 14 BEQ $C2CB ; 0 bytes: keep 0 +C2B7 88 DEY +C2B8 F0 10 BEQ $C2CA ; 1 byte: keep 1 +C2BA B9 00 02 LDA $0200,Y ; last byte +C2BD C9 0D CMP #$0D +C2BF F0 0A BEQ $C2CB ; last byte is CR: length becomes len-1 +C2C1 88 DEY +C2C2 B9 00 02 LDA $0200,Y ; second to last byte +C2C5 C9 0D CMP #$0D +C2C7 F0 02 BEQ $C2CB ; second to last is CR: length becomes len-2 +C2C9 C8 INY +C2CA C8 INY +C2CB 8C 74 02 STY $0274 ; the length the parser uses +``` + +Current behaviour: `U strip_terminator()` in `software/io/iec/cbmdos_parser.cc` +removes one trailing carriage return only. The second branch is missing. +**Change required**, and it is not cosmetic: it is the reason CMD's manual tells +programmers to append the terminator themselves when a parameter can be 13. + +**Decision (PR #881): implemented in part.** The second branch drops a carriage return +second to last only when a line feed follows it, which is what BASIC's `PRINT#` to a +logical file number of 128 or more sends (C64 ROM `$AAD7`). The ROM's branch also cuts a +binary parameter of 13 short, for example the high byte of an `M-R` address or a count +of 13, and the reporter of #877 wrote that "needing an additional CR for some commands +do not need to be reproduced". A lone carriage return, which is an empty command after +the strip, answers `31`, as the ROM does at `$C175` and as sd2iec does. + +**SI-017.** The binary Change Partition command is exempt from SI-016, because its +parameter byte is mandatory and cannot be a terminator. Current behaviour: +`U strip_terminator()` already exempts `C` followed by `$D0`. Unchanged. + +**SI-018.** The Position command is exempt from SI-016, because its last parameter +byte is data. Source: `SD parse_position()` begins `command_length = +original_length;`, restoring the length from before the strip. **Change required.** + +**Decision (PR #881): implemented with one difference from sd2iec.** The record number +and the offset of a relative file are read from the command as sent, so a 13 in the +offset's place is the offset, as the ROM reads it at `$E23E`. The position in a plain +file (SI-082) is read from the command without its terminator. sd2iec reads it from +the command as sent, which makes the documented BASIC form `"P"+CHR$(ch)+CHR$(lo)` +position to `lo + 13*256`; before PR #881 this drive stripped the terminator and +positioned to `lo`, and keeping that avoids a regression for the form GSD documents. A +record number sent without an offset and without a terminator, as a machine language +caller sends it, takes both of its bytes. + +**SI-019.** Where the last parameter is optional, the terminator wins, so partition +13 has to be asked for with the terminator sent explicitly. Source: HD 9-16, +"To avoid problems with reading information from Partition 13, the G-P command +should always be sent with a trailing carriage return (CHR$(13))." Unchanged. + +### 3.4 Numeric parameters + +**SI-020.** The numeric parameters of the block and user commands are separated by +any run of spaces, commas or cursor-right characters, and a colon may stand between +the command word and the first parameter. Source: HD 9-5 and 9-6, which show +`PRINT#15,"U1";2;0;1;34`, `PRINT#15,"U1 2 0 1 34"` and `PRINT#15,"U1:";2;0;1;34` +as equivalent. Unchanged; `U parse_block_parameters()` implements it. + +### 3.5 Command length + +**SI-021.** The command channel buffer holds at least 254 bytes, and the name buffer +of a data channel holds at least 254 bytes. Sources: HD 4-6, "the input buffer of +the HD is only 254 characters long"; SD `CONFIG_COMMAND_BUFFER_SIZE`, 120 on the +small AVR boards and 254 on uIEC; GUG, "The total length of the directory path, +including all the slashes is 232 characters", which is the binding number, because a +C64 OS path plus a partition number, a colon and a 16-character name does not fit in +anything smaller. + +Current behaviour: `U iec_channel.h` declares `wr_buffer[65]` and both +`IecCommandChannel::push_data()` and `IecChannel::push_data()` stop storing at 64 +bytes. **Change required.** + +**SI-022.** A command longer than the buffer answers `32,SYNTAX ERROR` and is not +executed. Sources: HD B-2, error 32; `SD parse_doscommand()`, which returns +`ERROR_SYNTAX_TOOLONG` when the command fills the buffer; ROM `$C2CE`, which raises +error 32 when the command length reaches 42. + +Current behaviour: the excess bytes are counted in `trace_cmd_dropped` and +discarded, and the truncated command is then executed. **Change required**, and this +is a data loss defect rather than a compatibility one: a `S` command truncated in the +middle of a path scratches files in the wrong directory. + +**Decision (PR #881): implemented, and extended to names.** A command of 254 bytes or +more answers `32` and is not executed. An OPEN name of 254 bytes or more answers `32` as +well and opens nothing, rather than creating or reading a file under its first bytes. + +--- + +## 4. Error codes + +### 4.1 The table + +The drive's own table in `U software/io/iec/iec_drive.cc` already carries the right +numbers and strings. What is wrong is the parser's private constants, which the +parser returns to the drive. + +**SI-030.** `U software/io/iec/cbmdos_parser.h` defines + +```c +#define ERR_SYNTAX 30 +#define ERR_ILLEGAL_CHARS 31 +#define ERR_ILLEGAL_NAME 32 +#define ERR_UNKNOWN_CMD 33 +``` + +The names and the numbers do not agree with CBM or CMD DOS. The correct meanings +are, from HD B-2 and 1541: + +| Code | Meaning | Raised when | +| --- | --- | --- | +| 30 | SYNTAX ERROR (general) | the command was recognised but could not be parsed | +| 31 | SYNTAX ERROR (unrecognized command) | the first character is not a command letter | +| 32 | SYNTAX ERROR (command string too long) | over the command buffer | +| 33 | SYNTAX ERROR (illegal file name) | a wildcard where wildcards are not accepted | +| 34 | SYNTAX ERROR (missing file name) | no name, or a missing colon | + +**Change required:** rename the constants to their real meanings and correct the +return sites. There are 35 of them in `cbmdos_parser.cc`; these are the ones whose +value changes. Every other site returns 30, which stays 30 because the command letter +was recognised and only its arguments were not. + +| Site | Condition | Today | Required | +| --- | --- | --- | --- | +| `execute_command()` final `return` | first character is not a command letter | 33 | **31** (SI-031) | +| `parse_full_path()`, empty name | a colon with nothing after it | 32 | **34** | +| `parse_open()`, `contains_any(",=:\xA0\r")` | illegal character in a name | 31 | **33** | +| `copy_command()`, `dest.has_wildcard` | wildcard in the copy target | 32 | **33** | +| `rename_command()`, `dest.has_wildcard` | wildcard in the rename target | 32 | **33** | +| `block_command()` default | `B` followed by an unknown letter | 33 | **30** | +| `dir_command()` defaults | `C`, `M` or `R` followed by an unknown letter | 33 | **30** | +| `get_command()` default | `G` followed by an unknown letter | 33 | **30** | +| `user_command()` default | `U` followed by an unknown letter | 33 | **30** | +| `time_command()` final `return` | `T` followed by an unknown letter | 33 | **30** | +| `extended_command()` | `X` or `E` followed by an unknown word | 33 | **30** | + +**SI-031.** An unrecognised command answers `31`. Verified in ROM at `$C160`: + +``` +C160 20 B3 C2 JSR $C2B3 ; strip the terminator first +C163 B1 A3 LDA ($A3),Y ; first byte of the command +C165 8D 75 02 STA $0275 +C168 A2 0B LDX #$0B ; twelve command letters +C16A BD 89 FE LDA $FE89,X +C16D CD 75 02 CMP $0275 +C170 F0 08 BEQ $C17A ; found: dispatch +C172 CA DEX +C173 10 F5 BPL $C16A +C175 A9 31 LDA #$31 ; not found: error 31 +C177 4C C8 C1 JMP $C1C8 +``` + +and stated in 1541 ("31: SYNTAX ERROR (invalid command). The DOS does not recognize +the command. It must begin with the first character sent.") and HD B-2. The reporter +asked for 31 on #877 on 11 September 2026, having measured `33` for a one-byte +command `CHR$(0)` and for `A`. + +Current behaviour: `U IecParser::execute_command()` returns `ERR_UNKNOWN_CMD`, which +is 33. **Change required.** + +Note the divergence: `SD parse_doscommand()` answers 30 here and reserves 31 for an +empty command. This specification follows HD, 1541, ROM and the reporter's stated +expectation rather than SD, and section 16 records it as C1. + +**SI-032.** Opening a name for writing has four cases, and each has a different +answer. + +| Case | Answer | Source | +| --- | --- | --- | +| wildcard, no `@` | `33` | 1541: "Pattern matching characters cannot be used in the Save command or when Opening files for the purpose of Writing new data"; `SD file_open()` | +| `@`, the pattern matches a file of the same type | replace it, keeping the **matched** file's name rather than the pattern | ROM `$D8FC` falls through on a type match (the ROM says nothing about which name is kept); IDE 7.1; `SD file_open()` for the name rule | +| `@`, the pattern matches a file of a different type, or matches a REL file | `64,FILE TYPE MISMATCH` | ROM `$D8F5` | +| `@`, the pattern matches nothing | `64` | `SD file_open()` | + +The third row is the one that reconciles the sources, and it comes straight out of +the 1541 ROM. The save-with-replace path compares the type of the entry it found +against the type the open asked for: + +``` +D8E1 AD 00 02 LDA $0200 ; first byte of the name +D8E4 C9 40 CMP #$40 ; '@' ? +D8E6 F0 0D BEQ $D8F5 ; yes: the replace path +... +D8F5 A5 E7 LDA $E7 ; the found entry's type byte +D8F7 29 07 AND #$07 ; 0 DEL, 1 SEQ, 2 PRG, 3 USR, 4 REL +D8F9 CD 4A 02 CMP $024A ; the requested type +D8FC D0 67 BNE $D965 ; different -> error 64 +D8FE C9 04 CMP #$04 ; REL? +D900 F0 63 BEQ $D965 ; also error 64 +... +D965 A9 64 LDA #$64 +D967 4C C8 C1 JMP $C1C8 ; CMDERR +``` + +`SAVE` asks for PRG. So `SAVE"@:foo*"` answers `64` on a real drive whenever the +first entry matching `foo*` is not a PRG, which is what the reporter reported on +#877 ("real floppy return 64", 11 September 2026), and it replaces the file when it is. The same check guards the ordinary open +at `$D95C`, which is where the `64` of SI-035 comes from. + +`SD file_open()` produces the same four answers, by a different route for the last +row: + +```c +if (ustrchr(fname, '*') || ustrchr(fname, '?') || (*fname == 160)) { + if (command_buffer[0] == '@') set_error(64); + else set_error(33); + return; +} +``` + +(`src/fileops.c` at `9087321`; commit `a76deb2` introduced the `*` and `?` tests and +the `160` test was added later.) + +Current behaviour: `U parse_open()` does not reject a wildcard in a write name at +all. The 33 the reporter saw is produced further down, by the file system layer +refusing a host name that contains `*`, so none of the four cases can be told apart +where they have to be. **Change required**, in the parser and in the open path. + +**SI-033.** Scratching nothing is not an error. The answer is +`01,FILES SCRATCHED,00,00`. Sources: HD B-1, "01 FILES SCRATCHED (not an error). +The number of files scratched will be indicated in the track variable"; +`SD parse_scratch()`, which ends unconditionally with +`set_error_ts(ERROR_SCRATCHED,count,0)`; IDE 15.2.2, which shows the count in the +track field. + +Current behaviour: `U IecCommandChannel::do_scratch()` returns +`ERR_FILE_NOT_FOUND` when the count is zero. TRACE shows C64 OS hitting exactly this +with `S/TEMPORARY/:*`. **Change required.** + +**Decision (PR #881): implemented, with a path check.** A scratch whose path does not +exist answers `71,DIRECTORY ERROR` with the partition number, instead of +`01,FILES SCRATCHED,00,00`, so a mistyped path is reported rather than looking like an +empty directory. sd2iec also reports the path error (`SD parse_scratch()`). + +**SI-034.** Selecting a partition that does not exist answers +`77,SELECTED PARTITION ILLEGAL`. Source: HD B-5. Unchanged. + +**SI-035.** Opening a file for writing when one of that name exists, without `@`, +answers `63,FILE EXISTS`. Opening for reading when none exists answers +`62,FILE NOT FOUND`. Opening an existing REL file with a non-REL type answers `64`. +Sources: HD B-3 and B-4; `SD file_open()`. Unchanged; covered by Suite5 of +`software/test/iecdrive/testdrive.cc`. + +### 4.2 Errors that must stop being reported as 69 + +**SI-036.** `69,FILESYSTEM ERROR` is an Ultimate code with no counterpart on any +other device. It must not be the answer to a condition that CBM DOS names. +`U IecDrive::set_error_fres()` maps the unmapped `FRESULT` values to it and puts the +raw `FRESULT` in the track variable. Every path that can reach a user must map to a +documented code first. The known case is SI-083. + +--- + +## 5. Partition commands + +### 5.1 Change partition + +**SI-040.** `CPn`, with the number in ASCII, and `C` followed by shifted P (`$D0`) +with the number as one binary byte, both select a partition and answer +`02,PARTITION SELECTED,,00`. Sources: HD 9-10, FD, RL, IDE 15.3.1, SD README. +Unchanged since #878 and #881; TRACE shows C64 OS using the binary form 29 times in +one boot and the ASCII form once. + +### 5.2 Get partition info + +**SI-041.** `G-P` with no parameter, or with 255, answers for the current partition. +With 0 it answers for the system partition, which this drive does not have, so byte 0 +is 0, meaning "not created", and byte 2 is 0. With any other value it answers for +that partition, and again byte 0 is 0 if it does not exist. Current behaviour: +`U IecParser::get_command()` rewrites 255 to 0 and passes an absent parameter as 0, +and `U do_get_partition_info()` then resolves 0 to the current partition, so all +three cases give the same answer. **Change required:** 0 and "absent" are different +questions. +The answer is 30 bytes followed by `CHR$(13)`, laid out as HD 9-15 and 9-16 give it: + +| Byte | Content | +| --- | --- | +| 0 | partition type: 0 not created, 1 native, 2 1541, 3 1571, 4 1581, 5 1581 CP/M, 6 print buffer, 7 foreign, 255 system | +| 1 | reserved, `CHR$(0)` | +| 2 | partition number | +| 3-18 | partition name as shown in the partition directory | +| 19-21 | start address, high to low | +| 22-26 | reserved, `CHR$(0)` | +| 27-29 | size, high to low | +| 30 | `CHR$(13)` | + +Bytes 19-21 and 27-29 are counted in 512-byte blocks on the HD and the FD and in +256-byte blocks on RAMLink (RL, same page). This drive follows the HD and uses 512. + +Current behaviour: correct since PR #881, including the type in byte 0 and the +partition's own name in bytes 3 to 18. What remains wrong is that byte 27 is set to +`0xFF` as a placeholder, so every partition reports a size of 16711680 blocks. +**Change required:** report the real free-plus-used size of the partition's file +system, clamped to `0xFFFFFF`, which is what `SD parse_getpartition()` does. + +**SI-042.** Byte 1 stays zero. The FD redefines it as a disk-information bit field +(FD, Getting Partition Information: bit 7 disk present, bit 6 formatted, bit 5 valid +CMD or CBM format, bit 4 true 1581, bits 3-0 density) and sd2iec writes `0xE2` there, +which decodes as an FD-2000 with a 1.6 MB disk inserted. This drive is not an FD and +must not claim to be one. IDE leaves the byte unused (IDE table 26). + +**SI-043.** The partition type is decided from the file system at the partition's +root. Current behaviour, added in PR #881: `U cbm_partition_type_of()` reads the +geometry, mapping no track and sector addressing or 256 sectors per track to native, +40 sectors to 1581, and 21 sectors to 1541 or 1571 by track count. This reaches the +same mapping `SD pdir_refill()` reaches from the image type +(`(imagetype & D64_TYPE_MASK) + TYPE_NAT - 1` with `D64_TYPE_DNP == 1`, so a DNP +image lists as native). Unchanged. + +### 5.3 Partition directory + +**SI-044.** `LOAD"$=P[:pattern][=tp]"` lists the partitions. `tp` is one of `N`, `4`, +`7`, `8`, `C`. Sources: HD 9-14; FD and RL, which drop `C`; SD README. Unchanged +since PR #881. + +**SI-045.** The listing is a header line, one line per partition, and the BASIC end +marker. **There is no blocks free line.** Source: issue #890; GAP, "The partition +directory does not list a blocks free count"; `SD pdir_refill()`, whose last act is + +```c +buf->lastused = 1; +buf->sendeoi = 1; +memset(buf->data,0,2); +``` + +Current behaviour: `U IecChannel::read_dir_entry()` shares its end-of-listing path +with the file directory and emits `0 BLOCKS FREE.`. **Change required.** This is +issue #890. + +**SI-046.** The number printed before the header name is the number of partitions. +Sources: GAP, "The first number before the partition directory's header line is a +count of how many "user" partitions there are"; `SD load_directory()`, +`buf->data[HEADER_OFFSET_DRIVE] = max_part`. Current behaviour: +`U IecChannel::setup_partition_read()` copies `c_header` and never sets byte 4, so +the number is 0. **Change required.** + +**SI-047.** The block count column of each partition line is the partition number. +Sources: GAP, "The typical block size of a directory entry is used for the partition +number"; `SD pdir_refill()`, `dent.blocksize = part + 1`. Current behaviour: +`U read_dir_entry()` sets `info.size = part_idx * 254` so that the block conversion +yields the partition number. Unchanged. + +**SI-048.** The type column is the three-character partition type: `NAT`, `41 `, +`71 `, `81 `. Sources: issue #877; SD `filetypes[]` entries 8 to 11. Unchanged since +PR #881. + +**SI-049.** The header name is the drive's name, not a partition's. `SD` uses the +static string `SD2IEC` with id `IK`. This drive uses `ULTIMATE HD` with id `UL 64`, +which is already in `U setup_partition_read()`. Unchanged. + +**SI-050.** A `SYSTEM` line is not emitted. `SD` emits one from `syspart_line[]` +immediately after the header, and IDE lists partition 255 as the disk label line. +This drive has no system partition, and SI-041 already answers `G-P 0` with type 0. +Recorded so the omission is deliberate rather than accidental. + +### 5.4 Other partition commands + +**SI-051.** `R-P:newname=oldname` renames a partition. Source: HD 9-14, FD, RL. +Not implemented. `U execute_command()` routes every `R` whose second character is not +`D` to `rename_command()`, which strips the leading letter and then hands `-P:WORK` +to `parse_full_path()`; that rejects the `-` and answers `30`. **Change required:** +recognise `R-P` and `R-H` before falling through to the file rename, as +`SD parse_doscommand()` does with `if (command_length > 2 && command_buffer[1] == '-')`. + +**Decision (PR #881): not implemented.** Neither report nor GAP nor TRACE uses `R-P`, +and the rename would live only in memory until the partition list is saved from the +menu. The drive answers `30`, as before. + +**SI-052.** `N[n]:name[,id]` formats. Its full behaviour is specified in SI-071. + +**SI-053.** `I[n][:]` initialises. On a device with no removable medium this is a +no-op that answers `00, OK` and frees the user buffers. Sources: HD 9-13, "This +function is performed automatically by the HD, but the command has been implemented +to retain compatibility"; `SD parse_initialize()`, which frees the user buffers. +Current behaviour, measured: `I` answers `73,U64HD ULTIMATE DOS V2.0,00,00`, because +`U IecCommandChannel::do_initialize()` returns `ERR_DOS` and `U user_command()` +routes `UI` to the same executer method. **Change required:** `I` and `UI` are different commands and must +answer differently. `I` answers `00, OK`; `UI` answers the 73 message. + +**SI-054.** `V[n][:]` validates. On a host file system there is nothing to validate, +so it answers `00, OK` without doing anything, which is the same position HD 9-13 +takes for `I`. Not implemented; **change required** (it currently answers 31 after +SI-031, or 33 today). + +**Decision (PR #881): not implemented.** Inside a mounted disk image, validating means +rebuilding the block availability map from the directory, and answering `00, OK` +without doing it would tell a program that the image was checked. The reporter wrote on +#877 that "V not implemented, but that's ok for the time being". The drive answers +`31`, the answer for a letter that is not a command, as it did before (33 before +SI-031). + +**SI-055.** The 1581-style sub-partition commands `/[n]:name` and +`/[n]:name,`+`CHR$(st)CHR$(ss)CHR$(sl)CHR$(sh)`+`,C` are not implemented and are out +of scope. They address 1581 emulation partitions, which this drive does not have. +Sources: HD 9-9 and 9-11; 1581 User's Guide, which gives the same syntax. + +--- + +## 6. Directory commands + +**SI-060.** `MD[n][path]:name` creates a directory. A colon is required; without one +the answer is `34`. A name that is a single shifted space answers `34`. Sources: +HD 9-17, which states the colon rule as its first guideline; `SD parse_mkdir()`. +Current behaviour is worse than accepting the colon-less form. `U dir_command()` +parses with `path_only = true`, so a command with no colon produces an empty name and +an empty path, and `MD` then tries to create the current directory itself: measured, +`MD NOCOLON` answers `63,FILE EXISTS`. **Change required.** + +**SI-061.** `CD[n]{<-|[path][:]name}` changes directory, per SI-010 and SI-014. +Current behaviour: correct except for the left arrow and for wildcards in +intermediate components. + +**SI-062.** `CD` into a file whose name has a disk image extension mounts that image +and makes its root the current directory; `CD<-` from the root of a mounted image +unmounts it. Sources: SD README, "CD is also used to mount/unmount image files"; +GSD "Mounting a Disk Image". Current behaviour: the Ultimate virtual file system +mounts images as directories, so `CD:GAME.D64` already works and `CD<-` already +leaves. Unchanged, and recorded because it is the feature `XI` in sd2iec exists to +make discoverable. + +**SI-063.** `RD[n]:name` removes a directory. It takes no path: a `/` anywhere in the +command answers `34`. It refuses a directory that is not empty. Sources: HD 9-19, +"This command does not allow the use of paths in order to avoid problems with +removing a subdirectory which is a parent of the directory in which you are located"; +`SD parse_rmdir()`, which rejects any `/` with `ERROR_SYNTAX_NONAME` and answers +`63,FILE EXISTS` for a directory that still has entries. Current behaviour: `U do_remove_dir()` accepts a path and maps `FR_DENIED` to +`ERR_FILE_EXISTS`. Measured, `RD/PROBEDIR` removes the directory and answers +`00, OK`, which is the case HD 9-19 forbids in order to stop a user removing a parent +of the directory they are standing in. **Change required** for the path rejection. + +**SI-064.** `R-H[n][path]:newname` renames a directory header. The name is at most +16 characters. Sources: HD 9-15; IDE 15.6.5; `SD parse_set_header(3)`, which also +accepts an id of at most five characters. On a host file system a directory has no +header separate from its name, so this renames the directory itself, which is what +GSD says sd2iec does with the equivalent operation. Not implemented; +**change required.** C64 OS depends on the header for a related reason: GAP says +"C64 OS in particular uses the directory header when creating a favorite... The name +of the favorite is taken from the directory header name." + +**Decision (PR #881): not implemented.** On a CMD HD, `R-H` changes only the header +block and leaves the directory's name in its parent unchanged; on a host file system the +only equivalent is renaming the directory itself, which is a different operation and +would surprise a program written for a CMD HD. GSD states that "The R-H command is not +supported by sd2iec". C64 OS takes a favorite's name from the header, and SI-065, which +is implemented, makes the header show the directory's own name as sd2iec does. The +reporter wrote that `R-H` "should add not to far away, for the time being ok". The +drive answers `30`. + +**SI-065.** The header line of a directory listing carries the name of the directory +as it appears in its parent, and of the partition when the root is listed. Source: +GAP, "on SoftIEC it tries to show you the current path. This is inconsistent for the +sake of doing something clever, but it breaks the expectation... I would change this +behavior to SD2IEC's way, in the name of compatibility"; `SD fat_getdirlabel()`, +which returns the volume name for the root and otherwise walks `..` to find the entry +whose cluster is the current directory and returns that entry's name. + +Current behaviour: `U setup_directory_read()` uses `partition->GetName()` for every +directory, truncated to its last 16 characters. That is no longer the full path GAP +complained about, but it is still not the directory's own name. **Change required.** + +--- + +## 7. File commands + +### 7.1 Open + +**SI-070.** The type and access suffixes are `,P`, `,S`, `,U`, `,L`+`CHR$(rl)` and +`,R`, `,W`, `,A`, `,M`. Secondary address 0 forces read and PRG; secondary address 1 +forces write and PRG; any other secondary address defaults an unspecified type to +SEQ. Sources: HD 9-23 to 9-31 for `,P`, `,S`, `,U`, `,L`, `,R`, `,W` and `,A`; +`SD file_open()` for `,M` (`case 'M': /* Modify */`, which HD does not document) and +for "Force mode+type for secondaries 0/1". Unchanged; `U setup_file_access()` implements it. + +**SI-071.** `N[n]:name[,id]` creates or formats a disk image, as sd2iec does, because +this drive has no formattable medium of its own. Source: SD README under `N:` and +`SD fat_format_image()`: + +* If the name ends in a known image extension and no such file exists, an image of + that format is created. `.D64` and `.D41` mean a 1541 image, `.D71` a 1571, `.D81` + a 1581, `.DNP` a native partition image. An id is required. +* For `.DNP` the id is a three digit track count and the image is + `65536 * tracks` bytes, created but not formatted. +* If the name has no known image extension, `.D64` is appended, and in that case an + existing file is **not** overwritten: the answer is `63,FILE EXISTS`. +* If the file exists and the extension was given explicitly, it is formatted, except + that an existing `.DNP` is refused with `63` whether or not the extension was given + (`SD fat_format_image()`, `if (ext == NULL || imagetype == IMG_IS_DNP)`; the README + text omits the DNP exception). +* The disk label is the name with the extension removed. + +Current behaviour: `U IecParser::format_command()` parses a `name=type` form that +nothing sends, and `U do_format()` is a `printf` that answers `00, OK` without doing +anything. The reporter reported this on #877. **Change required.** + +**Decision (PR #881): implemented for host directories; refused inside a disk image.** +When the directory `N` addresses is inside a mounted disk image, sd2iec formats that +image. Doing that here would write the image file under the file system that has it +mounted and caches its block map, so `N` answers `30` there instead of creating an image +inside the image. The name buffer holds a 16 character label and a four character +extension, so `N:ABCDEFGHIJKLMNOP.D81,AB` creates a D81 image. + +**SI-072.** A file whose name ends in a disk image extension, or in `.CRT` or +`.TCRT`, is written to the host file system under exactly that name, with no type +extension added. Source: `SD should_save_raw()`; SD README, "PRG files that have D64, +D41, D71, D81, DNP or M2I as an extension will always be written without an x00 +header and without any additional PRG file extension." + +Current behaviour: `U IecChannel::ConstructPath()` appends the type extension +unconditionally, so JiffyDOS's MD81 produces `FOO.D81.prg`. The reporter reported +this on #877. **Change required.** + +### 7.2 Scratch, rename, copy + +**SI-073.** `S[n][path]:pattern[,[n][path]:pattern...]` scratches. Each element gets +its own partition and path. Directories are skipped. The answer is +`01,FILES SCRATCHED,,00` with the count in the track variable, per SI-033. +Sources: HD 9-27; `SD parse_scratch()`; IDE 15.2.2, whose examples include +`@S/STUFF/:*=OLD,*=BAK,/STUFF/BAK/:*`. Current behaviour: the parser splits on +commas and parses each element, which is right; the error code is wrong per SI-033 +and the element count is capped at 8 by `filename_t filenames[8]` in +`U scratch_command()`. HD 9-27 caps the list at five names ("will accept up to five +separate filename parameters"), so the cap already exceeds the CMD reference; SD README +under `S:` sets no limit below the command length, and that is the target. + +**SI-074.** `R[n][path]:newname=[[n][path]:]pattern` renames a file or a subdirectory. +Source and destination must be in the same directory; if they are not, the answer is +`62,FILE NOT FOUND`. An empty new name answers `34`. A new name that already exists +answers `63`, unless it differs from the old name only by case. A wildcard in the new +name answers `33`. Sources: HD 9-26, whose section is headed "Renaming Files and +Subdirectories" and which reads "Filenames and Native Mode subdirectory names may be +changed by using either the DOS RENAME or the BASIC 7.0 RENAME command", with +appendix J listing the command as "RENAME (Files and Subdirectories)"; +`SD parse_rename()`, which passes `FLAG_HIDDEN` and no type to `first_match()`, so an +entry of any type is matched, and whose `fat_rename()` renames the host entry, a +directory included; and `SD parse_rename()`'s note that "The 1541 renames the file to +'=' in this case, but I consider that a bug". Current behaviour: +`U do_rename()` does not check that the two directories agree, does not check for +an existing destination, and matches files only, so a subdirectory answers +`62,FILE NOT FOUND`; the wildcard rejection in `U rename_command()` answers +32 rather than 33. **Change required.** + +**Decision (PR #881): implemented except the directory rule.** The name checks are +implemented: `34` for an empty new name, `33` for a wildcard in it, `63` for a new name +that an entry of any type already has. A subdirectory is renamed under its own name: +`U do_rename()` resolves the source with directories allowed, and `CreateIecName()` +already reports `e_folder` for one, so the destination is built without a file type +extension. The rule that source and destination be in one +directory is not: before PR #881 a rename moved a file into another directory or +partition, `Suite8-RENAME-P1-TO-P2` in `software/test/iecdrive/testdrive.cc` asserted +that on `master`, IDE 15.2.3 documents the move, and no program has been named that +needs the `62`. An x00 file (SI-144) moved this way keeps its host name. See C14. +The directory half was reported on 917 as `@"MD:A` followed by `@"R:B=A` answering +`62,FILE NOT FOUND`, and the reporter's `finit` hits it when it renames `OS` through a +temporary name. + +**SI-075.** `C[n][path]:new=[[n][path]:]name[,[[n][path]:]name...]` copies, and with +more than one source appends them into the target. Path parsing restarts for every +source. The target takes the file type of the first source. Sources: HD 9-28, which +caps the sources at five; SD README under `C:`, which has no cap; `SD parse_copy()`, +whose `savedtype` takes the type from the first source (the README does not state +the type rule). +Current behaviour: `U do_copy()` takes the type from the first source already, and +`U copy_command()` caps the sources at 8. GAP reported, against firmware 3.10a, that +the copy command produced `kernal.bin.bin` and ignored paths. Neither is still true. +Measured on the head of PR #881, by linking a probe against the same objects the host +suite uses: `C:PROBE2.BIN=PROBE.BIN` answers `00, OK` and the listing shows +`PROBE2.BIN PRG`, one extension and not two; `C/SUB/:PROBE3.BIN=PROBE.BIN` answers +`00, OK` and the file appears in `SUB`. The requirement is therefore to keep a test +for both, not to fix anything. + +**SI-076.** `L[n][path]:name` toggles the lock flag on one file or directory. A +locked file lists with `<` after its type and cannot be scratched; a locked directory +cannot be removed. Sources: HD 9-30; IDE 15.2.4; `SD parse_lock()`, which toggles +`FLAG_RO`. Not implemented; **change required.** The reporter raised it on #877. + +**Decision (PR #881): implemented.** `L` finds its entry through the directory, as a +scratch does, so it locks the entry a listing shows under that name rather than the +first host file matching `NAME.???`. On a host file system the lock is the FAT read-only +attribute, which the Ultimate's FTP server and file browser then also respect; in a disk +image it is bit 6 of the file type byte. A scratch skips a locked entry, and also an +unlocked entry of the same name and type that follows a locked one in a disk image, +because deleting by name removes the first entry of that name. + +**SI-077.** The sd2iec extensions `EL:`, `EU:`, `EH:`, `A:` and `XH:`/`D:` are +specified as follows, from `SD parse_ecommand()`, `parse_eunlock()`, `parse_attr()` +and `parse_set_header()`, and from SD README: + +| Command | Effect | +| --- | --- | +| `EL:name[,name...]` | set read-only on each match; `EL:$` locks a whole mounted image | +| `EU:name[,name...]` | clear read-only on each match; `EU:$` unlocks a whole mounted image | +| `EH[path]:name` | toggle the hidden flag on one file | +| `EH:name,id` | with a colon straight after the partition, set the directory header | +| `A:[R][H][A]=name` | set exactly the named attributes and clear the others | +| `XH:name,id`, `D:name,id`, `R-H:name` | set the directory header | + +They are a second priority behind the CMD commands, because C64 OS hides files by a +leading dot rather than by a device attribute (Greg Nacu, "Hidden Files": "hiding +files doesn't work on a CMD HD, nor a RAMLink, nor an FD2000 or FD4000"), and the +Ultimate's name mapping already escapes a leading dot as `{2E}` so such names round +trip. + +**Decision (PR #881): not implemented.** `L` (SI-076) provides locking and unlocking, +which is what the reporter asked for on #877. `EL` and `EU` are sd2iec's spellings of the +same attribute. `EH` and `A:` with `H` hide files, which only has an effect if listings +leave hidden files out, and that was not implemented either (see SI-134). `XH:`, `D:` +and `EH:` with a colon set a directory header, which is `R-H` (SI-064). The drive +answers `30` for `E` and `X` forms and `31` for `A` and `D`, whose letters are not +command letters. + +--- + +## 8. Relative files + +**SI-080.** `OPEN lf,dv,sa,"[[n][path]:]name,L,"+CHR$(rl)` creates or opens a +relative file. The comma before the record length byte is part of the syntax: the +1581 User's Guide gives `OPEN 2,8,2,"GRADES,L," + CHR$(100)`, and `SD file_open()` +reads the byte after the next comma. HD 9-31 renders the same form, with OCR damage +that can be read either way. `P`+`CHR$(ch)`+`CHR$(lo)`+`CHR$(hi)`[+`CHR$(of)`] positions to a +record. `ch` is the channel, which programs written to HD 9-32 send as the secondary +address plus 96. Record numbers and byte offsets are 1-based. Positioning beyond the +end answers `50,RECORD NOT PRESENT`, which is not an error when the intent is to +extend the file. Sources: HD 9-31 to 9-33; IDE 15.1.1; GSD "Positioning (seeking) +Within a File". Unchanged; covered by Suite4 of `software/test/iecdrive/testdrive.cc`. + +**SI-081.** The channel byte of `P` is masked to its low four bits. Source: +`SD parse_position()`, `find_buffer(command_buffer[1] & 0x0f)`. Current behaviour: +`U do_set_position()` masks only when the byte is 19 or above, which reaches the same +channel for both documented spellings but accepts bytes 15 to 18 that no drive +accepts. Harmless; recorded so that the next reader does not "fix" it into a +divergence. + +**SI-082.** `P` also positions inside a plain file, to a 32-bit little-endian byte +offset, with the missing high bytes taken as zero. Sources: SD README under `P`; +GSD "Positioning (seeking) Within a File"; IDE 15.1.1, which documents both the +four-byte form and `F-P`. Unchanged in principle; `U do_set_position()` implements +it for `e_file`. + +**SI-083.** `P` on a file opened for writing must be able to move beyond the current +end of the file, and a following write must extend the file. Sources: IDE 7, +"Unlike other systems it's possible to seek beyond the end of a file when writing or +modifying and create 'holes'"; the JiffyDOS MD81 sequence the reporter posted on #877 +on 11 September 2026 as a separate `SOFTIEC-TRACE` excerpt (lines #259 to #262; it is +not in TRACE, which is the boot log), which is +`OPEN "FOO.D81,P,W"`, then `P`+`CHR$(4)`+`CHR$($FF)`+`CHR$($7F)`+`CHR$($0C)` to +position to 819199, then one byte, then `CLOSE`. + +Current behaviour: `U do_set_position()` follows the seek with a 512-byte read to +refill the channel buffer, which fails on a file opened without read access; and +inside a mounted image `FileInCBM::seek()` cannot position a file that has no +allocated first sector. The answer the reporter saw was `69,FILESYSTEM ERROR,02,00`, +where the 2 is the raw `FRESULT` `FR_INT_ERR` put into the track variable by +`set_error_fres()`. **Change required:** do not read after seeking on a write +channel, extend the file where the medium allows it, and answer `72,DISK FULL` where +it does not. + +**SI-084.** A relative file on the host file system is read in either of the two +layouts in use, and written in the one this firmware already writes. Nothing on a +user's medium changes. + +| | header | first record at | file size | +| --- | --- | --- | --- | +| this firmware | two bytes, record length little endian | 2 | `2 + n*r` | +| sd2iec, no wrapper | one byte, the record length | 1 | `1 + n*r` | +| either, with an x00 wrapper | 26 bytes, record length at offset 25 | 26 | `26 + n*r` | + +Sources: `U setup_file_access()` writes `uint16_t wrd = record_size` and +`U seek_record()` uses `const uint32_t c_header = 2`; `SD create_file()` sets +`buf->pvt.fat.headersize = 1` and writes that one byte, and `SD fat_file_seek()` +adds `headersize` to every position; `SD P00_RECORDLEN_OFFSET` is 25, and SD README +says "When x00 support is disabled the first byte of a REL file is assumed to be the +record length". + +**The two plain layouts are told apart by the file size, under two stated +assumptions.** Both put the record length `r` in byte 0, so `r` is known before the +layout is. This firmware's files are `2 + n*r` bytes and sd2iec's are `1 + n*r`, so +`size mod r` is `2 mod r` for one and `1 mod r` for the other. The reader must compare +against `2 mod r`, not against the constant 2: for `r = 2` the residues are 0 and 1. +The two residues coincide only when `r` divides 1, that is only at `r == 1`. HD 9-31 +gives the legal record length as 2 to 254, and for every `r` in that range the test is +exact. A second, cheaper check comes first: byte 1 is zero in this firmware's layout, +because a record length below 256 has a zero high byte, so a non-zero byte 1 settles +it immediately; a zero byte 1 settles nothing, because it may be sd2iec payload. + +The assumptions, and what breaks them: + +1. Both writers pad every record to `r` bytes, so a plain file is never left with a + partial last record. This firmware does so in `U IecChannel::write_record()` + (`memset(buffer + pointer, 0, recordSize - pointer)` then `f->write(buffer, + recordSize, ...)` at a record-aligned `recordOffset`), and sd2iec does so in + `SD fat_file_write()` (`memset(buf->data + buf->lastused + 1, 0, ...)` and + `buf->lastused = buf->recordlen + 1`). A file truncated by something else, for + example a copy tool that stopped early, has an arbitrary residue and is read as + whichever layout the residue happens to select. That is the same silent outcome + the current reader has today for every sd2iec file, and no size-based rule can do + better without a wrapper. +2. `r = 1` is outside HD's legal range, but both writers accept it: `U + setup_file_access()` refuses only 0 and values of 256 and above, and + `SD file_open()` refuses only 0. For `r = 1` both residues are 0 and the size + cannot decide. The reader then takes this firmware's two byte layout, because that + is the only plain layout this firmware has ever written, and an sd2iec `r = 1` + file is read one byte late unless it carries an `R00` wrapper. This is a recorded + limitation, not a guarantee. + +An `R00` wrapper is recognised by its extension and `"C64File"` signature (SI-144) +before the size test is applied, so the wrapped layout never enters this comparison. +Empty files are covered: a fresh file is 2 bytes from this firmware and 1 byte from +sd2iec, residues `2 mod r` and 1. + +**Change required**, and it is purely additive. Read both plain layouts and the +wrapped one; keep writing the two byte layout for a plain `.rel`. Interchange on the +write side is SI-146. + +Current behaviour: `U setup_file_access()` reads the first two bytes as one little +endian record length and refuses a value of 256 or more with +`50,RECORD NOT PRESENT`. Against an sd2iec file the second byte is payload, so the +usual outcome is that refusal. The case that matters is the other one: when that +payload byte happens to be zero the value is accepted, the record length is right, +and every record is then read one byte late. Silent misreading is the behaviour to +replace, and it is why the discriminator above is on the file size rather than on the +record length alone. + +**Decision (PR #881): implemented, for host file systems.** Inside a disk image the file +system presents a relative file with a two byte header whatever its size, so the one +byte test is not applied there. A relative file opened with a record length is looked up +by its CBM name first, so an existing `R00` file is opened rather than created again +beside it (SI-146). + +--- + +## 9. Direct access + +**SI-090.** `OPEN lf,dv,sa,"#"` allocates a 256-byte buffer on that channel, with the +buffer pointer at 1. `"##n"`, exactly three characters, allocates `n` chained +256-byte buffers with the pointer at 0; if the name is not exactly three characters a +plain buffer is allocated instead, and if there is not enough room the answer is +`70,NO CHANNEL`. Sources: SD README "Large buffers", which is the source for `##n`, for +the `70` answer and for the statement that a standard buffer starts "with the +read/write pointer set to byte 1"; GSD "Buffers and Large Buffers". HD 9-40 documents +only `#[bu]`, where `bu` selects a drive buffer number 0 to 29, and says nothing about +the initial pointer. Current behaviour: `U setup_buffer_access()` gives a fixed 256-byte buffer +with the pointer at 0. **Change required** for the initial pointer of `#` and for +`##n`. + +**Decision (PR #881): `#` implemented; `##n` not implemented.** sd2iec provides large +buffers for its direct sector commands `DR` and `DW`, which read and write sectors of +512 bytes (SD README), and those are out of scope here (SI-096). This drive's block +commands address disk images with 256 byte sectors only, so a large buffer would have no +command that fills it from a medium, and it would be the only memory a channel allocates +and frees. `##n` opens a standard 256 byte buffer. + +**SI-091.** The parameter forms are, from HD 9-43 to 9-46 and Appendix J: + +| Command | Parameters | +| --- | --- | +| `B-A`, `B-F` | partition, track, sector | +| `B-R`, `B-W`, `B-E`, `U1`, `U2` | channel, partition, track, sector | +| `B-P` | channel, position | + +Unchanged since PR #881, which fixed `B-A` and `B-F` from four parameters to three. + +**SI-092.** `B-P` takes an optional third parameter, the high byte of a 16-bit buffer +position, defaulting to zero. Source: SD README, "The B-P command supports a third +parameter that holds the high byte of the buffer position, For example, 'B-P 9 4 1' +positions to byte 260"; GSD "The Buffer Pointer". Current behaviour: +`U block_command()` reads two parameters and `U do_buffer_position()` masks the +position to eight bits. **Change required** once SI-090 provides large buffers. + +**Decision (PR #881): not implemented**, because `##n` is not (SI-090). A third +parameter is ignored, as the ROM ignores it. + +**SI-093.** The partition parameter of a direct access command is ignored; the +channel uses the partition that was current when it was opened. Source: HD 9-8 and +9-44, "The partition number should always be 0 (zero). This is because direct access +commands will always access the partition that was the current partition at the time +the direct access channel was opened"; GSD says the same. **Change required:** bind +the partition at `#` open time and use it, rather than resolving the parameter with +`GETPARTITION()` as `U do_block_read()` and its siblings do today. + +**SI-094.** `B-R` and `B-W` differ from `U1` and `U2`: they use the first byte of the +block as a length. Sources: HD 9-44 and 9-45; `SD parse_block()`, which sets +`buf->position = 1; buf->lastused = buf->data[0];` for `B-R` and writes +`buf->data[0] = buf->position-1` for `B-W`. Current behaviour: `U block_command()` +maps `B-R` and `U1` to the same executer method. **Change required**, though it is +low priority: GSD recommends `U1` and `U2` for this reason and most software uses +them. + +**SI-095.** `B-E` is not implemented and will not be: it executes 6502 code in drive +memory, which this drive does not have. It answers `30`, because `B` is a recognised +command letter and only the sub-command is not (SI-030). + +**SI-096.** The sd2iec direct sector commands `DI`, `DR` and `DW`, and the error +`78,BUFFER TOO SMALL`, are out of scope. They expose the raw storage device below the +file system, which is not something this firmware should offer over IEC. Source: +SD README under `D`. + +--- + +## 10. Device commands + +**SI-100.** `U0>`+`CHR$(d)` changes the device number, for `d` in 8 to 30. Sources: +HD 9-49; IDE 15.4.1; `SD parse_user()`, which accepts 4 to 30 and recognises the `>` +by `(command_buffer[2] & 0x1f) == 0x1e`. GAP lists this as a gap: "Changing the +device address with u0> command. This is supported on all devices going back to +ancient times, before the 1541. This produces a syntax error in SoftIEC." Not +implemented; **change required.** The new number is not persisted unless the user +saves the settings. + +**Decision (PR #881): implemented.** The number is written into the IEC processor's +device number slot without holding the processor in reset, because the command is still +on the bus, and it is not written to the configuration. + +**SI-101.** `S-8`, `S-9` and `S-D` are the typed aliases for swapping to device 8, +device 9 and back to the configured default. Sources: HD 9-34; IDE 15.4.1. On this +drive there is nothing to swap with, so `S-8` and `S-9` set the device number +directly and `S-D` restores the configured one. **Change required**, and note the +parsing hazard: `U execute_command()` routes every `S` to `scratch_command()`, so +`S-8` currently tries to scratch a file named `-8` and answers, measured, +`62,FILE NOT FOUND`. `SD parse_doscommand()` guards +this with `if (command_length == 3 && command_buffer[1] == '-')`, and then answers +`31`: sd2iec recognises the form but does not implement the swap. + +**Decision (PR #881): not implemented.** There is no second drive to swap with, and no +report or program asks for the aliases. The three byte forms answer `31`, as sd2iec +answers them, and are not taken for a scratch of a file named `-8`. + +**SI-102.** `W-0` and `W-1` clear and set a software write protect for the whole +drive. Sources: HD 9-35; IDE 15.4.10. While set, every write answers +`26,WRITE PROTECT ON`. Not implemented; **change required.** `U execute_command()` +has no `W` case at all, so today it answers 33 and after SI-031 it would answer 31; +either way the command has to be added rather than reclassified. + +**Decision (PR #881): not implemented.** No report or program asks for a software write +protect, and it needed a check in every path that writes. `W` is not a command letter +here, so the drive answers `31`. + +**SI-103.** The three resets are distinct. + +| Command | Effect | Answer | +| --- | --- | --- | +| `UI` | nothing | `73,,00,00` | +| `UI+`, `UI-` | select the serial timing | `00, OK` | +| `UJ` | close every open data channel; keep the current partition, every partition's current directory, and any mounted image | `73,...` | +| `U`+shifted J, `CHR$(202)` | close every open data channel, return every partition to its root, select the default partition | `73,...` | + +Sources: HD 9-51; SD README under `UI/UJ` and `U`; GSD "Warm, Cold and Hard +Reset". Current behaviour: `UI`, `UI+`, `UI-` and `UJ` are recognised but `UJ` only +sets the error code, closing nothing; `U`+`CHR$(202)` is not recognised at all. + +**None of the three may reconfigure the IEC interface.** GAP reports that "cold reset +and hard reset 'uj' and 'uJ' seem to lock up the bus. Needs a STOP+RESTORE to +recover", against firmware 3.10a. The mechanism is visible in the present code and +must be designed out rather than re-measured. `IecDrive::reset()` begins with +`effectuate_registered_settings()`, which reaches `IecInterface::configure()`, and +that function opens with + +```cpp +HW_IEC_RESET_ENABLE = 0; +``` + +holding the IEC processor in reset while it rewrites the device-number slots, then +releasing it. Command handlers run on the "IEC Server" task, inside the bus state +machine loop in `IecInterface::task()`, while the host still has the command channel +addressed. Resetting the IEC processor from there drops the drive off the bus in the +middle of a handshake, and a host waiting on a handshake that never completes is +exactly the symptom GAP describes. + +**Change required**, in three parts. Implement `UJ` so that it closes the channels. +Implement `U`+`CHR$(202)`. And implement both so that the drive answers the current +transaction first and performs the state reset when the command channel has been +unlistened, never calling `IecInterface::configure()`, because nothing about the bus +configuration changes: the device number, the enable flag and the slot assignment are +all unchanged by a drive reset. `IecDrive::reset()` as it stands is the menu's reset, +not a command handler's, and must not be reused without removing that call. + +**SI-104.** `U3` to `U8` and `UC` to `UH` jump into drive memory and are not +implemented; they answer `30`, for the same reason as SI-095. Source: HD 9-51. + +**SI-105.** The memory commands are implemented as follows. + +* `M-R`+`CHR$(lo)`+`CHR$(hi)`[+`CHR$(n)`] returns `n` bytes over the error channel, + with `n` absent meaning 1 and `n` zero meaning 256. It does not read past a page + boundary. Sources: HD 9-46 and 9-47 for the syntax, zero meaning 256 and the page + boundary; ROM `$CB24` (`LDA $0274 / CMP #$06 / BCC`, one byte when the command is + shorter than six bytes) and `SD handle_memread()` ("Read 1 Byte if no explicit + length was provided") for the absent count. HD does not describe the absent case. +* `M-W`+`CHR$(lo)`+`CHR$(hi)`+`CHR$(n)`+data accepts 1 to 248 bytes and discards + them. Source: HD 9-47. +* `M-E`+`CHR$(lo)`+`CHR$(hi)` answers `00, OK` and does nothing. Source: HD 9-48. + +What `M-R` returns is specified in section 11. The reporter's position on #877 is +that the count matters more than the content: "M-R should return the number of +queried bytes. I agree we have nothing good to return but we can return each byte to +be 42... That way, a software that does M-R to identify devices is syntactically +happy." Not implemented; TRACE shows all four of C64 OS's probes answering +`33,SYNTAX ERROR` because `U execute_command()` routes `M` to `dir_command()`, which +accepts only `MD`. **Change required.** + +**Decision (PR #881): `M-R` implemented; `M-W` and `M-E` answer `30`.** Nothing of what +`M-W` writes is kept and `M-E` runs nothing, so answering `00, OK` would tell a fast +loader that its drive code is in place and running; this is the same reason SI-120 gives +for not answering OK to a clock write that sets nothing. The reporter's request was for +`M-R`, which C64 OS sends four times at boot (TRACE). + +**SI-106.** `S-C`, the SCSI pass-through of HD 9-39, is out of scope. + +--- + +## 11. Device identification + +This section exists because it is the one place where copying another device exactly +would be wrong. + +**SI-110.** The `UI` message is the primary identification and must name this device. +Source: SD README, "If you are the author of a program that needs to detect sd2iec +for some reason, DO NOT use M-R for this purpose. Use the UI command instead and +check the message you get for 'sd2iec' and 'uiec' instead"; GSD "Device Detection". +Current behaviour: `73,U64HD ULTIMATE DOS V2.0`. Unchanged. + +**SI-111.** `M-R` must not return the signature of a 1541, a 1571, a 1581 or a CMD +device, because a program that reads one of those will then drive this device as that +model. The signatures are, read out of the ROM images in this repository: + +| Address | 1541 | 1571 | 1581 | CMD | +| --- | --- | --- | --- | --- | +| `$FEA4` | `CA CC` | `CA CC` | `FF FF` | `"HD"`, the fifth and sixth bytes of `"CMD HD"` at `$FEA0` | +| `$E5C5` | `35 34` = `"54"` | `35 37` = `"57"` | `FF FF` | | +| `$A6E8` | outside the ROM | `48 C9` | `35 38` = `"58"` | | + +The two bytes at `$E5C5` and `$A6E8` are the model digits inside the drive's power-up +message. The CMD signature is documented by its own manual: HD 9-47 gives the +detection example `PRINT#15,"M-R"CHR$(160)CHR$(254)CHR$(6)` followed by +`IF A$="CMD HD"`, that is six bytes from `$FEA0`. + +TRACE shows C64 OS reading exactly `$FEA4`, `$E5C5`, `$A6E8` and `$0002`, two bytes +each, before falling back to `UI`. The probe strings are literal bytes inside +`OS/LIBRARY/IEC.LIB.R`. + +**SI-112.** `M-R` returns the requested number of bytes, every byte `$00`, at every +address. There is no address table and no exception. + +Three things follow from that choice and each is a reason for it. + +* The byte count is what makes a probe well formed. A device that answers a syntax + error to `M-R` is not merely unidentifiable, it is broken from the caller's point + of view, which is what TRACE shows happening to C64 OS today. The reporter's + position on #877 was the same, and he proposed 42; the count is the part both + positions agree on. +* `$00` matches none of the model signatures in SI-111, so no caller can conclude + 1541, 1571, 1581 or CMD. +* `$00` is the one value sd2iec deliberately returns for a detection address: + `{ 0xfffe, { 0x00, 0x00 }, 0xff }` in `SD drive_magics`, commented "Disable AR6 + fastloader". Returning it everywhere gives every fastloader that probes the same + answer that makes Action Replay 6 fall back to the KERNAL loader. + +**SI-113.** This drive does **not** implement sd2iec's `drive_magics` table, which +returns bytes chosen to put DreamLoad, ULoad Model 3 and Krill's loader into 1541 or +1571 mode. Those values are correct for sd2iec because sd2iec reimplements those +loaders. This drive implements none of them, so a loader that concluded "1541" from a +faked byte would go on to upload drive code with `M-W` and call it with `M-E`, and +then wait for a response that is never coming. Answering `$00` makes the same loader +fall back to the standard serial protocol, which works. + +**SI-114.** Identification of this drive is the `UI` string, and its format is fixed +here so that software can rely on it: `73,U64HD ULTIMATE DOS V2.0,00,00`. The +leading token is the device family and the trailing token is the DOS version. A +future revision may raise the version; it may not change the family token, and it may +not introduce a memory signature at `$FEA0` or anywhere else. Software that needs to +recognise this drive matches on the string, which is also what SD README tells +authors to do for sd2iec: "DO NOT use M-R for this purpose. Use the UI command +instead." That C64 OS already copes with this is not an assumption: the boot in TRACE +falls through all four `M-R` probes to `UI` and succeeds. + +**SI-115.** The sd2iec `XR` mechanism, which serves a real drive ROM image from a file +for `M-R` so that GEOS and Wheels can identify a drive, is out of scope. Sources: +SD README under `XR` and under GEOS and Wheels; GAP does not ask for it. The +reporter asked on #877 that the documentation state plainly that there is no GEOS and +no Wheels support, which belongs in `GideonZ/1541u-documentation` rather than here. + +--- + +## 12. Real time clock + +**SI-120.** `T-RA`, `T-RB`, `T-RD` and `T-RI` read the clock and `T-WA`, `T-WB`, +`T-WD` and `T-WI` set it. The `A` format is +`"dow. mo/da/yr hr:mi:se xM"+CHR$(13)` with the day of week four characters followed +by a space, from `SUN.`, `MON.`, `TUES`, `WED.`, `THUR`, `FRI.`, `SAT.`. The `B` and +`D` formats are nine bytes: day of week, year, month, day, hour in 12-hour form, +minute, second, an AM or PM flag, and `CHR$(13)`, BCD-coded for `B`. The `I` format +is the ISO 8601 subset `"YYYY-MM-DDThh:mm:ss dow"+CHR$(13)`. Sources: HD 9-36 to +9-38; IDE 15.4.8; SD README under `T-R and T-W`; GSD "Realtime Clock". + +Current behaviour: the four read forms are implemented in +`U IecParser::time_command()`. The write forms answer `00, OK` and do nothing. +**Change required** only in that the write forms should set the Ultimate's real time +clock, which is the device's clock, or answer `30,SYNTAX ERROR` as sd2iec does when +there is no clock to set. Silently answering OK and not setting the clock is the one +thing that must not remain. + +**Decision (PR #881): the write forms answer `30`.** The clock belongs to the system, +and GAP notes that C64 OS sets it through its UCI real time clock driver. Setting it from +the IEC bus would have needed a setter in each of the three real time clock drivers. +`30` is the answer this requirement allows. + +--- + +## 13. Directory listings + +### 13.1 Layout + +**SI-130.** A listing is a BASIC program: a two-byte load address `$0401`, then per +line a two-byte link pointer, a two-byte line number carrying the block count, the +text, and a zero; the program ends with two zero bytes. Source: `SD dirheader[]`, +`{1, 4, /* BASIC start address */ 1, 1, /* next line pointer */ 0, 0, ...}`. + +Current behaviour: `U iec_channel.h` `c_header[32] = { 1, 1, 4, 1, 0, 0, 18, 34, ...}` +transposes the first four bytes, so the drive sends load address `$0101` and link +`$0104`. TRACE confirms it on the wire: +`#48 CLOSE ... read=384 [01 01 04 01 02 00 12 22 4E 4F 20 4E 41 4D 45 20 ...]`. + +This is invisible to `LOAD"$",dv`, which is a relocating load, and to `LIST`, which +uses the link only as an end marker, and to a program that reads `$` as a file and +skips two bytes. It is wrong for `LOAD"$",dv,1`, an absolute load, which would place +the listing at `$0101`. **Change required.** + +**SI-131.** Byte 4 of the header, the low byte of the header line's BASIC line +number, is the partition number for a file listing and the number of partitions for a +partition listing. See SI-046. Current behaviour: correct for a file listing, zero +for a partition listing. + +**SI-132.** The file type field is followed by `<` when the file is locked, and +preceded by `*` when the file was not closed. Sources: HD 9-30 for `<`; +`SD createentry()` for both (the splat is CBM DOS behaviour and is not on HD 9-30). +Locking is SI-076; the splat has no counterpart on a host file system and is not +required. + +**SI-133.** The low byte of the next-line link pointer is `(file size mod 254) + 2`, +so that a program can recover the exact byte length of a file. Sources: SD README, +"If known, the low byte of the next line link pointer of the directory listing will +be set to (filesize MOD 254)+2"; GSD "File Sizes and Blocks Free". Not implemented; +**change required.** It costs nothing and it is the only way a C64 program can learn +a file's true size from a listing. + +**SI-138.** The last byte of a listing is sent with EOI, whatever the size of the reads +that bring the listing in. A BASIC program that reads a listing one byte at a time with +`GET#` must therefore see the KERNAL status become 64 on that byte and 0 on every byte +before it. Sources: 917, where the same program ended against a CMD HD and an sd2iec and +ran for ever against this drive, reading zeroes with a status of 0; `SD dir_footer()`, +which sets `sendeoi` on the blocks free line. + +Current behaviour: the end of a listing is the only buffer for which +`U read_dir_entry()` sets `last_byte`, and it sets `prefetch_max` to 31 where that buffer +holds 32 valid bytes, and to 1 where the partition listing's end marker holds 2. +`U IecChannel::pop_data()` tests `pointer == prefetch_max - 1` and so reaches that branch +one byte before `pointer == last_byte`. It then calls `read_dir_entry()` again, which +returns -1 without moving `pointer`, and the channel stands one byte short of its last +byte for ever. A load does not notice: `prefetch_data()` runs ahead within one talk and +reaches `last_byte`, which sends the EOI. A `GET#` addresses the channel to talk again for +every byte, and `push_command(0x60)` resets the prefetch to the stuck pointer, so the +program gets the same byte back for ever. **Change required.** + +**SI-139.** A time stamped directory line has a fixed length: 64 bytes in the long format +and 42 bytes in the short format, counting the link pointer, the block count and the zero +that ends the BASIC line. The bytes between the end of the stamp and that zero are `$01`. +The stamp begins four characters behind the three character type of the long format and +two characters behind the single type letter of the short format; the first of the three +characters in the long format is the lock and splat position of SI-132. + +Sources: `SD createentry()`, which clears the line to index 63 for `DIR_FMT_CMD_LONG` and +index 41 for `DIR_FMT_CMD_SHORT`, writes the type at `data + 1`, the long stamp at +`data + 7` and the short stamp at `data + 3`, and then fills what is left with `1` up to +the zero. HD 9-22 agrees: measuring the character positions in the scan rather than +reading its extracted text, the type starts 19 columns behind the opening quote of the +name in both formats, the date starts 6 columns behind the start of the type in the long +format and 2 in the short format, and the time starts 11 columns behind the start of the +date in the long format and 6 in the short format. 917 reports the same two properties as +measurements against a CMD HD and an sd2iec: "each directory entry is precisely 64 bytes" +in the long format, and "there are 3 spaces 0x20 characters following the CBM file type +before the start of the date ... Except, on SoftIEC there's only one space. And there are +none of the $01 padding bytes after the time." + +Current behaviour: `U read_dir_entry()` writes the long stamp at offset `31 - chars` and +the short stamp at offset `29 - chars`, where `chars` is the number of digits in the block +count, and sets `prefetch_max` to whatever length the contents came to. A long line is +therefore 48 bytes for a one digit block count and 45 for a four digit one, with the stamp +two columns too far left and one space where three belong. A short line is 42 bytes down +to 39 with the columns already right. **Change required** in both formats. The filler is +what 917 saw first: "on lines where the filesize is 2 digits, there is a trailing 0x01 +before the 0x00 line ending on CMD HD but not on SoftIEC". + +### 13.2 Filters + +**SI-134.** `LOAD"$[n][path][:pattern[=tp]]"` filters by name and type. `tp` is `P`, +`S`, `U`, `R`, or `B` for a directory. Sources: HD 9-20, "P for program (PRG), S for +sequential (SEQ), U for user (USR), R for relative (REL), and B for subdirectory +branch (DIR)". `D` is accepted as a synonym for `B`, which is an sd2iec extension; +GSD warns that "If filtering a directory programmatically, B should be used for +compatibility with CMD storage devices. D is only supported by sd2iec", and IDE 6.2 +in fact maps `D` to DEL. `H` additionally shows hidden files. + +Current behaviour: `U parse_dir_option()` accepts all of them, but it maps `H` to bit +6 of the type mask while `U read_dir_entry()` tests `1 << ftype` with `ftype` at most +5. Measured, `$:*=H` lists the header and no entries at all, where `$:*=P` and +`$:*=B` list correctly. +**Change required:** `H` is not a type, it is a flag that suppresses the hidden +filter, and it must be kept separate from the type bits. + +**Decision (PR #881): `H` no longer filters; hidden files stay listed.** `H` is accepted +and sets no type bit, so `$:*=H` lists what `$:*` lists. Leaving hidden files out of a +listing by default is not implemented: before PR #881 they were listed, C64 OS hides +files by a leading dot rather than by an attribute, and no report asks for the change. + +**SI-135.** `LOAD"$=T..."` produces a time-stamped listing, with options `L`, `N`, +`>stamp` and `fopen(partition->GetPath(), fs_filename, flags | FA_OPEN_FROM_CBM, &f)` is present + at tag `v3.14` and at tag `v3.14d`. Commit `76d887bd`, "Pulled in the iec_compatibility + branch" of 23 June 2026, rewrote that open and dropped the argument. `76d887bd` is an + ancestor of `v3.15` and is not an ancestor of `v3.14d`, so every release from 3.15 on + hands out the CVT container where 3.14d handed out the file. The flag itself was left in + `fs_errors_flags.h` and still tested by `FileInCBM::open()`, with no caller anywhere in + the tree. +* The listed type has never matched a CBM drive. At 3.14d `CreateIecName()` copied the + extension straight into the three type characters for a name that is already in CBM + form, so a GEOS file listed as `CVT`, which is not a CBM file type at all. 3.15 lists it + as `SEQ`. Neither is what the entry's type bits say, so this half is a defect of long + standing whose symptom changed in 3.15, not a regression. + +**Implemented (PR #881).** Both halves changed together, because either one alone is worse +than the previous state: the type alone would offer a `LOAD` a stream it cannot run, and +the stream alone would leave the type contradicting the disk. + +* `FileInfo` carries the directory entry's type bits in a new field, `cbm_filetype`, which + is zero on a file system that has no CBM type. `U DirInCBM::get_entry()` fills it in, and + `U IecPartition::CreateIecName()` uses it when it is set, in front of the extension + comparison it did before. The `CVT` extension itself is unchanged, so the file browser, + the FTP server and the UCI target still see and write `.CVT` files as they did. +* The IEC read open passes `FA_OPEN_FROM_CBM`, which `U FileInCBM::open()` already tested + and which no caller had ever set. The CVT header branch is skipped and the file's own + chain is read. A VLIR file's chain is its record block, which is what a 1541 hands over. + +The `C` command still copies a GEOS file out of an image as a CVT container, because +`U IecCommandChannel::do_copy()` opens each source with a plain `FA_READ`. That keeps the +interchange format on a copy to the host file system, where it is what the receiving side +needs, and it is the one place where a copy and a read of the same file differ. + +Measured against a reference 1541: VICE's `c1541` lists `geos-2.0r-cenbe.d64` as +`prg prg usr usr usr usr usr usr usr`, which is what this drive now lists and is neither +the nine `SEQ` of the previous behaviour nor the nine `PRG` a type-only change would give. +`c1541` extracts `DISK COPY` from `deskpack-plus-b.d64` as 4,335 bytes; this drive now +hands out the same 4,335 bytes. That file has a load address of `$0801` and a `10 SYS(2064)` +line, so it loads and runs from BASIC. It is the only one of the 355 GEOS entries on the +twenty GEOS disks that were scanned for which that is true, so the change is a correctness +fix first and an enabling one only incidentally. + +Measured on an Ultimate 64 Elite, with `deskpack-plus-b.d64` mounted as the Software IEC +partition and the same BASIC program run from the C64 on each firmware. The program sends +`CD:DESKPACK.D64`, prints the printable bytes of `$:DISK COPY`, then prints the first eight +bytes an open of `DISK COPY` returns. + +| Firmware | Listed type | First eight bytes | +| --- | --- | --- | +| 3.14d (`40a41caa`), FPGA 122, core 1.49 | `CVT` | `1 8 13 8 10 0 158 40` | +| 3.15 as this PR found it (`bc3f2dc4`), FPGA 125, core 1.50 | `SEQ` | `130 0 0 68 73 83 75 32` | +| This change (`79a53425`), FPGA 125, core 1.50 | `PRG` | `1 8 13 8 10 0 158 40` | + +`1 8 13 8 10 0 158 40` is `$01 $08 $0D $08 $0A $00 $9E $28`, the load address and first +BASIC line of the file, and is what `c1541` extracts. `130 0 0 68 73 83 75 32` is +`$82 $00 $00` followed by `DISK `, which is the CVT header's copy of the directory entry: +its first two bytes are read as a load address of `$0082`. Each firmware was run from its +own matching bitstream over JTAG, so 3.14d ran on the FPGA core it shipped with. + +GEOS itself still cannot start from this drive, because the GEOS speeder is not +implemented; that is out of scope here and belongs in its own issue. + + +--- + +## 14. File naming on the host file system + +### 14.1 The scheme that already exists + +The Ultimate maps a PETSCII name to a host file name by escaping the bytes a host +file system cannot carry, and by appending the CBM file type as an extension. The +design is `doc/filenames_design.txt` and `software/test/iecdrive/doc.md`; the code is +`petscii_to_fat()` and `fat_to_petscii()` in `software/components/pattern.cc`. + +That same scheme is sd2iec's **extension mode 5**. It is not a coincidence and not a +convergence: the functions are the same code in both projects, down to the comment +`// '|' > 96 ;)` and the `reserved_names` table. A unified diff of `petscii_to_fat()` +between `U software/components/pattern.cc` and `SD src/fatops.c` shows only whitespace, +the two divergences listed in SI-142, and one restructured assignment; +`fat_to_petscii()` differs only in how `hex2bin()` is called. GideonZ wrote +them here in 2020 (`3ec23bb9`, 4 October 2020); the reporter added them to sd2iec as +mode 5 in 2025 (`0f22587`, 6 June 2025) and documented them in that fork's README in +2026 (`ddb949c`). Upstream sd2iec has modes 0 to 4 only. + +**SI-140.** This is a compatibility contract, not an implementation detail. A card +or stick written by an Ultimate must read back on a markusC64 sd2iec in extension +mode 5, and the reverse. Nothing in this specification may change the mapping except +to close the two divergences below. + +**SI-141.** The rules, from the shared implementation and SD README: + +* A byte below 32, at or above 96, or one of `: / \ " < >`, or a leading `.`, is + written as two upper case hex digits. A run of such bytes shares one pair of + braces: `ABC` in shifted PETSCII becomes `{C1C2C3}`. +* A name that matches a reserved DOS name (`CON`, `PRN`, `AUX`, `NUL`, `COM1` to + `COM9`, `LPT1` to `LPT9`) is prefixed with an empty `{}`. +* A name that would otherwise end in `.prg`, `.seq`, `.usr` or `.rel` gets an empty + `{}` appended, so that the type extension stays unambiguous. +* A trailing run of shifted spaces (`$A0`) is dropped, because a CBM directory entry + is padded with them. See SI-147, which is about the state this rule is actually in. +* The CBM file type is the host extension `.prg`, `.seq`, `.usr` or `.rel`, added on + create and hidden on read. + +**SI-142.** Close the two divergences. + +* sd2iec also escapes `*` and `?`; this firmware does not. sd2iec additionally + refuses to create a name containing either (`SD a76deb2`). Adopt both: escape them, + and refuse to create such a name per SI-032. +* The length guard differs by one: sd2iec tests `(i + 4) > maxlen`, this firmware + tests `(i + 4) >= maxlen`, so it truncates one byte earlier. Adopt sd2iec's. + +**Decision (PR #881): the first divergence is closed; the length guard is kept.** `*` +and `?` are escaped, and scratch, `RD` and opens by pattern match through a directory +scan. The guard is not changed: the difference is in what `maxlen` means, the buffer +size here and the characters before the terminator in sd2iec, and changing the guard +together with every call site leaves every name the drive produces the same while +`FileInfo::generate_fat_name()` would write one byte past its buffer. The one overrun +that did exist is fixed: the `{}` appended to a name ending in `.prg`, `.seq`, `.usr` or +`.rel` is only added when it fits. + +**SI-143.** Names that the forward mapping can never produce must still be readable. +`software/test/iecdrive/doc.md` sets this out under "Injectivity vs Accessibility" +and the code implements it with the rendered-name fallback in +`resolve_existing_iec_path()` and `find_rendered_iec_child()`. Unchanged. The +warning in that document stands: the fallback must not be used for `S`, because +scratching by a heuristic match deletes the wrong file. + +### 14.2 x00 wrappers + +**SI-144.** Add support for reading P00, S00, U00 and R00 files: a 26-byte header +beginning with `"C64File"` and a zero, the 16-character CBM name plus a terminator at +offset 8, the record length at offset 25, then the unmodified data. The host +extension is `P00`, `S00`, `U00` or `R00`, the two digits incremented only to break +an 8.3 collision. Sources: `SD src/fatops.c`, `P00_HEADER_SIZE 26`, +`P00_CBMNAME_OFFSET 8`, `P00_RECORDLEN_OFFSET 25`, `p00marker[] = "C64File"`; GFN. + +Reading is unconditional on sd2iec, in every extension mode. GFN's argument for it is +worth restating because it is the deciding one: an x00 file preserves the CBM name, +its case and its type exactly; two files may differ by case alone; the name may +contain every character CBM DOS allows; and every emulator and every sd2iec unwraps +it the same way regardless of configuration. It is the only mapping under which a +file moved between an Ultimate, an sd2iec and VICE keeps its identity. + +**Decision (PR #881): implemented.** An x00 file lists, opens (with or without a type), +positions, appends, copies (the data without the header, with the type from the +header), renames (the name in the header; the host name is kept) and scratches under the +CBM name in its header. A new file of a name that an x00 file carries answers `63`, and +with `@` the x00 file is removed and the new file written in its place, as sd2iec's +`file_open()` does. The UCI `GET_IECNAME` command reads the header when it is given a +full path. The reason for implementing it is GAP's section on file names, which asks +the drive to follow how sd2iec stores CBM file types. + +**SI-145.** Writing x00 files is a configuration choice, default off, so that +existing users see no change. When on, it follows sd2iec mode 1 (x00 for SEQ, USR and +REL, plain for PRG) or mode 2 (x00 for everything). Source: SD README under `XEnum`. + +**Decision (PR #881): not implemented.** It adds a user setting that no report asks for, +and reading x00 files (SI-144) already gives the interchange with files that VICE and +sd2iec write. New files are written plain, as before. + +**SI-146.** The x00 wrapper is the whole of the write side answer for relative files. +With it the record length is at a fixed header offset that both devices already +agree on, so a relative file created while SI-145 is enabled is readable by an +sd2iec without either device changing its plain layout. A plain `.rel` keeps this +firmware's two byte layout for ever, which is why SI-084 needs no migration and why +no file a user already has is touched. + +**Decision (PR #881): implemented for reading only**, because SI-145 is not +implemented. An existing `R00` file is read and written through its header; a new +relative file is created in the plain two byte layout. + +### 14.3 The shifted space defect + +**SI-147.** The shifted space rule is broken in two independent ways, and the second +makes the same file name map to different host names on different Ultimate models. + +The code is, in both projects: + +```c +while (*pet) { + char p = *(pet++); + if (p == 160) { + const char *q = pet; + while (*(q++) == 160) + ; + if (!*q) + break; + } + ... +``` + +**First defect, an off-by-one.** After the inner loop, `q` points one past the first +byte that is not `$A0`. "Everything from here to the end is `$A0`" is therefore +`*(q-1) == 0`, not `*q == 0`. As written the test reads one byte beyond the string +terminator, so whether a trailing shifted space is dropped depends on memory outside +the name. Compiled with unsigned `char`, the function gives `AB` for `AB`+`$A0` when +the byte after the terminator is zero and `AB{A0}` when it is not. The same +off-by-one also truncates a name at an *interior* shifted space: `A`+`$A0`+`B` comes +out as `A`, losing everything from the shifted space onwards. + +**Second defect, `char` signedness.** `p` is a plain `char`. Where `char` is signed, +`(char)0xA0` is -96 and `p == 160` is never true, so the whole branch is dead code +and every `$A0` is escaped as `{A0}`. Where `char` is unsigned the branch is live. +This is not theoretical: + +| Build | `char` | Evidence | Result | +| --- | --- | --- | --- | +| U64, Nios II | signed | `target/u64/nios2/ultimate/output/pattern.lst` contains no constant 160 anywhere in `petscii_to_fat`; the compiler removed the branch | every `$A0` escaped | +| U64 II and U2+L, RISC-V | unsigned | `target/u64ii/riscv/ultimate/output/pattern.lst` contains `li t1,160` | branch live, with both symptoms above | +| host test builds | signed | `-fsigned-char` appears in the flags recorded in `target/pc/linux/iecdrive/output/pattern.lst` | branch dead, so **the host tests cannot see any of this** | +| sd2iec on AVR | unsigned | avr-gcc default | branch live, same as the RISC-V build | + +So a file whose name ends in a shifted space gets one host name on a U64 and +another on a U64 II, and the host unit tests agree with neither in the way that +matters. + +**Required:** compare on `(uint8_t)p` so the rule is the same on every target, and +test `*(q-1)` so that only a trailing run is dropped and an interior shifted space is +escaped. With both changes the function gives `AB` for `AB`+`$A0`, `A` for +`A`+`$A0`+`$A0`, and `A{A0}B` for `A`+`$A0`+`B`, on every target and regardless of +surrounding memory. The same change belongs in sd2iec, because SI-140 only holds if +both sides agree. + +**SI-148.** The policy the fixed rule serves, which the reporter asked to have +settled before anyone changes the code: + +1. `$A0` is a legal byte inside a CBM name. It maps to the host as `{A0}` and maps + back unchanged. Nothing rejects it on read. +2. A **trailing** run of `$A0` is padding, not data, and is dropped before mapping. A + CBM directory entry is a fixed 16-byte field padded with `$A0`, so a name arriving + from one carries padding that was never part of the name. +3. A name that is empty, or whose first byte is `$A0`, is refused on create, with + `33`, or `64` when `@` is given. This is the same branch as the wildcard rejection + in SI-032: `SD file_open()` tests `(*fname == 160)` alongside `*` and `?`, and + `SD parse_mkdir()` and `parse_rename()` refuse such a name with `34`. +4. A directory listing ends the name at its terminator or at 16 characters, **not** at + the first `$A0`. A 1541 puts the closing quote at the first `$A0` because that is + where its fixed-width field stops carrying name, and reproducing that would make + this drive and an sd2iec print different names for the same file. + `SD createentry()` ends at `$22`, `$00` or 16, and this drive does the same. + +Together with SI-147 that is the whole of the shifted space question, and it needs +nothing further from anyone. + +--- + +## 15. Limits, and what must not break + +### 15.1 Limits + +**SI-150.** Summary of the numbers this specification sets, with their sources. + +| Limit | Required | Today | Source | +| --- | --- | --- | --- | +| command channel buffer | at least 254 | 64 | HD 4-6, `SD CONFIG_COMMAND_BUFFER_SIZE` | +| OPEN name buffer | at least 254 | 64 | GUG, 232-character paths | +| path components | no fixed limit below the buffer | unbounded | HD 4-6 | +| scratch list elements | limited only by the command length | 8 | SD README under `S:`; HD 9-27 allows five | +| copy source elements | at least 5 | 8 | HD 9-28 | +| partitions | 1 to 255 | 1 to 255 | GUG | +| CBM name | 16 characters | 16 | all | +| path components in one command | at least 16 | 16 | GUG: 232 characters allows about 13 levels of 16-character names | + +The 16-component cap is `path.split('/', components, 16)` in +`U resolve_directory_path()`. It is adequate for the path length GUG specifies but +has no margin, and anything over it is silently truncated rather than refused. + +### 15.2 Behaviour that must not change + +These are stated so that the work below does not quietly regress them. Each is +already correct. + +1. `//` is the partition root and a single leading `/` is the current directory + (SI-010). +2. The binary Change Partition keeps a parameter byte of 13 (SI-017). +3. `B-A` and `B-F` take three parameters (SI-091). +4. `G-P` reports the type in byte 0 and the partition's own name in bytes 3 to 18 + (SI-041). +5. The partition directory prints `NAT`, `41 `, `71 `, `81 ` (SI-048). +6. Block command parameters may be separated by the spaces BASIC prints (SI-020). +7. Relative file behaviour as covered by Suite4 of `software/test/iecdrive` + (SI-080). +8. The `{HH}` name mapping (SI-140). +9. The two byte record length header of a plain `.rel` file (SI-084). This one is + newly on the list: an earlier revision of this document proposed changing it, and + the reason it is here is that changing it would alter the meaning of every + relative file this firmware has already written. +10. JiffyDOS acceleration, which is implemented in the IEC processor microcode + `software/io/iec/iec_code.iec` and is what GAP, writing in 2023, reported + missing. + +### 15.3 Consequences elsewhere + +**SI-151. Retired.** An earlier revision of this document required the relative file +record length to change from two bytes to one, and this requirement carried the +migration for the files this firmware had already written. Both were wrong: a +migration over user data, by a heuristic, in order to gain an interchange that the +x00 wrapper already provides, is a cost with no matching benefit. SI-084 now reads +both plain layouts and keeps writing the existing one, and SI-146 provides the +interchange, so there is nothing to migrate. The number is left retired rather than +reused, so that a reference to it in an older note resolves to this paragraph. + +**SI-152.** Raising the command buffer (SI-021) changes the `SOFTIEC_LOG_MAX_BYTES` +assumption in `software/io/iec/iec_log.h`, which is 64 because the buffers were 64. +The failure log must keep reporting a command's real length and mark where its +rendering is cut. + +**Decision (PR #881): implemented.** A log line carries one rendering of the bytes, as +text with every byte that is not printable ASCII written as `\xNN`, which loses nothing. +A rendering that does not fit its 260 character buffer ends in `..`, and the line still +carries the real length. The lines of the setting **Log Every Operation** (section 18) +render the directory, the host path and a reply the same way. + +**SI-153.** Three existing tests encode behaviour this specification changes, and +each must be updated in the same commit as the change, not separately. + +| Test | Today | After | +| --- | --- | --- | +| `Suite8-CD-PARENT-OTHERDIR` in `software/test/iecdrive/testdrive.cc` | `CD/_/OTHERDIR` succeeds | rewritten as `CD/../OTHERDIR` (SI-014) | +| any test that asserts `62,FILE NOT FOUND` from a scratch that matched nothing | 62 | `01,FILES SCRATCHED,00,00` (SI-033) | +| any test that asserts `33` for a command whose first letter is not a command letter | 33 | `31` (SI-031) | +| `Suite10-U3` in `testdrive.cc` and `test_dispatch("U3:2,0,18,0", ..., ERR_UNKNOWN_CMD)` in `software/io/iec/cbmdos_parser_test.cc` | 33 | `30`, because `U` is a command letter and only the sub-command is unknown (SI-104, SI-030) | +| `Suite10-FullBuffer` in `testdrive.cc`, which sends 64 bytes of `Z` and asserts `33,SYNTAX ERROR` to show the full buffer is still executed | 33 | `32`, because a command that fills the buffer is refused (SI-022); the test's purpose, that the 64th byte is not lost, needs a 64-byte command that is valid, sent after the buffer is raised | + +--- + +## 16. Conflicts between the sources, and how each is decided + +Every row is decided. Where the sources disagreed, the row states the primary +evidence that settled it rather than which source was preferred. Nothing here is +left for someone else to answer before the work can start. + +| # | Case | What the sources said | Decision and evidence | +| --- | --- | --- | --- | +| C1 | Error code for an unrecognised command | HD B-2 and 1541 say 31. `SD parse_doscommand()` says 30 and reserves 31 for an empty command. The reporter asked for 31. | **31** (SI-031). Settled by ROM `$C175`: the command-table miss loads `#$31`. sd2iec is the outlier, and the reporter's request agrees with the hardware. | +| C2 | `CD/:<-` | `SD do_chdir()` goes to the parent. The reporter expected it to enter a directory named `<-`, while noting he had no reference for the spelling beyond an emulator. | **Parent** (SI-015). One rule covers every measured case: the arrow is the parent in the name position and a literal character in a path component. HD 9-19 says the arrow "cannot be combined with any subdirectory path information", which is the same statement. `CD/<-` remains the way to enter such a directory. | +| C3 | `SAVE"@:foo*"` | The reporter measured `64` on a real drive. `SD file_open()` and IDE 7.1 replace the matched file; sd2iec answers 64 only when nothing matched. | **Settled by ROM `$D8F5`** (SI-032). Save-with-replace compares the found entry's type against the requested type and answers 64 on a mismatch or on a REL. `SAVE` asks for PRG, so a `foo*` that first matches a non-PRG answers 64 and one that matches a PRG replaces it. Every source is consistent once that check is known. | +| C4 | `$=P` footer | Issue #890 and `SD pdir_refill()` say no footer. IDE prints `n PARTITIONS.`. | **No footer** (SI-045). The issue is explicit, sd2iec agrees, and IDE64's footer is its own extension. | +| C5 | `$=P:*=C` | HD 9-14 says `C` selects 1581 CP/M. `SD load_directory()` maps `C` to internal type 12, which is `80 `, an 8050 image. | Accept `C` and match nothing, because this drive has neither kind of partition. Recorded so the sd2iec mapping is not copied by mistake. | +| C6 | `=D` directory filter | `SD` and this firmware treat `D` as DIR. IDE 6.2 maps `D` to DEL. GSD warns that on other drives `D` matches everything. | Keep `D` as a synonym for `B` (SI-134), and say in the user documentation that software should send `B`. Changing it would break the sd2iec software that already sends `D`, and no software can be relying on `D` meaning DEL here because this drive has no DEL entries. | +| C7 | Wildcards with more than one `*` | `SD match_name_str()` and CBM DOS stop at the first `*`. This firmware backtracks. GAP calls the difference harmless. | Keep the current behaviour (SI-136). For one `*` it agrees with sd2iec's default; for more it narrows rather than widens a match, so no command can act on more files than the other devices would. | +| C8 | G-P byte 1 | HD and RL say reserved zero. FD defines a disk-information bit field and `SD` writes `0xE2`, which decodes as an FD-2000 with a 1.6 MB disk. | **Zero** (SI-042). Byte 1 is a claim about the device model, and this drive is not an FD. | +| C9 | G-P block unit | HD and FD count 512-byte blocks; RL counts 256-byte blocks. | **512** (SI-041), following the HD, which is the reference text and the larger of the two devices this drive resembles. | +| C10 | What `M-R` should answer | Nothing documents what C64 OS concludes from each answer. SD README says not to use `M-R` for detection at all. The reporter proposed a constant 42. | **The requested count of `$00` bytes at every address, and no magic table** (SI-112, SI-113). `$00` matches no model signature, and it is the value sd2iec deliberately returns at `$FFFE` to make Action Replay 6 fall back to the KERNAL loader. Faking a 1541 signature would invite a loader to upload drive code this drive cannot run. Identification is the `UI` string, whose format SI-114 fixes. | +| C11 | Whether `UJ` and `U`+shifted J lock the bus | GAP reports it against firmware 3.10a. Nothing since has tested it. | **Settled from the code, not by re-measuring** (SI-103). `IecDrive::reset()` reaches `IecInterface::configure()`, which sets `HW_IEC_RESET_ENABLE = 0` and holds the IEC processor in reset while it rewrites the slots. Command handlers run on the IEC task inside the bus state machine with the host still addressed, so that call is a bus-lock by construction. The requirement is that no reset command touches the interface, which removes the mechanism whether or not 3.10a's symptom survives today. | +| C12 | Shifted space (`$A0`) inside a name | The reporter wrote that this "is a topic of its own, but I do not want to start that topic without having discussed that first". | **Decided** (SI-147 for the two defects, SI-148 for the policy): `$A0` is legal inside a name and maps to `{A0}`; a trailing run is padding and is dropped; a name that is empty or starts with `$A0` is refused on create; a listing ends the name at its terminator or at 16 characters rather than at the first `$A0`, because ending it earlier would make this drive and an sd2iec print different names for the same file. | +| C13 | GAP's report that copy produces `kernal.bin.bin` and ignores paths | Measured against firmware 3.10a. | **Already fixed.** Measured on the head of PR #881 with a probe linked against the host suite's objects: the target gets one extension and a target path is honoured (SI-075). The requirement is a regression test. | +| C14 | `R` across directories | IDE 15.2.3 renames or moves a file between directories. `SD parse_rename()` answers `62,FILE NOT FOUND` when the two paths differ. HD 9-26 says the two names must be in the same partition. | This document decided **62** (SI-074), by precedence rule 3: SD wins over IDE. **PR #881 reversed it:** the move worked before PR #881, a test on `master` asserted it, and no program has been named that needs the `62`. | +| C15 | The two identification bytes in a listing header | 917 reports that this drive prints `00 2a` where a CMD HD prints `hd 1h`, and calls the difference harmless. `SD dirheader[]` prints the disk id `IK` and the DOS version `2A`. | **Keep `00 2a`.** The field is a claim about the device: `1H` is the CMD HD's own DOS version, and a drive that answers `UI` with its own identification string (SI-114) should not print a CMD HD's version in its listings. sd2iec prints a made up id and `2A` for the same reason, so the shape of the current answer is the one an sd2iec-like device gives. | +| C16 | The low byte of a line's link pointer | 917 reports that a CMD HD prints `01 01` on every line and that this drive prints something else. SD README defines the low byte as `(filesize MOD 254)+2`, and GSD documents it. | **Keep the remainder** (SI-133). It is what sd2iec does, its author documented it, and it is the only way a program can learn a file's exact length from a listing. A program that reads the link as an end-of-program marker is unaffected, because the byte is never 0 and the high byte stays 1. | + + +## 17. Tests + +Every requirement gets a test at the cheapest layer that can fail for it. + +**T1. Parser, `target/pc/linux/parse`.** Command recognition, parameter splitting, +error codes, path and name grammar, the terminator rules of SI-016 to SI-019, the +name mapping of SI-141 and SI-142. These run in well under a second and need no file +system. + +**T2. Drive, `target/pc/linux/iecdrive`.** Everything that needs a file system: the +listing layouts of section 13, the partition directory of section 5.3, file and +directory commands, relative files, direct access, the x00 wrapper. The existing +suites 3 to 10 are the model, and Suite10 already covers the #875 to #877 work. + +The measurements marked "measured" in this document were taken by linking a small +probe against this target's objects, sending each command through +`IecCommandChannel::push_command()` and reading `IecDrive::get_error_string()` back. +Those cases belong in the suite as they are implemented, one assertion per +requirement, so that the answer recorded here becomes the answer the suite enforces. +The set is: the ten commands of the probe's first section (`A`, `V`, `R-P`, `S-8`, +`W-1`, `U0>`, `L`, `R-H`, `I`, `M-R`), the scratch of SI-033, the `MD` and +`RD` forms of SI-060 and SI-063, the two copies of SI-075, the three filters of +SI-134, and the four left-arrow forms of SI-014. The listing layout of SI-138 and SI-139 +needs a reader that addresses the channel to talk for every byte, because a whole stream +read cannot fail for either of them. For the requirements PR #881 decided not +to implement, the tests assert the answer given in the decision, so that a later +implementation has to change a test on purpose. + +**T3. Hardware, `tests/e2e/io/iec`.** Only what a host build cannot reach. Two +classes qualify and both have already caught defects: + +* Anything that goes through the firmware's own `sscanf` in + `software/system/small_printf.cc` rather than the C library's. That implementation + supports only `%d`, `%x`, `%c` and `%s`, has no field width, no conversion + suppression and no length modifiers, and its `%s` writes an unbounded word. A host + build links glibc and will not see the difference. The time-stamped listing filter + of SI-135 is parsed with it, and that is how the `30,SYNTAX ERROR` recorded in + `tests/e2e/io/iec/README.md` reached a device that a host build said was fine. +* Anything whose input is the byte sequence a Commodore actually puts on the bus, + which is what `iec_agent.asm` produces. The #875 to #877 defects were all of this + kind: a host test that builds its command strings by hand cannot fail for them. +* Anything whose behaviour depends on the signedness of `char`. The host builds are + `-fsigned-char`, the U64 build is Nios II and also signed, and the U64 II and U2+L + builds are RISC-V and unsigned. SI-147 is the known case and no host test can see + it. A cheaper alternative for this one class is to compile the affected host suite + a second time with `-funsigned-char` and run both, which would catch it without a + device. + +**T4. The C64 OS acceptance test.** Install C64 OS on a Software IEC partition, boot +it, and compare the `SoftIEC:` lines of the resulting log against TRACE. The drive +logs a line only for a failed command, a failed open and a channel fault, so the +criterion is that no such line carries an error code that a CMD HD would not also +produce. TRACE gives +the baseline: 68 commands, 107 opens, 108 closes and 80 status reads in one boot, and +of its 601 lines 11 carry `33,SYNTAX ERROR` and 9 carry `62,FILE NOT FOUND`. + +--- + +## 18. Order of work + +Grouped so that each group is independently shippable and independently testable. + +**Group 1, the defects the reporter raised.** SI-031 error codes, SI-033 scratch, +SI-045 and SI-046 the partition directory, SI-053 `I`, SI-072 image names, +SI-083 `P` on a write channel, SI-105 memory commands, SI-071 `N`. These are the +contents of issues #877 and #890 and they are what unblocks the reporter's testing. + +**Group 2, the limits.** SI-021 and SI-022 buffer size and the 32 error. This is a +data loss defect and it gates anything that sends a long path, which C64 OS does. + +**Group 3, the missing commands.** SI-100 `U0>`, SI-101 `S-8`/`S-9`/`S-D`, +SI-102 `W-0`/`W-1`, SI-054 `V`, SI-051 `R-P`, SI-064 `R-H`, SI-076 `L`. + +**Group 4, the grammar.** SI-012 wildcards in path components, SI-014 the left arrow, +SI-016 the second terminator branch, SI-060 the `MD` colon, SI-063 the `RD` path +rejection, SI-074 rename checks, SI-093 direct access partition binding. + +**Group 5, the listings.** SI-130 header bytes, SI-133 the size remainder, +SI-065 the header name, SI-137 the raw directory, SI-138 the end of file at the end of a +listing, SI-139 the length and columns of a time stamped line, SI-149 the type of a file +inside a disk image. + +**Group 6, naming.** SI-147 first, because it is the only requirement in this +document that makes two Ultimate models write different bytes to the same medium. +Then SI-142 the two divergences, then SI-144 to SI-146 x00 together with SI-084, +which is the relative file reader the wrapper completes. + +**Group 7, the rest.** SI-090 to SI-092 large buffers, SI-094 `B-R` and `B-W`, +SI-077 the sd2iec attribute commands, SI-120 clock writes. + +Several requirements in groups 3, 5, 6 and 7 were then decided against; section 18.1 +lists them. + +The `SOFTIEC-TRACE` diagnostics added by PR #881 were reduced, before release, to two +kinds of `SoftIEC:` line. The drive always writes one for a command that leaves an +error, an open that fails and the first failure of a channel. With the setting **Log +Every Operation** in the SoftIEC Drive Settings, which is off by default, it also writes +one for every other command, open and close. Such a line adds the reply of a command +that answers with data, such as `M-R`, the host file an open reached or the first 32 +bytes of a listing, and a listing writes its last line as well. Every line carries the +bytes the host sent, the error channel's answer, and the current partition and its +directory as they are once the operation has run, so the line of a `CD` shows the +directory it entered. Every line ends in ` #` and a sequence number that counts the lines +the drive has written, so a reader can tell a line lost or delivered twice on the way to +the log from one the drive wrote twice. With the setting off, a successful command costs one read of the setting and +writes nothing. The setting exists so that a trace like TRACE, of what a program sends +and what the drive answers, can be recorded with a release build. + +Each part of a line is rendered into a fixed buffer of 260 characters that the rendering +never passes, and the lines are written while the drive lock is held. +`Suite11-OperationLogBounds` sends the longest command, name, reply, directory and host +path the drive accepts with the setting on, and the AddressSanitizer build fails on a +byte outside those buffers. The serial port takes each line one character at a time, so +with the setting on an operation also takes as long as its line needs to be sent. The +firmware's `printf` does not keep a line together, so a message another task prints at +the same moment can split a `SoftIEC:` line in two, and the rest of the line then +arrives with the next syslog message. With the firmware also printing its REST and FTP +requests, this happened to 1 line of 732 during a Software IEC soak on an Ultimate 64 +Elite, and to 15 lines of 668 during `iec-dos-commands` and a soak on a U2+L. + +### 18.1 What PR #881 implements + +PR #881 implements a requirement when it fixes a defect, or when the reporter of #877, +#890 or #917, GAP or TRACE names it. A review of the implementation against that rule decided +against the requirements in the first table and narrowed the ones in the list after it. +Each of them also has a **Decision (PR #881)** paragraph below the requirement itself, and +the tests assert the answer given here. The requirements not named in this section are +implemented as written; the **Decision (PR #881)** paragraphs of SI-076, SI-084, SI-100, +SI-144 and SI-152 only record how they were implemented. + +**Not implemented.** No command in TRACE uses any of these, so a C64 OS boot is not +affected by them. + +| Requirement | Why it is not implemented | What the drive answers | +| --- | --- | --- | +| SI-051 `R-P` | No report, GAP or TRACE uses it, and the new name would only live in memory until the partition list is saved from the menu | `30` | +| SI-054 `V` | Inside a disk image, an OK would claim a validation of the block map that did not happen | `31` | +| SI-064 `R-H` | On a host directory it would rename the directory itself, which a CMD HD's header rename does not do; sd2iec does not support it either | `30` | +| SI-077 `EL:`, `EU:`, `EH:`, `A:`, `XH:`, `D:` | `L` (SI-076) provides lock and unlock; hiding files has no effect while listings show hidden files; the header forms are `R-H` | `30` for the `E` and `X` forms, `31` for `A` and `D` | +| SI-090 `##n`, SI-092 | Large buffers serve sd2iec's 512 byte sector commands `DR` and `DW`, which are out of scope (SI-096); this drive's block commands use 256 byte sectors | `##n` opens a standard buffer; a third `B-P` number is ignored | +| SI-101 `S-8`, `S-9`, `S-D` | There is no second drive to swap with | `31`, as sd2iec answers | +| SI-102 `W-0`, `W-1` | No report or program asks for a software write protect, and it needs a check in every path that writes | `31` | +| SI-105 `M-W`, `M-E` | Nothing written is kept and nothing is run, so an OK would tell a fast loader its drive code runs | `30` | +| SI-120 `T-WA`, `T-WB`, `T-WD`, `T-WI` | The clock belongs to the system, and C64 OS sets it through its UCI clock driver (GAP) | `30`, which SI-120 allows | +| SI-137 raw directory | It would change what existing programs, and clients of the UCI target, receive when they open `$` on a data channel | the listing, as before | +| SI-145 writing x00 files | A new user setting that no report asks for; reading x00 files (SI-144) already gives the interchange | new files are written plain | + +**Implemented in part, or with a difference.** For each: what is implemented, what is +not, why, and whether a C64 OS boot as recorded in TRACE is affected. + +* **SI-016, the command terminator.** + * Implemented: a carriage return at the end of a command is dropped (the ROM's first + branch), except after `C`+shifted P (SI-017). A carriage return followed by a line + feed at the end is dropped as well, and a lone carriage return answers `31`. + * Not implemented: the ROM's second branch, which also ends a command at a carriage + return second to last when the last byte is something else, dropping that byte. Here + both bytes stay part of the command, so `S:NAME`+`CHR$(13)`+`X` scratches nothing + where a 1541 scratches `NAME`. + * Why: that branch cuts a binary parameter of 13 short, such as the high byte of an + `M-R` address or its count, and the reporter asked on #877 for it not to be reproduced. + * C64 OS: not affected. None of the 68 commands in TRACE has a carriage return before its + last byte. +* **SI-018, `P`.** + * Implemented: the record number and the offset of a relative file are taken from the + command as sent, so an offset of 13 is kept. + * Different: the position in a plain file is taken from the command without its + terminator, where sd2iec takes it from the command as sent. `"P"+CHR$(2)+CHR$(100)` + from BASIC positions to byte 100 here and to byte 3,428 on sd2iec. + * Why: this drive positioned to byte 100 before PR #881, and that is what GSD's + documented form means. + * C64 OS: not affected; TRACE has no `P`. +* **SI-022, commands that fill the buffer.** + * Implemented: a command of 254 bytes or more answers `32` and is not executed. + * Different: an OPEN name of 254 bytes or more also answers `32` and opens nothing; the + requirement names only commands. + * Why: a name cut short would create or read a file under its first bytes, the same data + loss the requirement prevents for commands. + * C64 OS: not affected; its longest open name in TRACE is 26 bytes. +* **SI-033, scratching nothing.** + * Implemented: a scratch that matches nothing answers `01,FILES SCRATCHED,00,00`, which + is what C64 OS's `S/TEMPORARY/:*` receives at boot. + * Different: a scratch whose path does not exist answers `71,DIRECTORY ERROR` instead. + * Why: a mistyped path should be reported rather than look like an empty directory; + sd2iec reports it as well. + * C64 OS: not affected. Its system directory contains `temporary/`, whose files it + scratches at boot (C64 OS file system documentation). +* **SI-071, `N`.** + * Implemented: creating and formatting D64, D71, D81 and DNP images in a host directory. + * Not implemented: `N` inside a mounted disk image, which sd2iec answers by formatting + that image. Here it answers `30`. + * Why: the image file would be rewritten under the file system that has it mounted and + caches its block map. + * C64 OS: not affected; TRACE has no `N`. +* **SI-074, rename.** + * Implemented: `34` for an empty new name, `33` for a wildcard in it, `63` for a name any + entry already has, and the rename of a subdirectory (HD 9-26, "Renaming Files and + Subdirectories"). + * Not implemented: `62` for a rename into another directory or partition. The file is + moved, as it was before PR #881 (decision C14 is reversed). + * Why: the move worked on `master`, a `master` test asserted it, and IDE64 documents it; + no program has been named that needs the `62`. + * C64 OS: not affected; TRACE has no `R`. +* **SI-090, direct access buffers.** + * Implemented: `#` opens a 256 byte buffer with its pointer at byte 1, block commands on a + channel not opened with `#` answer `70`, and the channel keeps its partition (SI-093). + * Not implemented: `##n`; see the table above. + * C64 OS: not affected; TRACE has no `#`. +* **SI-105, memory commands.** + * Implemented: `M-R`, the four probes C64 OS sends at boot, answers the requested count of + `$00` bytes. + * Not implemented: `M-W` and `M-E`; see the table above. + * C64 OS: `M-R` is the part it uses. +* **SI-134, directory filters.** + * Implemented: the type filters, and `H`, which no longer sets a type bit, so `$:*=H` + lists every entry instead of none. + * Not implemented: leaving hidden files out of a listing unless `H` is given. Hidden + files are listed, as before PR #881. + * Why: C64 OS hides files by a leading dot rather than by an attribute, and no report + asks for the change. + * C64 OS: not affected; TRACE lists with `$` and `$:pattern` only. +* **SI-136, wildcard matching.** + * Implemented: the full glob with any number of `*`, as the requirement records. + * Different: the requirement calls the matcher unchanged, but it had two defects that PR + #881 fixed. It took time exponential in the number of stars, so one command such as + `S:****************Q` kept the IEC task busy for minutes, and it matched a name that + ended where the pattern had a `*`, whatever followed, so `S:FOO*X` scratched `FOO`. + * Why: both are defects, and the second deletes files the pattern does not name. + * C64 OS: not affected. The only pattern in a command in TRACE is `S/TEMPORARY/:*`, and + its listings use `$:MENU.M` and `$:UTILITIES.M`, which contain no star. +* **SI-142, host names.** + * Implemented: `*` and `?` are escaped as `{2A}` and `{3F}`, and scratch, `RD` and opens + by pattern match through a directory scan. + * Not implemented: sd2iec's length guard. + * Why: the difference is only in what the length parameter means, and changing it changes + no host name the drive produces; the one overrun that existed, the `{}` appended to a + long name ending in `.prg`, is fixed. + * C64 OS: not affected. +* **SI-146, relative files in x00 wrappers.** + * Implemented: an existing `R00` file is read and written through its header. + * Not implemented: creating one; a new relative file is written in the plain two byte + layout, because SI-145 is not implemented. + * C64 OS: not affected; TRACE opens no relative file. + +### 18.2 Defects fixed alongside + +The implementation also fixed defects that this specification does not name, found by a +randomized soak of the drive under AddressSanitizer and by a review aimed at crashes. They +are listed in the description of PR #881 with the test that shows each one: a negative +byte count offered for a record read past its end, a disk image chain walked off the +disk, a read past the end of a file in a disk image, host names copied without a +terminator, a disk image released by the mount cache while a listing still read it, +exponential wildcard matching, sector access without the file manager's lock, a copy that +leaked its buffer when a source partition did not exist, a UCI open that left the +previous file open, and concurrent access to the partition table from the menu, REST, +UCI and the IEC task. + +The stress mode of the Software IEC soak found one more on both devices: `B-A` of a block +that is already allocated answered `74,DRIVE NOT READY`. It now answers `65,NO BLOCK` with +the next higher free track and sector, or track 0 when no higher block is free, as the +1541-II User's Guide (error 65) and HD 9-43 describe. `B-F` of a block that is already +free, which also answered 74, now answers OK and changes nothing; neither manual lists an +error for it. sd2iec does not implement `B-A` or `B-F`. + +A review of the operation log found that any change in the Software IEC settings held the +IEC processor in reset, so turning **Log Every Operation** on or off dropped a transfer on +the bus. Only a change of the device number or of the enable reconfigures the processor now. + +--- + +## 19. Out of scope + +Named so that the boundary is explicit rather than implied. + +* Burst commands and the C128 fast serial protocol (HD 9-52 to 9-64). +* The job queue (HD 9-65 to 9-67), block execute (SI-095) and user jumps (SI-104): + all of them run 6502 code in drive memory. +* `S-C`, the SCSI pass-through (SI-106). +* 1581-style sub-partitions (SI-055). +* The sd2iec direct sector commands `DI`, `DR`, `DW` (SI-096). +* Serving a drive ROM image for `M-R` so that GEOS and Wheels identify a drive + (SI-115). GEOS and Wheels support needs gateware work and is a separate project; + the reporter asked that the documentation say so. +* Swap lists, `XS` and the disk change buttons: they are a user interface feature of + a device with physical buttons, and `U cbmdos_parser.cc` already records the + reasoning, "Swaplists are not part of the drive, they are part of the user + interface." +* M2I files, which sd2iec itself has deprecated (SD README, Deprecation notices). +* Mapping each Ultimate storage device to its own IEC device number, which GAP asks + for. The partition model in section 2 answers the same need within one device + number, and C64 OS supports at most five devices at once against 255 partitions. +* Commands that appear in the reference documents and are not specified above. They + are listed so that the omission is deliberate. None of them gets a requirement here; + where the command's first letter is a command letter, the general rule of SI-030 + applies and the answer is `30`, and where it is not, SI-031 applies and the answer + is `31`. + * HD Appendix J: `BOOT` (a BASIC 7.0 statement, not a command-channel command); + the `U0` utility forms other than `U0>`+`CHR$(d)`, that is `U0`, `U0+`, `U0-`, + `U0>B0`, `U0>B1`, `U0>R`, `U0>S`, `U0>T`, `U0>V0`, `U0>V1`, `U0>M0`, `U0>M1`, + `U0>MR` and `U0>MW` (HD 9-49), which select serial timing, retries, interleave + and 1571 modes that this drive does not have. The 1541 ROM's command table at + `$FE89` also carries `&` (execute utility file), which HD does not list. + * IDE section 15: 15.2.3 moving a file between directories with `R` (this + specification follows `SD parse_rename()` and answers `62`, SI-074; see C14); + 15.2.5 hide; 15.4.2 get disk change; 15.4.5, 15.4.6 and 15.4.7 (`U0>P`, `U0>E`, + `U0>L`, power, eject and medium lock); 15.4.9 format disk; 15.5.1 direct access + identify and the LBA forms of buffer read and write; 15.6.2 change root + directory; 15.7 CD-ROM commands. All of them address IDE64 hardware or its CFS + file system. + * SD README: the settings commands `X`, `XE+`/`XE-`, `XEL`/`XEU`, `XET`, `XI`, + `XN`, `XH+`/`XH-`, `XD`, `XW`, and `XL`/`XU`, which the README names in a heading + and does not describe. This drive keeps its settings in the Ultimate + configuration; SI-145 is the one sd2iec setting (`XE`) that gets a counterpart. + `XS` and `XR` are listed above. +* The firmware hang the reporter saw three times on #877 while starting C64 OS, where + "the ultimate becomes unresponsive it's completely dead, just the c64 is still + running. But not the soft iec. The menu button is dead." Nothing in this + specification addresses it, because nothing here explains it: the reported sequence + is power on, enable Software IEC, add a partition, `@"cp2"`, load the directory, + run C64 OS, and the successful run of exactly that sequence is TRACE. It is a + separate investigation and needs its own issue. What would move it forward is a + syslog capture that ends at the hang rather than one from a successful boot, and + whether REST and ping still answer while the menu button does not. PR #881 fixed the + crash and hang defects of section 18.2, measured the IEC task's stack after a soak on + a U2+L (3,352 of 6,400 bytes left), and added a soak of the drive over the real bus, + `tests/soak/io/iec/softiec_soak_test.py`; none of them reproduced the hang. + +--- + +## Appendix A. What C64 OS sends + +From TRACE, one successful boot: 68 commands, 107 opens, 208 data addressings, 108 +closes, 80 status reads. Eighteen distinct command strings, eighty-four distinct open +names, longest open name 26 bytes. + +| Command | Count | Answer today | +| --- | --- | --- | +| `C`+`$D0`+`CHR$(2)` | 29 | `02,PARTITION SELECTED` | +| `CD//OS/DESKTOP/1/` | 11 | `00, OK` | +| `CD//OS` | 6 (plus one with a terminator) | `00, OK` | +| `CD//OS/SERVICES/{$C1}PP {$CC}AUNCHER/` | 6 | `00, OK` | +| `CD//OS/DRIVERS/` | 3 | `00, OK` | +| `CD//OS/SETTINGS/`, `CD//OS/DESKTOP/`, `CD//OS/CHARSETS/` | 1 each | `00, OK` | +| `CP2`, `CP2`+CR | 1 each | `02,PARTITION SELECTED` | +| `M-R` at `$FEA4`, `$E5C5`, `$A6E8`, `$0002`, 2 bytes each | 1 each | `33,SYNTAX ERROR` | +| `UI` | 1 | `73,U64HD ULTIMATE DOS V2.0` | +| `S/TEMPORARY/:*` | 1 | `62,FILE NOT FOUND` | +| `CHR$(0)` | 1 | `33,SYNTAX ERROR` | + +Open names are of the forms `NAME`, `:NAME`, `/PATH/:NAME`, `$` and `$:PATTERN`. +Data channels used are 0, 2, 3 and 14. Names carry shifted PETSCII and spaces, for +example `:{$C1}BOUT {$D4}HIS {$C1}PP`. + +So the whole of a C64 OS boot needs: the binary Change Partition, `CD` with an +absolute path, `M-R`, `UI`, `S` with a path, a directory read with and without a +pattern, and file opens with a path. Everything else in this specification is for the +other software that already targets these devices. + +## Appendix B. Requirement index + +Sections 2 to 15 define 105 numbered paragraphs, SI-001 to SI-153 with gaps, one of +which (SI-151) is retired. Requirements that change nothing are marked "Unchanged" +and exist as a contract. Requirements marked "Change required", or stated as "Add", +"Close" or "Not implemented" (SI-036, SI-077, SI-142, SI-144 to SI-146), are the +work, and section 18 orders them. Section 18.1 lists the requirements PR #881 decided +not to implement or implemented in part, and each of them carries its decision below +the requirement. + +## Appendix C. The programs issue #917 reports + +Both programs were reported as photographs of a C64 screen. They are transcribed here so +that they can be run and turned into tests without reading the pictures again. + +The first program copies a time stamped listing byte by byte onto a second device. Greg +Nacu ran it with the listing on a Software IEC partition and the output file on an +sd2iec, and it never ended. + +```basic +10 OPEN2,8,2,"@//:DIRDATA.D,S,W" +20 OPEN3,8,0,"$=T:*" +30 GET#3,A$:S1=ST:PRINT#2,A$; +40 IFS1=0THEN30 +50 CLOSE2:CLOSE3 +``` + +Line 30 saves the status of the read in `S1` before the write to the other device +overwrites `ST`. Line 40 loops while that status is 0, so the program ends on the first +read whose status is not 0, which on a CMD HD and on an sd2iec is the 64 of the last byte. + +The second program is the reduced case, with no second device involved. It prints the +value of each byte and the status that came with it. + +```basic +10 OPEN2,8,0,"$=T:*" +20 GET#2,A$:A$=A$+CHR$(0):S1=ST:PRINTASC(A$),S1 +30 IFS1=0THEN20 +40 CLOSE2 +``` + +The photograph of its output ends with a line reading `0` and `64`: the last byte of the +listing is a zero and it arrives with end of file set. Against this drive the same program +printed `0` and `0` without stopping. SI-138 is the requirement, and the screen above the +first program also shows the directory it was reading, whose header is the CMD HD's +`1 "TESTS " HD 1H` (C15). diff --git a/run-tests b/run-tests index 7013f1541..2cb355798 100755 --- a/run-tests +++ b/run-tests @@ -644,6 +644,14 @@ SUITES: Sequence[Suite] = ( Suite("soak", "mount-cache-leak", "tests/soak/filemanager/mount_cache_leak_test.py", "-H @HOST@ -p @PASS@ -t @TIMEOUT@"), + # The Software IEC drive driven from the C64 over the real bus while REST and FTP + # load the device (#877). The suite has a --mode: a realistic C64 OS soak, a hostile + # stress that edge-tests the interface, or both in turn. The --profile the runner + # passes maps to a single mode: the stress profile runs the stress mode for ten + # minutes, the soak profile runs the soak mode for four hours. See --help and + # tests/soak/README.md for --mode and the per-phase durations. + Suite("soak", "softiec-soak", "tests/soak/io/iec/softiec_soak_test.py", + "-H @HOST@ -p @PASS@ -t @TIMEOUT@ --profile @SOAKPROFILE@"), ) diff --git a/software/chan_fat/full/ffconf.h b/software/chan_fat/full/ffconf.h index e4f55b53d..867418a13 100644 --- a/software/chan_fat/full/ffconf.h +++ b/software/chan_fat/full/ffconf.h @@ -52,7 +52,7 @@ /* This option switches f_expand function. (0:Disable or 1:Enable) */ -#define FF_USE_CHMOD 0 +#define FF_USE_CHMOD 1 /* This option switches attribute manipulation functions, f_chmod() and f_utime(). / (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */ diff --git a/software/chan_fat/pc/ffconf.h b/software/chan_fat/pc/ffconf.h index 2fef9160e..5e426ab80 100644 --- a/software/chan_fat/pc/ffconf.h +++ b/software/chan_fat/pc/ffconf.h @@ -50,7 +50,7 @@ /* This option switches f_expand function. (0:Disable or 1:Enable) */ -#define FF_USE_CHMOD 0 +#define FF_USE_CHMOD 1 /* This option switches attribute manipulation functions, f_chmod() and f_utime(). / (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */ diff --git a/software/components/pattern.cc b/software/components/pattern.cc index 482de5266..790584efc 100644 --- a/software/components/pattern.cc +++ b/software/components/pattern.cc @@ -75,56 +75,56 @@ static char get_escaped_char(const char *&p, bool &escape) return ret; } +// * matches any run of characters, including none, and ? any one character. The last * +// takes one more character each time the rest of the pattern fails, which takes time +// proportional to the product of the two lengths; the recursion this replaces took time +// exponential in the number of stars, which one command from the IEC bus can send. The +// recursion also matched a fixed string that ended where the pattern had a *, whatever +// followed it, so S:FOO*X scratched FOO. bool pattern_match(const char *pattern, const char *fixed, bool case_sensitive) { - const char *p; - const char *f; + const char *p = pattern; + const char *f = fixed; + const char *star_p = NULL; // the pattern after the last * + const char *star_f = NULL; // where in the fixed string that was last tried char cp, cf; - p = pattern; - f = fixed; - do { - if(!(*p)) { // end of pattern - return (*f == '\0'); // if the fixed is also at the end, we have a match, - // if not, then our pattern is too short and we don't match - } - if(!(*f)) { // end of fixed string - if(*p == '*') // check special case foo* == foo. + while(true) { + if(!(*f)) { // end of fixed string: what is left of the pattern may only be stars + while(*p == '*') + p++; + if(!(*p)) return true; - else - return false; // our pattern string was longer - } - if(*p == '*') { + } else if(*p == '*') { p++; // skip the * and set pointer to next character if(!(*p)) // end of our pattern, so we have a match return true; - - // now, recurse and try to find the pattern AFTER the * in the fixed string - while(*f) { - bool match = pattern_match(p, f, case_sensitive); - if(match) - return true; - f++; - } - return false; - } else if(*p == '?') { - // assume equality; continue + star_p = p; + star_f = f; + continue; } else { - if(!case_sensitive) { - cp = toupper(*p); - cf = toupper(*f); + if(*p == '?') { + cp = cf = 0; // assume equality + } else if(!case_sensitive) { + cp = toupper(*p); + cf = toupper(*f); } else { cp = *p; cf = *f; } - if(cf != cp) - return false; // two character inequal - } - f++; - p++; - } while(true); - - return false; // never gets here. + if(cf == cp) { + f++; + p++; + continue; + } + } + // No match from here: let the last * take one more character of the fixed string. + if(!star_p || !(*star_f)) + return false; + star_f++; + p = star_p; + f = star_f; + } } bool pattern_match_escaped(const char *pattern, const char *fixed, bool case_sensitive, bool p_esc, bool f_esc) @@ -435,15 +435,19 @@ void petscii_to_fat(const char *pet, char *fat, int maxlen) while (*pet) { char p = *(pet++); - if (p == 160) { + // A trailing run of shifted spaces is the padding of a CBM directory entry and is + // dropped; one inside a name is escaped like any other byte (SI-147). The compare + // is on the byte's value, so a signed char build does the same as an unsigned one, + // and the end is tested on the byte that stopped the run, not on the one after it. + if ((uint8_t)p == 160) { const char *q = pet; - while (*(q++) == 160) + while ((uint8_t)*(q++) == 160) ; - if (!*q) + if (!*(q - 1)) break; } - if ((p < 32) || (p >= 96) || (p == ':') || (p == '/') || (p == '\\') || (p == '\x22') || - (p == '<') || (p == '>') || (first && p == '.')) { // '|' > 96 ;) + if ((p < 32) || (p >= 96) || (p == ':') || (p == '/') || (p == '\\') || (p == '*') || (p == '\x22') || + (p == '<') || (p == '>') || (p == '?') || (first && p == '.')) { // '|' > 96 ;) if ((i + 4) >= maxlen) { break; @@ -472,7 +476,7 @@ void petscii_to_fat(const char *pet, char *fat, int maxlen) } fat[i] = 0; - if (strlen(fat) > 3) { + if ((strlen(fat) > 3) && (i + 3 <= maxlen)) { // the braces and the terminator fit char *ext = fat + strlen(fat) - 4; if (!strcasecmp(ext, ".prg") || !strcasecmp(ext, ".seq") || !strcasecmp(ext, ".usr") || !strcasecmp(ext, ".rel")) { strcat(fat, "{}"); diff --git a/software/filemanager/filemanager.cc b/software/filemanager/filemanager.cc index a3b7ca36d..595917b1e 100644 --- a/software/filemanager/filemanager.cc +++ b/software/filemanager/filemanager.cc @@ -500,6 +500,28 @@ void FileManager::get_display_string(Path *p, const char *filename, char *buffer n->get_display_string(buffer, width); } +// A directory handed out by open_directory(). Its file system is listed in +// open_directory_fs until the directory is deleted, so the mount cache does not release +// a disk image that a directory is still being read from: the Software IEC keeps a +// listing's directory open across bus reads, while other channels enter other images. +class ManagedDirectory : public Directory +{ + FileManager *fm; + FileSystem *fs; + Directory *dir; +public: + ManagedDirectory(FileManager *m, FileSystem *f, Directory *d) : fm(m), fs(f), dir(d) { + fm->open_directory_fs.append(fs); // open_directory() holds the lock + } + ~ManagedDirectory() { + fm->lock(); + delete dir; + fm->open_directory_fs.remove(fs); + fm->unlock(); + } + FRESULT get_entry(FileInfo &info) { return dir->get_entry(info); } +}; + FRESULT FileManager::open_directory(const char *path, Directory **dir, FileInfo *info) { *dir = NULL; @@ -518,6 +540,9 @@ FRESULT FileManager::open_directory(const char *path, Directory **dir, FileInfo } FileSystem *fs = pathInfo.getLastInfo()->fs; res = fs->dir_open(pathInfo.getPathFromLastFS(), dir); + if ((res == FR_OK) && *dir) { + *dir = new ManagedDirectory(this, fs, *dir); + } unlock(); return res; } @@ -775,23 +800,51 @@ FRESULT FileManager::get_free(Path *path, uint32_t &free, uint32_t &cluster_size return fres; } +FRESULT FileManager::get_total(Path *path, uint32_t &total, uint32_t &cluster_size) +{ + PathInfo pathInfo(rootfs); + pathInfo.init(path); + lock(); + FRESULT fres = find_pathentry(pathInfo, true); + if (fres != FR_OK) { + unlock(); + return fres; + } + FileInfo *inf = pathInfo.getLastInfo(); + if (!inf || !(inf->fs)) { + unlock(); + return FR_NO_FILESYSTEM; + } + fres = inf->fs->get_total(&total, &cluster_size); + + unlock(); + return fres; +} + +// The sector functions take the lock like every other entry point: find_pathentry() can +// mount and evict disk images, which changes mount_points under another task. FRESULT FileManager::fs_read_sector(Path *path, uint8_t *buffer, int track, int sector) { PathInfo pathInfo(rootfs); pathInfo.init(path); + lock(); FRESULT fres = find_pathentry(pathInfo, true); if (fres != FR_OK) { + unlock(); return fres; } FileInfo *inf = pathInfo.getLastInfo(); if (!inf || !(inf->fs)) { + unlock(); return FR_NO_FILESYSTEM; } fres = inf->fs->sync(); if (fres != FR_OK) { + unlock(); return fres; } fres = inf->fs->read_sector(buffer, track, sector); + unlock(); return fres; } @@ -799,38 +852,47 @@ FRESULT FileManager::fs_write_sector(Path *path, uint8_t *buffer, int track, int { PathInfo pathInfo(rootfs); pathInfo.init(path); + lock(); FRESULT fres = find_pathentry(pathInfo, true); if (fres != FR_OK) { + unlock(); return fres; } FileInfo *inf = pathInfo.getLastInfo(); if (!inf || !(inf->fs)) { + unlock(); return FR_NO_FILESYSTEM; } fres = inf->fs->sync(); if (fres != FR_OK) { + unlock(); return fres; } fres = inf->fs->write_sector(buffer, track, sector); + unlock(); return fres; } -FRESULT FileManager::fs_allocate_sector(Path *path, int track, int sector, bool alloc) +FRESULT FileManager::fs_allocate_sector(Path *path, int &track, int §or, bool alloc) { PathInfo pathInfo(rootfs); pathInfo.init(path); + lock(); FRESULT fres = find_pathentry(pathInfo, true); if (fres != FR_OK) { + unlock(); return fres; } FileInfo *inf = pathInfo.getLastInfo(); if (!inf || !(inf->fs)) { + unlock(); return FR_NO_FILESYSTEM; } fres = inf->fs->allocate_sector(track, sector, alloc); if (fres == FR_OK) { fres = inf->fs->sync(); } + unlock(); return fres; } @@ -984,6 +1046,11 @@ bool FileManager::is_mount_evictable(MountPoint *mp) return false; } } + for (int i = 0; i < open_directory_fs.get_elements(); i++) { + if (open_directory_fs[i] == fs) { + return false; + } + } for (int i = 0; i < mount_points.get_elements(); i++) { MountPoint *other = mount_points[i]; if (other && (other != mp) && other->get_file() && @@ -1153,6 +1220,24 @@ FRESULT FileManager::delete_file(const char *pathname) return fres; } +// Sets the attribute bits in mask to those in attrib, for the file systems that keep any. +FRESULT FileManager::set_attributes(const char *pathname, uint8_t attrib, uint8_t mask) +{ + PathInfo pathInfo(rootfs); + pathInfo.init(pathname); + lock(); + FRESULT fres = find_pathentry(pathInfo, false); + if (fres == FR_OK) { + fres = pathInfo.getLastInfo()->fs->file_attrib(pathInfo.getPathFromLastFS(), attrib, mask); + if (fres == FR_OK) { + mstring work; + sendEventToObservers(eRefreshDirectory, pathInfo.getFullPath(work, -1), ""); + } + } + unlock(); + return fres; +} + FRESULT FileManager::delete_file(Path *path, const char *name) { PathInfo pathInfo(rootfs); diff --git a/software/filemanager/filemanager.h b/software/filemanager/filemanager.h index c34ef789b..a5cf33061 100644 --- a/software/filemanager/filemanager.h +++ b/software/filemanager/filemanager.h @@ -93,6 +93,7 @@ class FileManager #endif IndexedListmount_points; IndexedListopen_file_list; + IndexedListopen_directory_fs; // one entry per directory open_directory() handed out IndexedListmanaged_temp_entries; uint32_t next_temp_seq; bool temp_auto_cleanup_enabled; @@ -102,7 +103,7 @@ class FileManager CachedTreeNode *root; FileSystem *rootfs; - FileManager() : mount_points(8, NULL), open_file_list(16, NULL), managed_temp_entries(16, NULL), next_temp_seq(0), mount_use_seq(0), temp_auto_cleanup_enabled(true), temp_use_cache_subfolder_enabled(true), /*used_paths(8, NULL), */observers(4, NULL) { + FileManager() : mount_points(8, NULL), open_file_list(16, NULL), open_directory_fs(4, NULL), managed_temp_entries(16, NULL), next_temp_seq(0), mount_use_seq(0), temp_auto_cleanup_enabled(true), temp_use_cache_subfolder_enabled(true), /*used_paths(8, NULL), */observers(4, NULL) { root = new CachedTreeNode(NULL, "RootNode"); root->get_file_info()->attrib = AM_DIR; rootfs = new FileSystem_Root(root); @@ -151,6 +152,7 @@ class FileManager void enforce_temp_limits(void); // friend class FileDirEntry; + friend class ManagedDirectory; void lock() { #ifdef OS @@ -230,9 +232,11 @@ class FileManager void get_display_string(Path *p, const char *filename, char *buffer, int width); FRESULT get_free(Path *path, uint32_t &free, uint32_t &cluster_size); + FRESULT get_total(Path *path, uint32_t &total, uint32_t &cluster_size); + FRESULT set_attributes(const char *pathname, uint8_t attrib, uint8_t mask); FRESULT fs_read_sector(Path *path, uint8_t *buffer, int track, int sector); FRESULT fs_write_sector(Path *path, uint8_t *buffer, int track, int sector); - FRESULT fs_allocate_sector(Path *path, int track, int sector, bool alloc); + FRESULT fs_allocate_sector(Path *path, int &track, int §or, bool alloc); FRESULT fstat(Path *path, const char *filename, FileInfo &info); FRESULT fstat(const char *path, const char *name, FileInfo &info); diff --git a/software/filesystem/file_info.h b/software/filesystem/file_info.h index 4daa09827..cf4aa59cf 100644 --- a/software/filesystem/file_info.h +++ b/software/filesystem/file_info.h @@ -59,6 +59,7 @@ class FileInfo uint16_t lfsize; uint8_t attrib; /* Attribute */ uint8_t name_format; + uint8_t cbm_filetype; /* the CBM directory type bits, 0 when the file system has none */ char *lfname; char extension[4]; @@ -105,6 +106,7 @@ class FileInfo attrib = i->attrib; extension[0] = 0; name_format = i->name_format; + cbm_filetype = i->cbm_filetype; } ~FileInfo() @@ -124,6 +126,7 @@ class FileInfo attrib = i->attrib; extension[3] = 0; name_format = i->name_format; + cbm_filetype = i->cbm_filetype; } bool is_directory(void) { diff --git a/software/filesystem/file_system.h b/software/filesystem/file_system.h index 5f0431b04..aaab07541 100644 --- a/software/filesystem/file_system.h +++ b/software/filesystem/file_system.h @@ -42,15 +42,17 @@ class FileSystem virtual bool init(); // Initialize file system virtual bool is_writable() { return false; } // by default a file system is not writable, unless we implement it - // Three character partition type reported in the IEC partition directory ($=P). - // CMD DOS calls a partition that holds its own native file system "NAT", and - // reports a drive emulation partition by the drive model it emulates. A - // directory on the host file system and a DNP image are both native. - virtual const char *get_partition_type(void) { return "NAT"; } virtual FRESULT format(const char *name); // create initial structures of empty disk virtual bool supports_direct_sector_access(void) { return false; } + // Geometry of a file system that addresses its medium by track and sector, in the + // same terms as read_sector() and allocate_sector() below. Tracks are numbered + // from one. A file system without that kind of addressing reports no tracks. + virtual int get_num_tracks(void) { return 0; } + virtual int get_sectors_in_track(int track) { return 0; } + virtual FRESULT get_free (uint32_t *e, uint32_t *cs) { *e = 0; *cs = 0; return FR_OK; } // Get number of free sectors on the file system + virtual FRESULT get_total(uint32_t *e, uint32_t *cs) { *e = 0; *cs = 0; return FR_NOT_ENABLED; } // Get the number of clusters the file system holds, in the units of get_free virtual FRESULT sync(void) { return FR_OK; } // by default we can't write, and syncing is thus always successful // functions for reading directories @@ -63,6 +65,7 @@ class FileSystem virtual FRESULT file_open(const char *filename, uint8_t flags, File **); // Opens file (creates file object) virtual FRESULT file_rename(const char *old_name, const char *new_name); // Renames a file virtual FRESULT file_delete(const char *path); // deletes a file + virtual FRESULT file_attrib(const char *path, uint8_t attrib, uint8_t mask) { return FR_NOT_ENABLED; } // sets the attribute bits in mask to those in attrib virtual void file_print_info(File *f) { } // debug @@ -70,7 +73,10 @@ class FileSystem virtual bool needs_sorting() { return false; } virtual FRESULT read_sector(uint8_t *buffer, int track, int sector) { return FR_DENIED; } virtual FRESULT write_sector(uint8_t *buffer, int track, int sector) { return FR_DENIED; } - virtual FRESULT allocate_sector(int track, int sector, bool alloc) { return FR_DENIED; } + // Allocates or frees one block. Freeing a free block succeeds and changes nothing. + // Allocating an allocated block returns FR_EXIST with track and sector set to the next + // higher free block, or to 0 when no higher block is free. + virtual FRESULT allocate_sector(int &track, int §or, bool alloc) { return FR_DENIED; } }; #include "factory.h" diff --git a/software/filesystem/filesystem_d64.cc b/software/filesystem/filesystem_d64.cc index 8003c4ec5..a075be8bf 100644 --- a/software/filesystem/filesystem_d64.cc +++ b/software/filesystem/filesystem_d64.cc @@ -72,6 +72,33 @@ void FileSystemCBM::set_volume_name(const char *name, uint8_t *bam_name, const c } +// The layout table is a list of (number of tracks, sectors per track) pairs, ending +// in a pair whose track count is negative, which stands for every remaining track. +int FileSystemCBM::get_sectors_in_track(int track) +{ + if (track < 1) { + return 0; + } + --track; + const int *m = layout; + while ((m[0] >= 1) && (track >= m[0])) { + track -= m[0]; + m += 2; + } + return m[1]; +} + +// The medium ends where its last sector is, so the track that sector sits on is the +// last track. +int FileSystemCBM::get_num_tracks(void) +{ + int track, sector; + if (!get_track_sector(num_sectors - 1, track, sector)) { + return 0; + } + return track; +} + int FileSystemCBM::get_abs_sector(int track, int sector) { int result = sector; @@ -535,6 +562,35 @@ FRESULT FileSystemCBM::file_rename(const char *old_name, const char *new_name) return res; } +// A CBM directory entry has one attribute a host file system also has: the lock, bit 6 +// of the file type byte, which reads back as AM_RDO. +FRESULT FileSystemCBM::file_attrib(const char *path, uint8_t attrib, uint8_t mask) +{ + if (mask & ~AM_RDO) { + return FR_NOT_ENABLED; + } + PathInfo pi(this); + pi.init(path); + PathStatus_t pres = walk_path(pi); + if (pres == e_DirNotFound) { + return FR_NO_PATH; + } + if (pres != e_EntryFound) { + return FR_NO_FILE; + } + DirInCBM *dd = new DirInCBM(this, pi.getParentInfo()->cluster); + FileInfo info(56); + FRESULT res = find_file(pi.getFileName(), dd, &info); + if ((res == FR_OK) && (mask & AM_RDO)) { + DirEntryCBM *p = dd->get_pointer(); + p->std_fileType = (attrib & AM_RDO) ? (p->std_fileType | 0x40) : (p->std_fileType & ~0x40); + dirty = 1; + res = sync(); + } + delete dd; + return res; +} + FRESULT FileSystemCBM::deallocate_vlir_records(uint8_t track, uint8_t sector, uint8_t *visited) { uint8_t *rblk = new uint8_t[256]; @@ -704,17 +760,34 @@ FRESULT FileSystemCBM::write_sector(uint8_t *buffer, int track, int sector) return FR_OK; } -FRESULT FileSystemCBM::allocate_sector(int track, int sector, bool alloc) +// B-A of an allocated block answers 65, NO BLOCK, with the next higher free block, or track +// 0 when there is none (1541-II User's Guide, error 65; HD 9-43). set_sector_allocation() +// fails only when the block is already in the requested state. +FRESULT FileSystemCBM::allocate_sector(int &track, int §or, bool alloc) { int abs_sect = get_abs_sector(track, sector); if (abs_sect < 0) { return FR_INVALID_PARAMETER; } - bool res = set_sector_allocation(track, sector, alloc); - if (!res) { - return FR_DISK_ERR; + if (set_sector_allocation(track, sector, alloc) || !alloc) { + return FR_OK; } - return FR_OK; + for (int t = track, s = sector + 1; t <= get_num_tracks(); t++, s = 0) { + for (; s < get_sectors_in_track(t); s++) { + // Freeing succeeds only on an allocated block, and allocating it again restores + // the map and its free count exactly. + if (set_sector_allocation(t, s, false)) { + set_sector_allocation(t, s, true); + } else { + track = t; + sector = s; + return FR_EXIST; + } + } + } + track = 0; + sector = 0; + return FR_EXIST; } /************************************************************************************** @@ -1568,6 +1641,7 @@ FRESULT DirInCBM::get_entry(FileInfo &f) f.size = (int) p->size_low + 256 * (int) p->size_high; f.size *= 254; f.name_format = NAME_FORMAT_CBM; + f.cbm_filetype = tp; uint16_t yr = (p->year < 80) ? (p->year + 20) : (p->year - 80); f.date = yr << 9; @@ -2173,6 +2247,9 @@ FRESULT FileInCBM::read_linear(uint8_t *dst, int len, uint32_t& tr) return FR_DISK_ERR; } bytes_left = (1 + (int)fs->sect_buffer[1]) - offset_in_sector; + if (bytes_left < 0) { // positioned past the end of the file + bytes_left = 0; + } } // determine number of bytes to transfer now @@ -2415,7 +2492,7 @@ uint32_t FileInCBM::get_size() fs->get_track_sector(abs, ct, cs); do { abs = fs->get_abs_sector(ct, cs); - if (visited[abs]) { + if ((abs < 0) || visited[abs]) { // a link outside the disk, or a loop break; } visited[abs] = 1; diff --git a/software/filesystem/filesystem_d64.h b/software/filesystem/filesystem_d64.h index 8e1213c9d..4e347e492 100644 --- a/software/filesystem/filesystem_d64.h +++ b/software/filesystem/filesystem_d64.h @@ -204,6 +204,10 @@ class FileSystemCBM : public FileSystem bool is_writable(); bool supports_direct_sector_access(void) { return true; } + // Geometry, read out of the disk layout this file system was built with. + int get_num_tracks(void); + int get_sectors_in_track(int track); + // Create initial structures of empty disk virtual FRESULT format(const char *name) { return FR_NO_FILESYSTEM; } // Get number of free sectors on the file system @@ -220,10 +224,11 @@ class FileSystemCBM : public FileSystem FRESULT file_rename(const char *old_name, const char *new_name); // Renames a file FRESULT file_delete(const char *path); // deletes a file + FRESULT file_attrib(const char *path, uint8_t attrib, uint8_t mask); // only AM_RDO, the lock bit FRESULT read_sector(uint8_t *buffer, int track, int sector); FRESULT write_sector(uint8_t *buffer, int track, int sector); - FRESULT allocate_sector(int track, int sector, bool alloc); + FRESULT allocate_sector(int &track, int §or, bool alloc); friend class DirInCBM; friend class FileInCBM; @@ -252,7 +257,6 @@ class FileSystemD64 : public FileSystemCBM ~FileSystemD64() { } - const char *get_partition_type(void) { return "41 "; } bool init(void); FRESULT format(const char *name); FRESULT get_free (uint32_t*, uint32_t*); @@ -284,7 +288,6 @@ class FileSystemD71 : public FileSystemCBM delete[] bam2_buffer; } - const char *get_partition_type(void) { return "71 "; } bool init(void); FRESULT format(const char *name); FRESULT get_free (uint32_t*, uint32_t*); @@ -325,7 +328,6 @@ class FileSystemD81 : public FileSystemCBM delete[] bam_buffer; } - const char *get_partition_type(void) { return "81 "; } bool init(void); FRESULT format(const char *name); FRESULT get_free (uint32_t*, uint32_t*); diff --git a/software/filesystem/filesystem_fat.cc b/software/filesystem/filesystem_fat.cc index e2624e367..716a133bb 100644 --- a/software/filesystem/filesystem_fat.cc +++ b/software/filesystem/filesystem_fat.cc @@ -48,6 +48,18 @@ FRESULT FileSystemFAT :: get_free (uint32_t *e, uint32_t *cs) #endif } +// The data clusters of the volume: FatFs numbers them from 2 to n_fatent - 1. +FRESULT FileSystemFAT :: get_total (uint32_t *e, uint32_t *cs) +{ + *e = fatfs.n_fatent - 2; +#if FF_MAX_SS != FF_MIN_SS + *cs = fatfs.ssize * fatfs.csize; +#else + *cs = FF_MAX_SS * fatfs.csize; +#endif + return FR_OK; +} + bool FileSystemFAT :: is_writable() { #if FF_FS_READONLY @@ -164,6 +176,17 @@ FRESULT FileSystemFAT :: file_delete(const TCHAR *path) #endif } +FRESULT FileSystemFAT :: file_attrib(const TCHAR *path, uint8_t attrib, uint8_t mask) +{ +#if (FF_FS_MINIMIZE >= 1) || (FF_USE_CHMOD == 0) + return FR_NOT_ENABLED; +#else + mstring prefixedPath(prefix); + prefixedPath += path; + return f_chmod(prefixedPath.c_str(), attrib, mask); +#endif +} + FRESULT FileFAT :: read(void *buffer, uint32_t len, uint32_t *transferred) { if (!get_file_system()) { diff --git a/software/filesystem/filesystem_fat.h b/software/filesystem/filesystem_fat.h index bab7e6083..7915a67fb 100644 --- a/software/filesystem/filesystem_fat.h +++ b/software/filesystem/filesystem_fat.h @@ -29,8 +29,9 @@ class DirectoryFAT : public Directory inf->extension[0] = toupper(inf->extension[0]); inf->extension[1] = toupper(inf->extension[1]); inf->extension[2] = toupper(inf->extension[2]); - if(inf->lfname) { + if(inf->lfname && inf->lfsize) { strncpy(inf->lfname, fi->fname, inf->lfsize); + inf->lfname[inf->lfsize - 1] = 0; // a longer name is cut, not left unterminated } } @@ -96,6 +97,7 @@ class FileSystemFAT : public FileSystem bool init(void); // Initialize file system FRESULT format(const char *name);// Format! FRESULT get_free (uint32_t *e, uint32_t *cs); // Get number of free sectors on the file system + FRESULT get_total(uint32_t *e, uint32_t *cs); // Get number of clusters on the file system bool is_writable(); // by default a file system is not writable, unless we implement it FRESULT sync(void); // by default we can't write, and syncing is thus always successful @@ -107,6 +109,7 @@ class FileSystemFAT : public FileSystem FRESULT file_open(const char *filename, uint8_t flags, File **); // Opens file (creates file object) FRESULT file_rename(const char *old_name, const char *new_name); // Renames a file FRESULT file_delete(const char *path); // deletes a file + FRESULT file_attrib(const char *path, uint8_t attrib, uint8_t mask); bool needs_sorting() { return true; } }; diff --git a/software/io/command_interface/softiec_target.cc b/software/io/command_interface/softiec_target.cc index 509104656..224af7a09 100644 --- a/software/io/command_interface/softiec_target.cc +++ b/software/io/command_interface/softiec_target.cc @@ -56,6 +56,7 @@ void SoftIECTarget :: parse_command(Message *command, Message **reply, Message * *status = &c_iec_module_not_loaded; return; } + IecDriveLock guard(iec_drive); // the IEC task and the GUI reach the same channels (CR-6) switch(command->message[1]) { case SOFTIEC_CMD_IDENTIFY: @@ -270,6 +271,7 @@ void SoftIECTarget :: prepare_data(int count) void SoftIECTarget :: get_more_data(Message **reply, Message **status) { if (input_channel) { + IecDriveLock guard(iec_drive); #if SIEC_TARGET_DEBUG > 1 printf("Popping %d bytes.\n", input_length); #endif @@ -286,6 +288,7 @@ void SoftIECTarget :: get_more_data(Message **reply, Message **status) void SoftIECTarget :: abort(int a) { if (input_channel) { + IecDriveLock guard(iec_drive); int bytes = (a < input_length) ? a : input_length; #if SIEC_TARGET_DEBUG printf("Pop(%d:%d)\n", bytes, a); @@ -605,13 +608,19 @@ void SoftIECTarget :: cmd_get_iecname(Message *command, Message **reply, Message command->message[command->length] = 0; // make sure it's null terminated FileInfo info(128); info.lfname[127] = 0; - strncpy(info.lfname, (const char *)&command->message[2], 127); + const char *given = (const char *)&command->message[2]; + const char *base = strrchr(given, '/'); + strncpy(info.lfname, base ? (base + 1) : given, 127); get_extension(info.lfname, info.extension, true); filetype_t found_type = e_any; char iec_name[24]; IecPartition::CreateIecName(&info, iec_name, found_type); + // Given a full path, an x00 wrapper names the file the way the drive lists it (SI-144). + if (base) { + iec_x00_probe(FileManager::getFileManager(), given, iec_name, &found_type, NULL); + } data_message.message[0] = (uint8_t)found_type; data_message.length = 1 + strlen(iec_name); strcpy((char *)&data_message.message[1], iec_name); diff --git a/software/io/iec/cbmdos_parser.cc b/software/io/iec/cbmdos_parser.cc index 9c7ea0d33..fd6c4b871 100644 --- a/software/io/iec/cbmdos_parser.cc +++ b/software/io/iec/cbmdos_parser.cc @@ -114,7 +114,7 @@ int parse_full_path(const char *buf, filename_t& name, bool *replace = NULL, boo } name.has_wildcard = name.filename.contains_any("?*"); if (!path_only && name.filename.length() == 0) { - return ERR_ILLEGAL_NAME; + return ERR_NO_NAME; } return 0; } @@ -134,7 +134,7 @@ int parse_dir_option(const char *buf, dir_options_t &opt) case 'R': opt.filetypes |= 0x10; break; case 'B': opt.filetypes |= 0x20; break; case 'D': opt.filetypes |= 0x20; break; - case 'H': opt.filetypes |= 0x40; break; + case 'H': break; // show hidden files, which are listed anyway; not a file type (SI-134) case 'N': opt.timefmt = e_stamp_none; break; case '<': case '>': @@ -157,6 +157,24 @@ int parse_dir_option(const char *buf, dir_options_t &opt) return 0; } +// The partition directory takes a type where a directory of files takes its +// options: LOAD"$=P[:*][=tp]" with tp one of N, 4, 7, 8 or C. The bit set here is +// the CMD partition type code, so the drive can test it against a partition's own +// type without a second table. +int parse_partition_option(const char *buf, dir_options_t &opt) +{ + switch(buf[0]) { + case 'N': opt.partition_types |= (1 << 1); break; // native, and a DNP image + case '4': opt.partition_types |= (1 << 2); break; // 1541 image + case '7': opt.partition_types |= (1 << 3); break; // 1571 image + case '8': opt.partition_types |= (1 << 4); break; // 1581 image + case 'C': opt.partition_types |= (1 << 5); break; // 1581 CP/M, which this drive has none of + default: + return ERR_SYNTAX; + } + return 0; +} + int parse_open(const char *buf, open_t& fn) { fn.dir_opt = c_dir_options_init; @@ -201,7 +219,9 @@ int parse_open(const char *buf, open_t& fn) const char *parts[6] = { NULL }; int n = opts.split(',', parts, 6); for (int i=0;ido_block_read(p[0], p[1], p[2], p[3]); + return exec->do_block_read(p[0], p[1], p[2], p[3], true); case 'W': n = parse_block_parameters(params, param_len, p, 4); if (n != 4) return ERR_SYNTAX; - return exec->do_block_write(p[0], p[1], p[2], p[3]); + return exec->do_block_write(p[0], p[1], p[2], p[3], true); case 'P': n = parse_block_parameters(params, param_len, p, 2); if (n != 2) return ERR_SYNTAX; return exec->do_buffer_position(p[0], p[1]); case 'A': case 'F': + // Allocate and free take the partition, the track and the sector. They do + // not take a channel, because they touch no buffer; the manuals write them + // as B-A:"drive;track;block. A fourth number is what the ROM's parameter + // reader would have collected and the command would then have ignored. n = parse_block_parameters(params, param_len, p, 4); - if (n != 4) return ERR_SYNTAX; - return exec->do_block_allocate(p[0], p[1], p[2], p[3], buffer[2] == 'A'); + if (n < 3) return ERR_SYNTAX; + return exec->do_block_allocate(p[0], p[1], p[2], buffer[2] == 'A'); default: - return ERR_UNKNOWN_CMD; + return ERR_SYNTAX; } return 0; } @@ -317,10 +348,12 @@ int IecParser :: cp_command(const uint8_t *buffer, int len) { int part = 0; if (buffer[1] & 0x80) { // binary - part = buffer[2]; - if (len != 3) { + // C always carries its partition number, so anything after it is + // the terminator BASIC appends and not a second parameter. + if (len < 3) { return ERR_SYNTAX; } + part = buffer[2]; } else { // Partition 0 means "the one already selected", which is also what a command // with no number at all asks for. @@ -334,9 +367,27 @@ int IecParser :: cp_command(const uint8_t *buffer, int len) int IecParser :: dir_command(const uint8_t *buffer, int len) { if (buffer[1] != 'D') { - return ERR_UNKNOWN_CMD; + return ERR_SYNTAX; } mstring cmd((const char *)buffer, 2, len-1); + const char *colon = strchr(cmd.c_str(), ':'); + if (buffer[0] == 'M') { + // MD requires a colon, and a name that starts with a shifted space is no name + // (SI-060, SD parse_mkdir()). + if (!colon || ((uint8_t)colon[1] == 0xA0)) { + return ERR_NO_NAME; + } + } else if (buffer[0] == 'R') { + // RD takes a partition number and a name behind a colon, and no path, so that a + // directory cannot be removed from inside it (SI-063, HD 9-19, SD parse_rmdir()). + const char *p = cmd.c_str(); + while ((*p == ' ') || isdigit(*p)) { + p++; + } + if (strchr(cmd.c_str(), '/') || (*p != ':')) { + return ERR_NO_NAME; + } + } filename_t dest; int err = parse_full_path(cmd.c_str(), dest, NULL, true); if (err) { @@ -347,7 +398,7 @@ int IecParser :: dir_command(const uint8_t *buffer, int len) case 'M': return exec->do_make_dir(dest); case 'R': return exec->do_remove_dir(dest); default: - return ERR_UNKNOWN_CMD; + return ERR_SYNTAX; } return 0; } @@ -395,71 +446,72 @@ int IecParser :: get_command(const uint8_t *buffer, int len) switch(buffer[2]) { case 'P': if (len == 4) { - return exec->do_get_partition_info((int)buffer[3]); + // 255 asks for the current partition, which is what no parameter asks for + // as well, and is passed on as -1. Partition 0 is the system partition, a + // different question (SI-041). + int wanted = (int)buffer[3]; + return exec->do_get_partition_info((wanted == 255) ? -1 : wanted); } else if (len == 3) { - return exec->do_get_partition_info(0); + return exec->do_get_partition_info(-1); } return ERR_SYNTAX; default: - return ERR_UNKNOWN_CMD; + return ERR_SYNTAX; } return 0; } +// I[n][:] initialises the medium. UI is a different command, a reset that answers +// with the DOS version, and is handled by user_command(). int IecParser :: initialize_command(const uint8_t *buffer, int len) { - return exec->do_initialize(); + return exec->do_initialize_buffers(); } +// N[n][path]:name[,id] creates or formats a disk image (SI-071, SD parse_new()). The +// name needs a colon in front of it, and is split from the id at the first comma. int IecParser :: format_command(const uint8_t *buffer, int len) { mstring cmd((const char *)buffer, 1, len-1); - - const char *create[2]; - int n = cmd.split('=', create, 2);; - if (n == 2) { // create! - filename_t dest; - int err = parse_full_path(create[0], dest, NULL, false); - if (err) { - return err; - } - printf("Create disk image command: (%d) %s:%s, cmd: %s\n", dest.partition, dest.path.c_str(), dest.filename.c_str(), create[1]); - return 0; + if (!strchr(cmd.c_str(), ':')) { + return ERR_NO_NAME; } - - uint8_t name[24] = { 0xA0 }; - name[23] = 0; - uint8_t id1 = 0xA0, id2 = 0xA0; - for(int i=2;ido_format(name, id1, id2); + return exec->do_format(dest, id); } -int IecParser :: position_command(const uint8_t *buffer, int len) +// P+CHR$(ch)+CHR$(lo)[+CHR$(hi)[+CHR$(offset)]] for a relative file, and up to four +// position bytes for any other file (SD README). The record number and offset are read +// from the command as sent, len, because a 13 in the offset's place is the offset +// (SI-018, 1541 ROM $E23E). The position is read from the command without its terminator, +// stripped_len, so a position of fewer than four bytes from BASIC does not take the +// carriage return PRINT# appends as its next byte. +int IecParser :: position_command(const uint8_t *buffer, int len, int stripped_len) { uint32_t pos = 0; int chan = (int)buffer[1]; - len -= 2; buffer += 2; + len -= 2; stripped_len -= 2; buffer += 2; - if ((len < 1) || (len > 4)) { + if (len < 1) { return ERR_SYNTAX; } - for(int i=0; i= 2) ? (buffer[1] << 8) : 0); + int recoffset = (len >= 3) ? buffer[2] : 0; return exec->do_set_position(chan, pos, recnr, recoffset); } @@ -487,6 +539,9 @@ int IecParser :: rename_command(const uint8_t *buffer, int len) if (dest.has_wildcard) return ERR_ILLEGAL_NAME; + if ((uint8_t)dest.filename.c_str()[0] == 0xA0) { + return ERR_NO_NAME; // a name that starts with a shifted space (SI-148, SD parse_rename()) + } return exec->do_rename(src, dest); } @@ -510,6 +565,46 @@ int IecParser :: scratch_command(const uint8_t *buffer, int len) return exec->do_scratch(filenames, n); } +// L[n][path]:name toggles the lock of one file or directory (SI-076, HD 9-30). +int IecParser :: lock_command(const uint8_t *buffer, int len) +{ + mstring cmd((const char *)buffer, 1, len-1); + filename_t name; + int err = parse_full_path(cmd.c_str(), name, NULL, false); + if (err) { + return err; + } + return exec->do_lock(name); +} + +// M-R (SI-105). This drive has no drive memory, so M-R answers the number of bytes +// asked for, every one of them $00, which is no drive's signature (SI-112). M-W and M-E +// are refused: answering OK would tell a program that its drive code is in place. +int IecParser :: memory_command(const uint8_t *buffer, int len) +{ + switch(buffer[2]) { + case 'R': { + if (len < 5) { + return ERR_SYNTAX; + } + // No count reads one byte, as the 1541 ROM does at $CB24; a count of zero is + // 256; and a read stops at the end of the page. + int count = (len >= 6) ? buffer[5] : 1; + if (count == 0) { + count = 256; + } + if (count > 256 - buffer[3]) { + count = 256 - buffer[3]; + } + uint8_t zeros[256]; + memset(zeros, 0, sizeof(zeros)); + return exec->do_cmd_response(zeros, count); + } + default: + return ERR_SYNTAX; + } +} + static uint8_t bcdbyte(int a) { if(a > 99) @@ -582,9 +677,9 @@ int IecParser :: time_command(const uint8_t *buffer, int len) return exec->do_cmd_response(result, reslen); break; case 'W': - return 0; // just assume OK + return ERR_SYNTAX; // the clock belongs to the system, and answering OK would not set it (SI-120) } - return ERR_UNKNOWN_CMD; + return ERR_SYNTAX; } int IecParser :: user_command(const uint8_t *buffer, int len) @@ -602,12 +697,12 @@ int IecParser :: user_command(const uint8_t *buffer, int len) case 'A': n = parse_block_parameters(params, param_len, p, 4); if (n != 4) return ERR_SYNTAX; - return exec->do_block_read(p[0], p[1], p[2], p[3]); + return exec->do_block_read(p[0], p[1], p[2], p[3], false); case '2': case 'B': n = parse_block_parameters(params, param_len, p, 4); if (n != 4) return ERR_SYNTAX; - return exec->do_block_write(p[0], p[1], p[2], p[3]); + return exec->do_block_write(p[0], p[1], p[2], p[3], false); case '9': case 'I': // UI+ and UI- only select the serial bus timing. They are not a reset, so @@ -618,9 +713,19 @@ int IecParser :: user_command(const uint8_t *buffer, int len) return exec->do_initialize(); case ':': case 'J': - return exec->do_initialize(); + return exec->do_reset(false); + case 0xCA: // U+shifted J + return exec->do_reset(true); + case '0': + // U0>+CHR$(d) changes the device number (SI-100). CBM DOS takes the > from its + // low five bits, as sd2iec does. The other U0 forms select serial timing and + // retries this drive does not have. + if ((len == 4) && ((params[0] & 0x1F) == 0x1E) && (params[1] >= 8) && (params[1] <= 30)) { + return exec->do_set_device_number(params[1]); + } + return ERR_SYNTAX; default: - return ERR_UNKNOWN_CMD; + return ERR_SYNTAX; } return 0; } @@ -631,11 +736,44 @@ int IecParser :: extended_command(const uint8_t *buffer, int len) if (cmd == "PWD") { return exec->do_pwd_command(); } - return ERR_UNKNOWN_CMD; + return ERR_SYNTAX; +} + +// BASIC's PRINT# ends a command with a carriage return, and CBM DOS drops it before +// reading the command: the 1541 ROM does that at $C2B3. Change Partition in its +// binary form is the exception, because its partition byte is not optional, so a +// byte that happens to be a carriage return is that parameter. CMD DOS has the same +// ambiguity wherever the last parameter is optional, and its manual answers it by +// telling programmers to send the terminator themselves when they want partition 13. +// +// BASIC's PRINT# to a logical file number of 128 or more ends a line with a carriage +// return and a line feed (C64 ROM $AAD7), and both are dropped. The ROM also ends a +// command at any carriage return second to last (SI-016), but that would cut a binary +// parameter of 13 short, which the reporter of #877 asked not to reproduce. +static int strip_terminator(const uint8_t *buffer, int len) +{ + if ((len > 1) && (buffer[0] == 'C') && (buffer[1] == 0xD0)) { + return len; + } + if (len && (buffer[len - 1] == 0x0D)) { + return len - 1; + } + if ((len > 2) && (buffer[len - 2] == 0x0D) && (buffer[len - 1] == 0x0A)) { + return len - 2; + } + return len; } int IecParser :: execute_command(const uint8_t *buffer, int len) { + if (len >= CBMDOS_COMMAND_BUFFER_SIZE) { + return ERR_CMD_TOO_LONG; // SI-022: refused, not executed cut short + } + const int original_len = len; + len = strip_terminator(buffer, len); + if (len <= 0) { // a lone carriage return: the ROM at $C175 and sd2iec answer 31 + return ERR_UNKNOWN_CMD; + } switch(buffer[0]) { case 'B': return block_command(buffer, len); case 'C': @@ -649,20 +787,30 @@ int IecParser :: execute_command(const uint8_t *buffer, int len) break; case 'G': return get_command(buffer, len); case 'I': return initialize_command(buffer, len); - case 'M': return dir_command(buffer, len); + case 'M': + if (buffer[1] == '-') { + return memory_command(buffer, len); + } + return dir_command(buffer, len); case 'N': return format_command(buffer, len); - case 'P': return position_command(buffer, len); + case 'P': return position_command(buffer, original_len, len); // its last byte is data (SI-018) case 'R': if (buffer[1] == 'D') { return dir_command(buffer, len); } return rename_command(buffer, len); - case 'S': return scratch_command(buffer, len); + case 'S': + if ((len == 3) && (buffer[1] == '-')) { + return ERR_UNKNOWN_CMD; // S-8, S-9 and S-D swap device numbers, which this drive does not do (SD parse_doscommand()) + } + return scratch_command(buffer, len); case 'T': return time_command(buffer, len); case 'U': return user_command(buffer, len); case 'X': case 'E': return extended_command(buffer, len); + case 'L': + return lock_command(buffer, len); } return ERR_UNKNOWN_CMD; } @@ -678,8 +826,9 @@ const char *cbmdos_time(uint32_t dt, char *buf, bool longfmt) s = (dt & 31) << 1; int h12 = (h % 12); if (h12 == 0) h12 = 12; if (longfmt) { - // 07/27/19 03.44 PM - sprintf(buf, "%02d/%02d/%02d %02d.%02d %cM", M, D, y % 100, h12, m, (h >= 12)?'P':'A'); + // 07/27/19 03.44 PM. The three spaces are what a CMD HD prints between the date + // and the time in a long listing, measured on HD 9-22 and matching SD createentry(). + sprintf(buf, "%02d/%02d/%02d %02d.%02d %cM", M, D, y % 100, h12, m, (h >= 12)?'P':'A'); } else { // 07/27 03.44 P sprintf(buf, "%02d/%02d %02d.%02d %c", M, D, h12, m, (h >= 12)?'P':'A'); diff --git a/software/io/iec/cbmdos_parser.h b/software/io/iec/cbmdos_parser.h index a3e997f14..bbb6b3384 100644 --- a/software/io/iec/cbmdos_parser.h +++ b/software/io/iec/cbmdos_parser.h @@ -49,9 +49,10 @@ typedef struct { uint32_t min_datetime; uint32_t max_datetime; uint8_t filetypes; // P,S,U,R, B/D + uint8_t partition_types; // one bit per CMD partition type; zero means all of them } dir_options_t; -const dir_options_t c_dir_options_init = { e_stream_file, e_stamp_none, 0, 0, 0x00 }; +const dir_options_t c_dir_options_init = { e_stream_file, e_stamp_none, 0, 0, 0x00, 0x00 }; typedef struct { filename_t file; @@ -62,17 +63,27 @@ typedef struct { uint16_t record_size; } open_t; -#define ERR_SYNTAX 30 -#define ERR_ILLEGAL_CHARS 31 -#define ERR_ILLEGAL_NAME 32 -#define ERR_UNKNOWN_CMD 33 +// The syntax errors of CBM and CMD DOS (HD B-2, 1541 User's Guide). +#define ERR_SYNTAX 30 // the command was recognised, its arguments were not +#define ERR_UNKNOWN_CMD 31 // the first character is not a command letter +#define ERR_CMD_TOO_LONG 32 // the command filled the command buffer +#define ERR_ILLEGAL_NAME 33 // a wildcard or a character a name cannot carry +#define ERR_NO_NAME 34 // no name, or a colon with nothing after it +#define ERR_REPLACE_TYPE 64 // FILE TYPE MISMATCH: @ names nothing that can be replaced + +// The command buffer holds 254 bytes, as on the CMD HD (HD 4-6) and on sd2iec's uIEC +// (CONFIG_COMMAND_BUFFER_SIZE). A command that fills it is refused, because whether +// anything followed cannot be told (SI-021, SI-022). +#define CBMDOS_COMMAND_BUFFER_SIZE 254 class IecCommandExecuter { public: - virtual int do_block_read(int chan, int part, int track, int sector) { return 0; } - virtual int do_block_write(int chan, int part, int track, int sector) { return 0; } - virtual int do_block_allocate(int chan, int part, int track, int sector, bool allocate) { return 0; } + // length_byte: B-R and B-W, which use the first byte of the block as a length (SI-094); + // U1 and U2 do not. + virtual int do_block_read(int chan, int part, int track, int sector, bool length_byte) { return 0; } + virtual int do_block_write(int chan, int part, int track, int sector, bool length_byte) { return 0; } + virtual int do_block_allocate(int part, int track, int sector, bool allocate) { return 0; } virtual int do_buffer_position(int chan, int pos) { return 0; } virtual int do_set_current_partition(int part) { return 0; } virtual int do_change_dir(filename_t& dest) { return 0; } @@ -80,13 +91,19 @@ class IecCommandExecuter virtual int do_remove_dir(filename_t& dest) { return 0; } virtual int do_copy(filename_t& dest, filename_t sources[], int n) { return 0; } virtual int do_initialize() { return 0; } - virtual int do_format(uint8_t *name, uint8_t id1, uint8_t id2) { return 0; } + virtual int do_initialize_buffers() { return 0; } + // UJ closes the data channels; cold, for U+shifted J, also returns every partition to + // its root and selects the default one (SI-103). + virtual int do_reset(bool cold) { return 0; } + virtual int do_format(filename_t& dest, const char *id) { return 0; } virtual int do_rename(filename_t &src, filename_t &dest) { return 0; } virtual int do_scratch(filename_t filenames[], int n) { return 0; } virtual int do_cmd_response(uint8_t *data, int len) { return 0; } virtual int do_set_position(int chan, uint32_t pos, int recnr, int recoffset) { return 0; } virtual int do_pwd_command() { return 0; } virtual int do_get_partition_info(int part) { return 0; } + virtual int do_set_device_number(int dev) { return 0; } + virtual int do_lock(filename_t& name) { return 0; } // L: toggles the lock of one entry }; class IecParser @@ -99,13 +116,15 @@ class IecParser int copy_command(const uint8_t *buffer, int len); int initialize_command(const uint8_t *buffer, int len); int format_command(const uint8_t *buffer, int len); - int position_command(const uint8_t *buffer, int len); + int position_command(const uint8_t *buffer, int len, int stripped_len); int rename_command(const uint8_t *buffer, int len); int scratch_command(const uint8_t *buffer, int len); int time_command(const uint8_t *buffer, int len); int user_command(const uint8_t *buffer, int len); int extended_command(const uint8_t *buffer, int len); int get_command(const uint8_t *buffer, int len); + int memory_command(const uint8_t *buffer, int len); + int lock_command(const uint8_t *buffer, int len); public: IecParser(IecCommandExecuter *e) : exec(e) { } @@ -115,6 +134,7 @@ class IecParser int parse_open(const char *buf, open_t& fn); int parse_full_path(const char *buf, filename_t& name, bool *replace, bool path_only); int parse_dir_option(const char *buf, dir_options_t &opt); +int parse_partition_option(const char *buf, dir_options_t &opt); const char *cbmdos_time(uint32_t dt, char *buf, bool longfmt); const uint32_t make_fat_time(int y, int M, int d, int h, int m, int s); diff --git a/software/io/iec/cbmdos_parser_test.cc b/software/io/iec/cbmdos_parser_test.cc index 57f6b0652..4122f9929 100644 --- a/software/io/iec/cbmdos_parser_test.cc +++ b/software/io/iec/cbmdos_parser_test.cc @@ -4,6 +4,7 @@ #include "cbmdos_parser.h" #include "pattern.h" +#include "iec_log.h" typedef struct { int partition; @@ -18,10 +19,11 @@ typedef struct { uint32_t min_time; uint32_t max_time; uint8_t filetypes; + uint8_t partition_types; } open_result_t; const open_result_t c_open_result_init = { 0, "", "", false, false, e_any, e_not_set, - e_stream_file, e_stamp_none, 0x0, 0x0, 0x00 }; + e_stream_file, e_stamp_none, 0x0, 0x0, 0x00, 0x00 }; #include "cbmdos_stubs.cc" IecCommandExecuterStubs exec; @@ -52,6 +54,7 @@ void print_open(open_t& o) const char *fmt[] = { "None", "Short", "Long "}; printf(" Stamp Format: %s\n", fmt[(int)o.dir_opt.timefmt] ); printf(" File Types: %02x\n", o.dir_opt.filetypes); + printf(" Partition Types: %02x\n", o.dir_opt.partition_types); if (o.dir_opt.min_datetime) { printf(" From Time: %s (%08x)\n", cbmdos_time(o.dir_opt.min_datetime, buf, true), o.dir_opt.min_datetime); } @@ -80,6 +83,7 @@ void d_parse_open(const char *buf, open_t& o, int expected_retval = 0, open_resu ok &= (o.dir_opt.stream == result.stream); ok &= (o.dir_opt.timefmt == result.timefmt); ok &= (o.dir_opt.filetypes == result.filetypes); + ok &= (o.dir_opt.partition_types == result.partition_types); ok &= (o.dir_opt.min_datetime == result.min_time); ok &= (o.dir_opt.max_datetime == result.max_time); } @@ -158,8 +162,15 @@ void test_block_command_forms(void) test_dispatch("U1:2, 0 ,18,\x1D""0", 14, 0, "block read", 2, 0, 18, 0); test_dispatch("B-R:2,0,18,1", 12, 0, "block read", 2, 0, 18, 1); test_dispatch("B-W: 2 0 18 2 ", 17, 0, "block write", 2, 0, 18, 2); - test_dispatch("B-A:2,0,16,3", 12, 0, "block allocate", 2, 0, 16, 3); - test_dispatch("B-F:2,0,16,4", 12, 0, "block free", 2, 0, 16, 4); + // Allocate and free take three numbers, the partition, the track and the sector, + // as both the 1541 and the CMD manuals write them. This is what CHECK DISK on + // the 1541 TEST/DEMO disk sends, as PRINT#15,"B-A:"D$;T;S. A fourth number is + // ignored, which is what the drive does with a parameter it never reads. + test_dispatch("B-A:0,17,1", 10, 0, "block allocate", 0, 17, 1); + test_dispatch("B-F:0,17,1", 10, 0, "block free", 0, 17, 1); + test_dispatch("B-A: 0 17 1 ", 14, 0, "block allocate", 0, 17, 1); + test_dispatch("B-A:2,0,16,3", 12, 0, "block allocate", 2, 0, 16); + test_dispatch("B-A:0,17", 8, ERR_SYNTAX, NULL); test_dispatch("B-P: 2 0 ", 10, 0, "buffer position", 2, 0); // U1 and UA are the same command, and so are U2 and UB. @@ -181,13 +192,18 @@ void test_block_command_forms(void) // serial bus timing, so they must not reset anything. test_dispatch("UI", 2, 73, "initialize"); test_dispatch("U9", 2, 73, "initialize"); - test_dispatch("UJ", 2, 73, "initialize"); - test_dispatch("U:", 2, 73, "initialize"); + // UJ and U: close the data channels; U+shifted J also returns every partition to its + // root (SI-103). Both answer with the DOS version. + test_dispatch("UJ", 2, 73, "reset", 0); + test_dispatch("U:", 2, 73, "reset", 0); + test_dispatch("U\xCA", 2, 73, "reset", 1); + test_dispatch("UJ\r", 3, 73, "reset", 0); test_dispatch("UI+", 3, 0, NULL); test_dispatch("UI-", 3, 0, NULL); test_dispatch("U9+", 3, 0, NULL); - // U3 to U8 jump into a drive buffer, which has no equivalent here. - test_dispatch("U3:2,0,18,0", 11, ERR_UNKNOWN_CMD, NULL); + // U3 to U8 jump into a drive buffer, which has no equivalent here. U is a command + // letter, so only the sub-command is unknown: 30, not 31 (SI-104). + test_dispatch("U3:2,0,18,0", 11, 30, NULL); // The position command takes the secondary address either on its own or with 96 // added to it, which is the form the manuals document. Three parameter bytes are @@ -195,10 +211,431 @@ void test_block_command_forms(void) // which of the two it uses from the state of the channel. test_dispatch("P\x02\x01\x00\x01", 5, 0, "set position", 2, 0x10001, 1, 1); test_dispatch("P\x62\x01\x00\x01", 5, 0, "set position", 0x62, 0x10001, 1, 1); + // A record number without an offset, sent without a terminator, as a machine language + // caller sends it: the 1541 ROM takes the record from both bytes. + test_dispatch("P\x62\x05\x01", 4, 0, "set position", 0x62, 0x105, 0x105, 0); + // The documented BASIC form with one position byte: the carriage return behind it is + // not the next byte of the position (GSD "Positioning (seeking) Within a File"). A + // relative file would read it as the record's high byte, as the ROM does. + test_dispatch("P\x02\x64\r", 4, 0, "set position", 2, 100, 0xD64, 0); +} + +// What happens to the carriage return BASIC's PRINT# appends, and to the commands +// whose last parameter can be that same byte. CBM DOS drops one carriage return +// from the end of the command before reading it; the 1541 ROM does that at $C2B3. +// Where the last parameter is optional this leaves an ambiguity, and the CMD hard +// disk manual answers it for G-P: "To avoid problems with reading information from +// Partition 13, the G-P command should always be sent with a trailing carriage +// return (CHR$(13))." Change Partition in its binary form is the one command whose +// last parameter is mandatory, so it keeps a parameter of 13. +void test_command_terminator(void) +{ + // A lone carriage return is not a command the drive knows: 31, as the ROM answers. + test_dispatch("\r", 1, 31, NULL); + + // C selects a partition by a byte, so 13 is a partition number whether + // or not a terminator followed it. This is the regression reported against the + // first version of this fix. + test_dispatch("C\xD0\x0D", 3, 0, "select partition", 13); + test_dispatch("C\xD0\x0D\x0D", 4, 0, "select partition", 13); + test_dispatch("C\xD0\x04", 3, 0, "select partition", 4); + test_dispatch("C\xD0\x04\x0D", 4, 0, "select partition", 4); + test_dispatch("C\xD0", 2, ERR_SYNTAX, NULL); + // CPn takes the same number in ASCII, where no byte is ambiguous. + test_dispatch("CP4", 3, 0, "select partition", 4); + test_dispatch("CP13\r", 5, 0, "select partition", 13); + // Partition 0 means the one already selected, which is also what no number asks + // for. + test_dispatch("CP\r", 3, 0, "select partition", 0); + + // G-P without a number, and with 255, both ask about the current partition, which + // the parser passes on as -1. 0 asks about the system partition, a different + // question (SI-041). + test_dispatch("G-P", 3, 0, "partition info", -1); + test_dispatch("G-P\r", 4, 0, "partition info", -1); + test_dispatch("G-P\xFF", 4, 0, "partition info", -1); + test_dispatch("G-P\x00", 4, 0, "partition info", 0); + test_dispatch("G-P\x04", 4, 0, "partition info", 4); + test_dispatch("G-P\x04\r", 5, 0, "partition info", 4); + // Partition 13 needs the terminator the manual asks for, exactly as on a CMD + // drive. + test_dispatch("G-P\x0D\x0D", 5, 0, "partition info", 13); + + // The position command is exempt from the terminator rule, because its last + // parameter byte is data (SI-018, SD parse_position() restores the length from + // before the strip): an offset of 13 arrives with or without a terminator, and a + // terminator behind the parameters is ignored. + test_dispatch("P\x02\x0A\x00\x0D\x0D", 6, 0, "set position", 2, 0xD000A, 10, 13); + test_dispatch("P\x02\x0A\x00\x0D", 5, 0, "set position", 2, 0xA, 10, 13); + + // A command whose parameters are text loses the terminator rather than reading + // it as a value. + test_dispatch("B-P:2,13\r", 9, 0, "buffer position", 2, 13); +} + +// The error numbers of doc/softiec_compatibility_spec.md SI-030, one case per return +// site whose number differs from 30. The numbers are written out rather than taken +// from the constants, so a constant with the wrong value cannot pass. +// 30 the command was recognised and its arguments were not +// 31 the first character is not a command letter +// 33 a wildcard or a character a name cannot carry +// 34 no name, or a colon with nothing after it +// Like test_dispatch, and also compares the names the command carried, as the stub +// recorded them. +void test_dispatch_text(const char *cmd, int len, int exp_retval, const char *what, + const char *text, int a = 0) +{ + last_stub_call.command = NULL; + last_stub_call.text[0] = 0; + int retval = parser.execute_command((const uint8_t *)cmd, len); + bool ok = (retval == exp_retval) && last_stub_call.command && + (strcmp(last_stub_call.command, what) == 0) && + (strcmp(last_stub_call.text, text) == 0) && (last_stub_call.a == a); + if (ok) { + printf("Dispatch '%s' => OK!\n", cmd); + return; + } + printf("Dispatch '%s' returned %d (expected %d) and called %s(%d,'%s'), expected %s(%d,'%s')\n", + cmd, retval, exp_retval, + last_stub_call.command ? last_stub_call.command : "nothing", + last_stub_call.a, last_stub_call.text, what, a, text); + failures++; +} + +// The commands phase 3 of the specification adds, and the routing that has to find +// them before it falls through to rename and scratch. +void test_added_commands(void) +{ + // S-8, S-9 and S-D swap device numbers, which this drive does not do; they are not a + // scratch of a file called -8 (SD parse_doscommand()). + test_dispatch("S-8", 3, 31, NULL); + test_dispatch("S-D\r", 4, 31, NULL); + // SI-100: U0> followed by the device number as a byte. + test_dispatch("U0>\x0C", 4, 0, "device number", 12); + test_dispatch("U0>\x1E\r", 5, 0, "device number", 30); + test_dispatch("U0>\x0D\r", 5, 0, "device number", 13); + test_dispatch("U0>\x07", 4, 30, NULL); + test_dispatch("U0>\x1F", 4, 30, NULL); + test_dispatch("U0", 2, 30, NULL); + test_dispatch("U0+", 3, 30, NULL); + + // SI-105 and SI-112: M-R answers the number of bytes asked for, every one of them + // zero; no count means one, a count of zero means 256, and it stops at the end of + // the page. M-W and M-E are refused, because this drive runs no drive code. + test_dispatch("M-R\xA4\xFE\x02", 6, 0, "command response", 2); + test_dispatch("M-R\x02\x00\x02\r", 7, 0, "command response", 2); + test_dispatch("M-R\xA4\xFE", 5, 0, "command response", 1); + test_dispatch("M-R\x00\xFE\x00", 6, 0, "command response", 256); + test_dispatch("M-R\xF0\x00\x20", 6, 0, "command response", 16); + test_dispatch("M-R\xA4", 4, 30, NULL); + test_dispatch("M-W\x00\x05\x01\xEA", 7, 30, NULL); + test_dispatch("M-E\x00\x05", 5, 30, NULL); + test_dispatch("M-X", 3, 30, NULL); + // SI-120: the clock belongs to the system, so T-W answers 30 rather than an OK that + // would set nothing. + test_dispatch("T-WI2026-09-12T13:02:03", 23, 30, NULL); + test_dispatch("MD:DIR", 6, 0, NULL); // still a directory command +} + +// SI-021, SI-022 and SI-016: the command buffer holds 254 bytes, a command that fills +// it answers 32 and is not executed, and a carriage return second to last ends the +// command, as the 1541 ROM does at $C2B3. +void test_command_length_and_terminator(void) +{ + char cmd[300]; + memset(cmd, ' ', sizeof(cmd)); + memcpy(cmd, "B-P:2,144", 9); + test_dispatch(cmd, 253, 0, "buffer position", 2, 144); + test_dispatch(cmd, 254, 32, NULL); + test_dispatch(cmd, 255, 32, NULL); + + test_dispatch("B-P:2,144\r\n", 11, 0, "buffer position", 2, 144); + // Only a carriage return and a line feed end a command early: a 13 second to last is a + // binary parameter, here the high byte of an M-R address, and the count behind it + // stays. + test_dispatch("M-R\x00\x0D\x05", 6, 0, "command response", 5); +} + +// SI-060 and SI-063: MD requires a colon and refuses a name that is a shifted space; +// RD takes a name behind a colon and no path. +void test_md_rd_grammar(void) +{ + test_command(34, (const uint8_t *)"MD NOCOLON", 10); + test_command(34, (const uint8_t *)"MD:\xA0", 4); + test_command( 0, (const uint8_t *)"MD//SUB/:NAME", 13); + test_command(34, (const uint8_t *)"RD/PROBEDIR", 11); + test_command(34, (const uint8_t *)"RD//SUB/:NAME", 13); + test_command(34, (const uint8_t *)"RDNAME", 6); + test_command( 0, (const uint8_t *)"RD:NAME", 7); + test_command( 0, (const uint8_t *)"RD12:NAME\r", 10); +} + +// SI-147 and SI-142: the PETSCII to host name mapping shared with sd2iec's extension mode +// 5. A trailing run of shifted spaces is padding and is dropped; a shifted space inside a +// name is escaped; * and ? are escaped; and the braces a type extension gets stay inside the +// buffer. This suite is +// also built with -funsigned-char (target/pc/linux/parse_unsigned), because the shifted +// space rule depended on the signedness of char. +static void check_fat_name(const char *what, const char *pet, int maxlen, const char *expected) +{ + char fat[64]; + memset(fat, 'X', sizeof(fat)); + fat[sizeof(fat) - 1] = 0; + petscii_to_fat(pet, fat, maxlen); + if (strcmp(fat, expected) == 0) { + printf("Name %s => OK!\n", what); + return; + } + printf("Name %s mapped to '%s', expected '%s' (char is %s)\n", what, fat, expected, + ((char)0xA0 < 0) ? "signed" : "unsigned"); + failures++; +} + +void test_name_mapping(void) +{ + // Each name is followed by a byte that is not zero, so a test that reads past the + // terminator sees something other than the end of the string. + const char trailing[] = { 'A', 'B', (char)0xA0, 0, 'Z' }; + check_fat_name("AB+$A0", trailing, 51, "AB"); + const char trailing_run[] = { 'A', (char)0xA0, (char)0xA0, 0, 'Z' }; + check_fat_name("A+$A0$A0", trailing_run, 51, "A"); + const char interior[] = { 'A', (char)0xA0, 'B', 0, 'Z' }; + check_fat_name("A+$A0+B", interior, 51, "A{A0}B"); + const char interior_run[] = { 'A', (char)0xA0, (char)0xA0, 'B', 0, 'Z' }; + check_fat_name("A+$A0$A0+B", interior_run, 51, "A{A0A0}B"); + check_fat_name("star", "FOO*", 51, "FOO{2A}"); + check_fat_name("question mark", "WHAT?", 51, "WHAT{3F}"); + // A name that fills the buffer and ends in .PRG gets no braces, which would not fit: + // with a 48 byte buffer, 46 characters and the terminator are all there is room for. + check_fat_name("braces bound", "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOP.PRG", 48, + "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOP.PRG"); + check_fat_name("braces", "GAME.PRG", 48, "GAME.PRG{}"); +} + +// SI-076: L toggles the lock of one entry. +void test_lock_command(void) +{ + test_dispatch_text("L:TEST", 6, 0, "lock", "-1||TEST"); + test_dispatch_text("L1//:TEST\r", 10, 0, "lock", "1|//|TEST"); + test_dispatch("L:", 2, 34, NULL); +} + +// B-P positions within the 256 byte buffer; a third number is ignored, as the ROM ignores it. +// SI-094: B-R and B-W use the first byte of the block as a length, U1 and U2 do not. +void test_block_positions_and_lengths(void) +{ + test_dispatch("B-P 9 4 1", 9, 0, "buffer position", 9, 4); + test_dispatch("B-P:2,144", 9, 0, "buffer position", 2, 144); + test_dispatch("B-R:2,0,18,1", 12, 0, "block read", 2, 0, 18, 1); + test_dispatch("U1:2,0,18,1", 11, 0, "block read", 2, 0, 18, 1); + if (!last_stub_call.text[0] || strcmp(last_stub_call.text, "no length")) { + printf("U1 was not dispatched as a read without the length byte: '%s'\n", last_stub_call.text); + failures++; + } + test_dispatch("B-R:2,0,18,1", 12, 0, "block read", 2, 0, 18, 1); + if (strcmp(last_stub_call.text, "length")) { + printf("B-R was not dispatched as a read with the length byte: '%s'\n", last_stub_call.text); + failures++; + } + test_dispatch("B-W:2,0,18,1", 12, 0, "block write", 2, 0, 18, 1); + if (strcmp(last_stub_call.text, "length")) { + printf("B-W was not dispatched as a write with the length byte: '%s'\n", last_stub_call.text); + failures++; + } +} + +void test_error_codes(void) +{ + // SI-031: not a command letter. CHR$(0) and A are what the reporter measured on + // #877; Z and Q never become commands. + test_dispatch("\0", 1, 31, NULL); + test_dispatch("A", 1, 31, NULL); + test_dispatch("Z", 1, 31, NULL); + test_dispatch("Q\r", 2, 31, NULL); + // A colon with nothing after it. + test_dispatch("C99:EMPTY=", 10, 34, NULL); + test_dispatch("R:NEW=", 6, 34, NULL); + // A wildcard in the target of a copy or a rename. + test_dispatch("C:NEW*=OLD", 10, 33, NULL); + test_dispatch("R:NEW?=OLD", 10, 33, NULL); + // A command letter followed by a sub-command that does not exist. + test_dispatch("B-X:1,2,3", 9, 30, NULL); + test_dispatch("B-E:2,0,18,0", 12, 30, NULL); // SI-095: no drive memory to run code in + test_dispatch("MX", 2, 30, NULL); + test_dispatch("G-X", 3, 30, NULL); + test_dispatch("UZ", 2, 30, NULL); + test_dispatch("T-X", 3, 30, NULL); + test_dispatch("XFOO", 4, 30, NULL); + test_dispatch("EFOO", 4, 30, NULL); + + // SI-053: I is a command of its own. It releases the channels a program left open and + // answers OK; UI is the reset that answers with the DOS version. + test_dispatch("I", 1, 0, "initialize buffers"); + test_dispatch("I0:\r", 4, 0, "initialize buffers"); + test_dispatch("UI", 2, 73, "initialize"); + + // An open name carrying a character a name cannot carry. + open_t o; + d_parse_open("FILE=X", o, 33); + d_parse_open("@345:", o, 34); +} + +// The byte formatter of the Software IEC failure log. It takes a length and +// must never read the payload as a string, because an IEC payload can carry an +// embedded zero, a carriage return that is a parameter rather than a terminator, and +// shifted PETSCII bytes above 0x7F. +void test_log_render(const char *what, const uint8_t *data, int len, const char *exp_text) +{ + char txt[SOFTIEC_LOG_TEXT_SIZE]; + int txt_len = softiec_log_text(data, len, txt, sizeof(txt)); + if ((strcmp(txt, exp_text) == 0) && (txt_len == (int)strlen(exp_text))) { + printf("Log %s => OK!\n", what); + return; + } + printf("Log %s rendered \"%s\", expected \"%s\"\n", what, txt, exp_text); + failures++; +} + +// A rendering that does not fit has to say so rather than look like a short payload. +void test_log_truncation(void) +{ + const uint8_t data[] = { 0x41, 0x42, 0x43, 0x44 }; + char txt[6]; + softiec_log_text(data, 4, txt, sizeof(txt)); + if (strcmp(txt, "ABC..") == 0) { + printf("Log truncation => OK!\n"); + return; + } + printf("Log truncation rendered \"%s\", expected \"ABC..\"\n", txt); + failures++; +} + +void test_log_formatters(void) +{ + const uint8_t empty[1] = { 0 }; + test_log_render("empty payload", empty, 0, ""); + + // The command that started #881: C, shifted P, and partition 13 as a byte. + const uint8_t change_partition[] = { 'C', 0xD0, 0x0D }; + test_log_render("binary change partition", change_partition, 3, "C\\xD0\\r"); + + // A text command with the carriage return PRINT# appends behind it. + const uint8_t text_command[] = { 'G', '-', 'P', 0x0D }; + test_log_render("text command with terminator", text_command, 4, "G-P\\r"); + + // An embedded zero is a payload byte here, not the end of the payload. + const uint8_t with_zero[] = { 'A', 0x00, 'B' }; + test_log_render("embedded zero", with_zero, 3, "A\\0B"); + + // Quotes and backslashes have to survive the quoted rendering. + const uint8_t quoting[] = { '"', '\\', 0x0A }; + test_log_render("quoting", quoting, 3, "\\\"\\\\\\n"); + + test_log_truncation(); +} + +// The recursive pattern_match() the iterative one replaced, as the reference its results +// are compared with, with the one defect corrected: at the end of the fixed string only +// stars may be left of the pattern, where the recursion accepted anything after a star. +static bool reference_pattern_match(const char *p, const char *f, bool case_sensitive) +{ + do { + if (!(*f)) { + while (*p == '*') { + p++; + } + return (*p == '\0'); + } + if (!(*p)) { + return false; + } + if (*p == '*') { + p++; + if (!(*p)) { + return true; + } + while (*f) { + if (reference_pattern_match(p, f, case_sensitive)) { + return true; + } + f++; + } + return false; + } else if (*p != '?') { + char cp = case_sensitive ? *p : toupper(*p); + char cf = case_sensitive ? *f : toupper(*f); + if (cf != cp) { + return false; + } + } + f++; + p++; + } while (true); +} + +static int build_string(char *out, const char *alphabet, int base, int length, int index) +{ + for (int i = 0; i < length; i++) { + out[i] = alphabet[index % base]; + index /= base; + } + out[length] = 0; + return length; +} + +// Every pattern of up to five characters from A, b, * and ? against every name of up to +// five characters from a and B, both case modes, gives the reference's answer; and a +// pattern of forty stars that does not match returns at once, where the recursion took +// time exponential in the number of stars. +void test_pattern_match(void) +{ + char pattern[8], fixed[8]; + int compared = 0; + for (int plen = 0; plen <= 5; plen++) { + int pcount = 1; + for (int i = 0; i < plen; i++) pcount *= 4; + for (int pi = 0; pi < pcount; pi++) { + build_string(pattern, "Ab*?", 4, plen, pi); + for (int flen = 0; flen <= 5; flen++) { + for (int fi = 0; fi < (1 << flen); fi++) { + build_string(fixed, "aB", 2, flen, fi); + for (int cs = 0; cs < 2; cs++) { + bool want = reference_pattern_match(pattern, fixed, cs); + if (pattern_match(pattern, fixed, cs) != want) { + printf("pattern_match('%s', '%s', %d) differs from the reference, which says %d\n", + pattern, fixed, cs, want); + failures++; + return; + } + compared++; + } + } + } + } + } + // The defect the recursion had: a name that ends where the pattern has a star. + if (pattern_match("FOO*X", "FOO", false) || !pattern_match("FOO*", "FOO", false) || + pattern_match("*.D64", "", false) || !pattern_match("*", "", false)) { + printf("FOO*X matched FOO, FOO* did not match FOO, *.D64 matched nothing or * did not\n"); + failures++; + return; + } + char stars[64]; + memset(stars, '*', 40); + strcpy(stars + 40, "Q"); + if (pattern_match(stars, "ABCDEFGHIJKLMNOP", false) || !pattern_match(stars, "ABCDEFGHIJKLMNOQ", false)) { + printf("forty stars and Q matched wrongly\n"); + failures++; + return; + } + printf("Pattern match: %d comparisons with the reference, forty stars => OK!\n", compared); } int main(int argc, const char *argv[]) { + test_log_formatters(); + test_pattern_match(); + open_t o; d_parse_open("JUSTFILE", o, 0, { -1, "", "JUSTFILE", false, false, e_any, e_not_set, @@ -252,7 +689,7 @@ int main(int argc, const char *argv[]) { -1, "//FROMROOT/DEEPER", "BLAH", false, false, e_seq, e_read, e_stream_file, e_stamp_none, 0x0, 0x0, 0x00}); - d_parse_open("@345:", o, ERR_ILLEGAL_NAME); + d_parse_open("@345:", o, 34); // no name after the colon d_parse_open(",", o, ERR_SYNTAX); @@ -339,6 +776,43 @@ int main(int argc, const char *argv[]) { 69, "", "", false, false, e_any, e_not_set, e_stream_partitions, e_stamp_none, 0x0, 0x00, 0x00 }); + // The partition directory filters by partition type, where a directory of files + // takes its own options. LOAD"$=P:*=tp" with tp one of N, 4, 7, 8 or C. + d_parse_open("$=P:*=N", o, 0, + { -1, "", "*", true, false, e_any, e_not_set, + e_stream_partitions, e_stamp_none, 0x0, 0x00, 0x00, 0x02 }); + + d_parse_open("$=P:*=4", o, 0, + { -1, "", "*", true, false, e_any, e_not_set, + e_stream_partitions, e_stamp_none, 0x0, 0x00, 0x00, 0x04 }); + + d_parse_open("$=P:*=7", o, 0, + { -1, "", "*", true, false, e_any, e_not_set, + e_stream_partitions, e_stamp_none, 0x0, 0x00, 0x00, 0x08 }); + + d_parse_open("$=P:*=8", o, 0, + { -1, "", "*", true, false, e_any, e_not_set, + e_stream_partitions, e_stamp_none, 0x0, 0x00, 0x00, 0x10 }); + + d_parse_open("$=P:*=C", o, 0, + { -1, "", "*", true, false, e_any, e_not_set, + e_stream_partitions, e_stamp_none, 0x0, 0x00, 0x00, 0x20 }); + + d_parse_open("$=P:*=4,8", o, 0, + { -1, "", "*", true, false, e_any, e_not_set, + e_stream_partitions, e_stamp_none, 0x0, 0x00, 0x00, 0x14 }); + + d_parse_open("$=P:*=X", o, ERR_SYNTAX); + + // SI-134: H is not a file type but asks for hidden files, which are listed anyway, so + // it must not set a type bit: $:*=H lists what $:* lists. + d_parse_open("$:*=H", o, 0, + { -1, "", "*", true, false, e_any, e_not_set, + e_stream_dir, e_stamp_none, 0x0, 0x00, 0x00 }); + d_parse_open("$:*=P,H", o, 0, + { -1, "", "*", true, false, e_any, e_not_set, + e_stream_dir, e_stamp_none, 0x0, 0x00, 0x02 }); + d_parse_open("$//", o, 0, { -1, "//", "", false, false, e_any, e_not_set, e_stream_dir, e_stamp_none, 0x0, 0x00, 0x00 }); @@ -369,7 +843,15 @@ int main(int argc, const char *argv[]) test_command( 0, (const uint8_t *)"U2 2 0 18 4\r", 12); test_command( 0, (const uint8_t *)"B-P 2 234\r", 10); test_block_command_forms(); - test_command(32, (const uint8_t *)"C99:EMPTY=", 10); + test_command_terminator(); + test_error_codes(); + test_added_commands(); + test_command_length_and_terminator(); + test_md_rd_grammar(); + test_name_mapping(); + test_lock_command(); + test_block_positions_and_lengths(); + test_command(34, (const uint8_t *)"C99:EMPTY=", 10); test_command( 0, (const uint8_t *)"C1:FCOPY=3:FCOPY", 16); test_command( 0, (const uint8_t *)"C:FULLSTATS=STAT1,3:STAT3", 25); test_command( 0, (const uint8_t *)"C2:MCOPY=1/COPIERS/:MCOPY", 25); @@ -383,39 +865,39 @@ int main(int argc, const char *argv[]) test_command( 0, (const uint8_t *)"P\x02\xC8\0", 4); test_command( 0, (const uint8_t *)"P\x02\x2C\x01\0", 5); test_command( 0, (const uint8_t *)"P\x02\x90\x01\0\0", 6); - // A position is at most four bytes wide, so five parameter bytes is a syntax error. - test_command(ERR_SYNTAX, (const uint8_t *)"P\x02\xF4\x01\0\0\0", 7); + // A position is at most four bytes wide; what follows them, which from BASIC is the + // terminator, is ignored (SI-018). + test_dispatch("P\x02\xF4\x01\0\0\r", 7, 0, "set position", 2, 0x1F4, 500, 0); test_command( 0, (const uint8_t *)"CD:TEMP", 7); test_command( 0, (const uint8_t *)"CD1//TEMP", 9); test_command( 0, (const uint8_t *)"CD1//TEMP/TEMP2", 15); test_command( 0, (const uint8_t *)"CD1_", 4); - test_command( 0, (const uint8_t *)"RD33_/BLAH", 10); + test_command(34, (const uint8_t *)"RD33_/BLAH", 10); // RD takes no path (SI-063) test_command( 0, (const uint8_t *)"CD/TEMP/TEMP2", 13); test_command( 0, (const uint8_t *)"T-RA", 4); test_command( 0, (const uint8_t *)"T-RI", 4); test_command( 0, (const uint8_t *)"T-RD", 4); test_command( 0, (const uint8_t *)"T-RB", 4); - test_command( 0, (const uint8_t *)"T-WASUN. 13/07/25 09:34:13 PM", 29); test_command( 0, (const uint8_t *)"CP", 2); test_command( 0, (const uint8_t *)"CP1", 3); test_command( 0, (const uint8_t *)"CP12", 4); test_command( 0, (const uint8_t *)"CP123", 5); test_command( 0, (const uint8_t *)"CP1234", 6); test_command( 0, (const uint8_t *)"C\xD0\x1F", 3); - test_command( 0, (const uint8_t *)"N3/INSOMEDIR:HELL/HEAVEN=D64,NAME OF DISK,XX", 44); - test_command( 0, (const uint8_t *)"N:HELLO,123", 11); - test_command( 0, (const uint8_t *)"N:HELLO,23", 10); - test_command( 0, (const uint8_t *)"N:HELLO,A", 9); - test_command( 0, (const uint8_t *)"N:HELLO,", 8); - test_command( 0, (const uint8_t *)"N:HELLO", 7); - test_command( 0, (const uint8_t *)"N:", 2); + // N[n][path]:name[,id] (SI-071): the parser passes the name and the id on. + test_dispatch_text("N3//DISKS/:HELLO.D64,AB", 23, 0, "format", "3|//DISKS/|HELLO.D64|AB"); + test_dispatch_text("N:HELLO,123\r", 12, 0, "format", "-1||HELLO|123"); + test_dispatch_text("N:HELLO", 7, 0, "format", "-1||HELLO|"); + test_dispatch("N:", 2, 34, NULL); + test_dispatch("N:,AB", 5, 34, NULL); + test_dispatch("NHELLO,AB", 9, 34, NULL); test_command( 0, (const uint8_t *)"MD:TEMP", 7); test_command( 0, (const uint8_t *)"MD1:TEMP", 8); test_command( 0, (const uint8_t *)"MD1//:TEMP", 10); test_command( 0, (const uint8_t *)"MD1//TEMP/:TEMP2", 16); test_command( 0, (const uint8_t *)"MD:", 3); - test_command( 0, (const uint8_t *)"MD", 2); - test_command( 0, (const uint8_t *)"MD/PATH\xC1\xC2", 9); + test_command(34, (const uint8_t *)"MD", 2); // MD needs a colon (SI-060) + test_command(34, (const uint8_t *)"MD/PATH\xC1\xC2", 9); test_command( 0, (const uint8_t *)"MD:PATH\xC1\xC2", 9); test_command( 0, (const uint8_t *)"XPWD", 4); diff --git a/software/io/iec/cbmdos_stubs.cc b/software/io/iec/cbmdos_stubs.cc index 6615b2af5..ec01df41b 100644 --- a/software/io/iec/cbmdos_stubs.cc +++ b/software/io/iec/cbmdos_stubs.cc @@ -9,9 +9,10 @@ void print_file(filename_t& name); typedef struct { const char *command; int a, b, c, d; + char text[96]; // the names a command carried, where it carried any } stub_call_t; -stub_call_t last_stub_call = { NULL, 0, 0, 0, 0 }; +stub_call_t last_stub_call = { NULL, 0, 0, 0, 0, "" }; static void record_stub_call(const char *command, int a = 0, int b = 0, int c = 0, int d = 0) { @@ -20,14 +21,22 @@ static void record_stub_call(const char *command, int a = 0, int b = 0, int c = last_stub_call.b = b; last_stub_call.c = c; last_stub_call.d = d; + last_stub_call.text[0] = 0; +} + +// A file name as partition, path and name, for a test to compare as one string. +static void record_stub_name(filename_t& name) +{ + snprintf(last_stub_call.text, sizeof(last_stub_call.text), "%d|%s|%s", + name.partition, name.path.c_str(), name.filename.c_str()); } class IecCommandExecuterStubs : public IecCommandExecuter { public: - int do_block_read(int chan, int part, int track, int sector); - int do_block_write(int chan, int part, int track, int sector); - int do_block_allocate(int chan, int part, int track, int sector, bool allocate); + int do_block_read(int chan, int part, int track, int sector, bool length_byte); + int do_block_write(int chan, int part, int track, int sector, bool length_byte); + int do_block_allocate(int part, int track, int sector, bool allocate); int do_buffer_position(int chan, int pos); int do_set_current_partition(int part); int do_change_dir(filename_t& dest); @@ -35,34 +44,40 @@ class IecCommandExecuterStubs : public IecCommandExecuter int do_remove_dir(filename_t& dest); int do_copy(filename_t& dest, filename_t sources[], int n); int do_initialize(); - int do_format(uint8_t *name, uint8_t id1, uint8_t id2); + int do_initialize_buffers(); + int do_reset(bool cold); + int do_format(filename_t& dest, const char *id); int do_rename(filename_t &src, filename_t &dest); int do_scratch(filename_t filenames[], int n); int do_cmd_response(uint8_t *data, int len); int do_set_position(int chan, uint32_t pos, int recnr, int recoffset); int do_pwd_command(); int do_get_partition_info(int part); + int do_set_device_number(int dev); + int do_lock(filename_t& name); }; -int IecCommandExecuterStubs::do_block_read(int chan, int part, int track, int sector) +int IecCommandExecuterStubs::do_block_read(int chan, int part, int track, int sector, bool length_byte) { record_stub_call("block read", chan, part, track, sector); + strcpy(last_stub_call.text, length_byte ? "length" : "no length"); printf("Block read: Channel %d, Partition %d, T/S %d/%d\n", chan, part, track, sector); return 0; } -int IecCommandExecuterStubs::do_block_write(int chan, int part, int track, int sector) +int IecCommandExecuterStubs::do_block_write(int chan, int part, int track, int sector, bool length_byte) { record_stub_call("block write", chan, part, track, sector); + strcpy(last_stub_call.text, length_byte ? "length" : "no length"); printf("Block write: Channel %d, Partition %d, T/S %d/%d\n", chan, part, track, sector); return 0; } -int IecCommandExecuterStubs::do_block_allocate(int chan, int part, int track, int sector, bool allocate) +int IecCommandExecuterStubs::do_block_allocate(int part, int track, int sector, bool allocate) { - record_stub_call(allocate ? "block allocate" : "block free", chan, part, track, sector); - printf("Block %s: Channel %d, Partition %d, T/S %d/%d\n", allocate ? "allocate" : "free", chan, part, track, sector); + record_stub_call(allocate ? "block allocate" : "block free", part, track, sector); + printf("Block %s: Partition %d, T/S %d/%d\n", allocate ? "allocate" : "free", part, track, sector); return 0; } @@ -115,9 +130,23 @@ int IecCommandExecuterStubs::do_initialize() return 73; } -int IecCommandExecuterStubs::do_format(uint8_t *name, uint8_t id1, uint8_t id2) +int IecCommandExecuterStubs::do_reset(bool cold) +{ + record_stub_call("reset", cold ? 1 : 0); + return 73; +} + +int IecCommandExecuterStubs::do_initialize_buffers() +{ + record_stub_call("initialize buffers"); + return 0; +} + +int IecCommandExecuterStubs::do_format(filename_t& dest, const char *id) { - printf("Format: %s %02x %02x\n", name, id1, id2); + record_stub_call("format"); + snprintf(last_stub_call.text, sizeof(last_stub_call.text), "%d|%s|%s|%s", + dest.partition, dest.path.c_str(), dest.filename.c_str(), id); return 0; } @@ -142,7 +171,25 @@ int IecCommandExecuterStubs::do_scratch(filename_t filenames[], int n) int IecCommandExecuterStubs::do_cmd_response(uint8_t *data, int len) { - dump_hex_relative(data, len); + record_stub_call("command response", len); + int nonzero = 0; + for (int i = 0; i < len; i++) { + nonzero += (data[i] != 0); + } + last_stub_call.b = nonzero; + return 0; +} + +int IecCommandExecuterStubs::do_set_device_number(int dev) +{ + record_stub_call("device number", dev); + return 0; +} + +int IecCommandExecuterStubs::do_lock(filename_t& name) +{ + record_stub_call("lock"); + record_stub_name(name); return 0; } @@ -161,6 +208,7 @@ int IecCommandExecuterStubs::do_pwd_command() int IecCommandExecuterStubs :: do_get_partition_info(int part) { + record_stub_call("partition info", part); printf("Partition Info command\n"); return 0; } diff --git a/software/io/iec/iec_channel.cc b/software/io/iec/iec_channel.cc index 3a2a43a81..ae99e8f97 100644 --- a/software/io/iec/iec_channel.cc +++ b/software/io/iec/iec_channel.cc @@ -1,9 +1,80 @@ #include "iec_channel.h" #include "dump_hex.h" #include "rtc.h" +#include "iec_log.h" +#include "blockdev_file.h" +#include "filesystem_d64.h" +#include + +/* ------------------------------------------------------------------------------ + * The log (see iec_log.h): always one line for a command that leaves an error, an open + * that fails and the first failure of a channel. With the drive's "Log Every Operation" + * setting on, also one line for every other command, open and close, and for the last + * line of each listing. + * ------------------------------------------------------------------------------ */ + +// Whether the error channel now holds an error. 00 to 19 are not errors in CBM DOS, and 73 +// is the answer to UI and the other resets, not a failure. +bool IecChannel::drive_failed(void) +{ + return (drive->last_error_code >= 20) && (drive->last_error_code != ERR_DOS); +} + +// Writes one line: what happened, the current partition and its working directory, the +// bytes involved, optionally a labelled second set of bytes, the error channel's answer and +// a sequence number. +// Bytes are passed with their length and never treated as a string, and every rendering is +// bounded by its buffer. The buffers are static to keep them off the IEC task's small +// stack; every caller holds the drive's lock (CR-6), so two lines cannot be built at once. +void IecChannel::log_line(const char *what, const uint8_t *payload, int len, + const char *label, const uint8_t *extra, int extra_len) +{ + static char txt[SOFTIEC_LOG_TEXT_SIZE]; + static char more[SOFTIEC_LOG_TEXT_SIZE]; + static char dir[SOFTIEC_LOG_TEXT_SIZE]; + static char err[80]; + + // The drive's rendering of the error channel, without the carriage return it ends in, + // which would split the line. Reading it here does not clear it. + int n = drive->get_error_string(err); + if ((n < 0) || (n >= (int)sizeof(err))) { + n = 0; + } + while ((n > 0) && ((err[n - 1] == 0x0D) || (err[n - 1] == 0x0A))) { + n--; + } + err[n] = 0; + + IecPartition *part = drive->vfs ? drive->vfs->GetPartition(0) : NULL; + const char *cwd = part ? part->GetRelativePath() : NULL; + softiec_log_text((const uint8_t *)cwd, cwd ? strlen(cwd) : 0, dir, sizeof(dir)); + softiec_log_text(payload, payload ? len : 0, txt, sizeof(txt)); + softiec_log_text(extra, extra ? extra_len : 0, more, sizeof(more)); + // The sequence number counts every line, so a reader can tell a line that was lost or + // delivered twice on the way to the log from one the drive wrote twice. + static unsigned sequence = 0; + printf(SOFTIEC_LOG_PREFIX "%s dev=%d chan=%d part=%d dir=\"%s\" len=%d txt=\"%s\"%s%s%s%s%s -> %s #%u\n", + what, (int)drive->get_address(), channel, part ? part->GetPartitionNumber() : 0, dir, + payload ? len : 0, txt, label ? " " : "", label ? label : "", label ? "=\"" : "", + label ? more : "", label ? "\"" : "", err, ++sequence); +} + +// One line the first time a channel fails after it was opened, so a channel that fails +// on every byte does not fill the log. +void IecChannel::log_fault(const char *what) +{ + if (fault_logged) { + return; + } + fault_logged = true; + static char detail[96]; + snprintf(detail, sizeof(detail), "channel fault in %s, state %d", what, (int)state); + log_line(detail, NULL, 0, NULL, NULL, 0); +} IecChannel::IecChannel(IecDrive *dr, int ch) { + fault_logged = false; fm = FileManager::getFileManager(); drive = dr; channel = ch; @@ -19,8 +90,10 @@ IecChannel::IecChannel(IecDrive *dr, int ch) flags = 0; recordSize = 0; recordOffset = 0; + dataOffset = 0; recordDirty = false; dir_free = 0; + buffer_partition = 0; pingpong = true; swap_buffers(); } @@ -32,6 +105,7 @@ IecChannel::~IecChannel() void IecChannel::reset(void) { + fault_logged = false; close_file(); pingpong = true; @@ -95,13 +169,19 @@ t_channel_retval IecChannel::prefetch_more(int max_fetch, uint8_t*& datapointer, } bool last = false; if (last_byte >= 0) { // there is a last byte in this block + if (prefetch > last_byte) { + // Already past it, for example a P into a record beyond its last byte. + // Offering a negative count makes the UCI target copy that many bytes. + fetched = 0; + return IEC_NO_FILE; + } if (prefetch + max_fetch > last_byte) { // example: prefetch = 0, last_byte = 1 => there are 2 bytes. if max_fetch = 2, it will be set to 2. max_fetch = last_byte - prefetch + 1; last = true; } } else { if (prefetch + max_fetch > prefetch_max) { - max_fetch = prefetch_max - prefetch; + max_fetch = (prefetch < prefetch_max) ? (prefetch_max - prefetch) : 0; } } datapointer = &buffer[prefetch]; @@ -123,10 +203,12 @@ t_channel_retval IecChannel::pop_more(int pop_size) } pointer += pop_size; if (pointer == 512) { - if (read_block()) // also resets pointer. + if (read_block()) { // also resets pointer. + log_fault("read_block while streaming"); return IEC_READ_ERROR; - else + } else { return IEC_OK; + } } break; case e_dir: @@ -173,10 +255,12 @@ t_channel_retval IecChannel::pop_data(void) pointer ++; // make sure it's beyond the last byte now return IEC_NO_FILE; // no more data? } else if (pointer == 511) { - if (read_block()) // also resets pointer. + if (read_block()) { // also resets pointer. + log_fault("read_block while streaming"); return IEC_READ_ERROR; - else + } else { return IEC_OK; + } } break; case e_dir: @@ -234,6 +318,7 @@ int IecChannel::read_block(void) } if (res != FR_OK) { state = e_error; + log_fault("read_block"); return IEC_READ_ERROR; } if (curblk->valid_bytes == 0) { @@ -262,8 +347,9 @@ t_channel_retval IecChannel::push_data(uint8_t b) switch (state) { case e_filename: - if (pointer < 64) + if (pointer <= CBMDOS_COMMAND_BUFFER_SIZE) { // one more than open_file() accepts (SI-021) buffer[pointer++] = b; + } break; case e_record: @@ -289,6 +375,7 @@ t_channel_retval IecChannel::push_data(uint8_t b) fm->fclose(f); f = NULL; state = e_error; + log_fault("push_data block write"); return IEC_WRITE_ERROR; } pointer = 0; @@ -302,6 +389,7 @@ t_channel_retval IecChannel::push_data(uint8_t b) break; default: + log_fault("push_data on a channel that is not writing"); return IEC_BYTE_LOST; } return IEC_OK; @@ -316,6 +404,9 @@ t_channel_retval IecChannel::push_command(uint8_t b) pointer = 0; break; case 0xE0: // close + if (drive->log_every_operation()) { + log_line("close", NULL, 0, NULL, NULL, 0); + } if ((name_to_open.access == e_write) || (name_to_open.access == e_append)) { if (f) { if (pointer > 0) { @@ -327,6 +418,7 @@ t_channel_retval IecChannel::push_command(uint8_t b) } } close_file(); + name_to_open.access = e_not_set; // closed: I and UJ closing it again is not a write } else { state = e_error; return IEC_WRITE_ERROR; @@ -447,18 +539,61 @@ t_channel_retval IecChannel::write_record(void) static void iec_path_to_fs_path(mstring &path) { - // Path conversion needs to take place, because - // in this context, _ means "..", and when the path starts - // with a /, it should be stripped off, while // means root, - // which corresponds to starting with / in Ultimate VFS. + // Path conversion needs to take place, because when the path starts with a /, it + // should be stripped off, while // means root, which corresponds to starting with + // / in Ultimate VFS. A left arrow in a path component is a name like any other: it + // means the parent only in the name position, which do_change_dir() handles (SI-014). if (path[0] == '/' && path[1] != '/') { mstring stripped(path.c_str() + 1); path = stripped; } - path.replace("_", ".."); path.replace("//", "/"); } +// The disk image formats, by the extension of a name (SD check_imageext()). +typedef enum { e_image_none, e_image_d64, e_image_d71, e_image_d81, e_image_dnp } iec_image_t; + +static iec_image_t iec_image_type(const char *name) +{ + const char *dot = strrchr(name, '.'); + if (!dot || (strlen(dot) != 4)) { + return e_image_none; + } + char ext[4] = { (char)toupper(dot[1]), (char)toupper(dot[2]), (char)toupper(dot[3]), 0 }; + if (!strcmp(ext, "D64") || !strcmp(ext, "D41")) { + return e_image_d64; + } + if (!strcmp(ext, "D71")) { + return e_image_d71; + } + if (!strcmp(ext, "D81")) { + return e_image_d81; + } + if (!strcmp(ext, "DNP")) { + return e_image_dnp; + } + return e_image_none; +} + +// A disk image or a cartridge is stored under exactly its own name, with no type +// extension, so that a PC sees GAME.D81 and not GAME.D81.prg (SI-072, SD should_save_raw()). +static bool iec_name_is_raw(const char *name) +{ + if (iec_image_type(name) != e_image_none) { + return true; + } + const char *dot = strrchr(name, '.'); + if (!dot) { + return false; + } + char ext[5]; + int n = 0; + for (const char *p = dot + 1; *p && (n < 5); p++) { + ext[n++] = toupper(*p); + } + return ((n == 3) && !strncmp(ext, "CRT", 3)) || ((n == 4) && !strncmp(ext, "TCRT", 4)); +} + static bool iec_file_type_matches(filetype_t requested, filetype_t found) { return requested == e_any || found == e_any || requested == found; @@ -483,6 +618,118 @@ static void append_path_component(mstring& path, const char *component) path += component; } +// x00 wrappers (SI-144, SD fatops.c): a host file whose extension is P, S, U or R and two +// digits, and which starts with "C64File" and a zero, carries its CBM name in the 16 bytes +// at offset 8 and a relative file's record length at offset 25. The data follows the header. +static bool x00_extension(const char *ext, filetype_t *type) +{ + if (!ext || !ext[0] || !isdigit((uint8_t)ext[1]) || !isdigit((uint8_t)ext[2]) || ext[3]) { + return false; + } + switch (toupper((uint8_t)ext[0])) { + case 'P': *type = e_prg; return true; + case 'S': *type = e_seq; return true; + case 'U': *type = e_usr; return true; + case 'R': *type = e_rel; return true; + } + return false; +} + +static bool x00_path(const char *path, filetype_t *type) +{ + const char *dot = strrchr(path, '.'); + return dot && !strchr(dot, '/') && x00_extension(dot + 1, type); +} + +static bool x00_header(const uint8_t *header, uint32_t length, char *cbm_name, uint8_t *record_length) +{ + if ((length < X00_HEADER_SIZE) || (memcmp(header, "C64File", 8) != 0)) { + return false; + } + if (cbm_name) { + memcpy(cbm_name, header + 8, 16); + cbm_name[16] = 0; + } + if (record_length) { + *record_length = header[25]; + } + return true; +} + +// The CBM name, and the type, of a host file that is a genuine x00 wrapper; false for any +// other file, which is not opened unless its extension is an x00 one. +bool iec_x00_probe(FileManager *fm, const char *path, char *cbm_name, filetype_t *type, uint8_t *record_length) +{ + filetype_t found; + if (!x00_path(path, &found)) { + return false; + } + File *file = NULL; + if (fm->fopen(path, FA_READ, &file) != FR_OK) { + return false; + } + uint8_t header[X00_HEADER_SIZE]; + uint32_t got = 0; + FRESULT fres = file->read(header, X00_HEADER_SIZE, &got); + fm->fclose(file); + if ((fres != FR_OK) || !x00_header(header, got, cbm_name, record_length)) { + return false; + } + if (type) { + *type = found; + } + return true; +} + +// The name and type a directory entry has on the bus: the name in its x00 header when it +// is a wrapper, or the host name otherwise. Returns the size of the header, 0 or 26, which +// the entry's size includes. +int iec_entry_name(FileManager *fm, const char *dir_path, FileInfo *info, char *cbm_name, filetype_t& type) +{ + IecPartition::CreateIecName(info, cbm_name, type); + filetype_t wrapped; + if ((info->attrib & AM_DIR) || (info->name_format & NAME_FORMAT_CBM) || !dir_path || + !x00_extension(info->extension, &wrapped)) { + return 0; + } + mstring path(dir_path); + append_path_component(path, info->lfname); + if (!iec_x00_probe(fm, path.c_str(), cbm_name, &type, NULL)) { + return 0; + } + return X00_HEADER_SIZE; +} + +// Moves a file opened for reading past its x00 header when it has one, and returns the +// size of the header, 0 or X00_HEADER_SIZE (SI-144). +static uint32_t skip_x00_header(File *f, const char *path, uint8_t *record_length) +{ + filetype_t type; + uint8_t head[X00_HEADER_SIZE]; + uint32_t got = 0; + if (!x00_path(path, &type) || !f->get_size()) { + return 0; + } + if ((f->read(head, X00_HEADER_SIZE, &got) == FR_OK) && x00_header(head, got, NULL, record_length)) { + return X00_HEADER_SIZE; + } + f->seek(0); + return 0; +} + +// ConstructPath() names a file of any type with the pattern .???, which fstat() matches. +// This puts the name fstat() found in place of the pattern, because an x00 file is told +// by its real name (SI-144). +static void use_found_name(mstring& path, FileInfo& info) +{ + const char *p = path.c_str(); + const char *slash = strrchr(p, '/'); + mstring found(p, 0, slash ? (int)(slash - p) : -1); + char entry[80]; + found += (info.name_format & NAME_FORMAT_CBM) ? info.generate_fat_name(entry, sizeof(entry)) : info.lfname; + path = found; +} + static void partition_relative_to_full_path(IecPartition *partition, Path& relative, mstring& full_path) { full_path = partition->GetRootPath(); @@ -517,7 +764,7 @@ static FRESULT find_rendered_iec_child(FileManager *fm, const char *full_dir, char iec_name[24]; filetype_t found_type = e_any; - IecPartition::CreateIecName(&info, iec_name, found_type); + iec_entry_name(fm, full_dir, &info, iec_name, found_type); if (!is_dir && !iec_file_type_matches(ftype, found_type)) { continue; } @@ -528,7 +775,14 @@ static FRESULT find_rendered_iec_child(FileManager *fm, const char *full_dir, continue; } - actual_name = info.lfname; + // Inside a disk image a file is found again by its name with the type extension; + // on a host file system, and for any directory, by the name itself. + if (!is_dir && (info.name_format & NAME_FORMAT_CBM)) { + char entry[80]; + actual_name = info.generate_fat_name(entry, sizeof(entry)); + } else { + actual_name = info.lfname; + } if (out_info) { out_info->copyfrom(&info); } @@ -554,8 +808,15 @@ FRESULT resolve_directory_path(FileManager *fm, IecPartition *partition, // Path requested(path.c_str()); // this doesnt work if the path starts with .. for example // printf("resolve_directory_path: path = %s. Requested = %s. Resolved before loop = %s.\n", path.c_str(), requested.get_path(), resolved.get_path()); - const char *components[16]; - int count = path.split('/', components, 16); + // As many components as the path has, not a fixed number: a deeper path is followed + // to its end rather than cut off (SI-150). + int capacity = 1; + for (const char *p = path.c_str(); *p; p++) { + capacity += (*p == '/'); + } + const char **components = new const char *[capacity]; + int count = path.split('/', components, capacity); + FRESULT result = FR_OK; for (int i = 0; i < count; i++) { const char *component = components[i]; //requested.getElement(i); @@ -564,7 +825,8 @@ FRESULT resolve_directory_path(FileManager *fm, IecPartition *partition, if (!strcmp(component, ".") || !strcmp(component, "..")) { if (!resolved.cd(component)) { // not possible to move - return FR_NO_PATH; + result = FR_NO_PATH; + break; } continue; } @@ -573,8 +835,10 @@ FRESULT resolve_directory_path(FileManager *fm, IecPartition *partition, // printf("Fat component: %s\n", fat_component); direct_component = fat_component; + // A component with wildcards names the first directory that matches it (SI-012), + // so it is not tried as a literal name. Path direct_path(&resolved); - if (direct_path.cd(direct_component)) { + if (!iec_name_has_wildcards(component) && direct_path.cd(direct_component)) { mstring direct_full_path; partition_relative_to_full_path(partition, direct_path, direct_full_path); @@ -594,14 +858,19 @@ FRESULT resolve_directory_path(FileManager *fm, IecPartition *partition, // printf("Current Full Path: %s\n", current_full_path.c_str()); mstring actual_name; FRESULT fres = find_rendered_iec_child(fm, current_full_path.c_str(), component, - e_folder, true, false, false, + e_folder, true, false, true, actual_name, NULL); // printf("Fres = %s. Actual name = %s\n", FileSystem::get_error_string(fres), actual_name.c_str()); if (fres != FR_OK) { - return fres; + result = fres; + break; } resolved.cd(actual_name.c_str()); } + delete[] components; + if (result != FR_OK) { + return result; + } partition_relative_to_full_path(partition, resolved, full_path); // printf("Full Path: %s\n", full_path.c_str()); @@ -649,7 +918,7 @@ static FRESULT resolve_directory_target(FileManager *fm, IecPartition *partition petscii_to_fat(name.filename.c_str(), fatname, 52); Path direct_relative(relative_path.c_str()); - if (direct_relative.cd(fatname)) { + if (!name.has_wildcard && direct_relative.cd(fatname)) { mstring direct_full_path; partition_relative_to_full_path(partition, direct_relative, direct_full_path); @@ -665,7 +934,7 @@ static FRESULT resolve_directory_target(FileManager *fm, IecPartition *partition mstring actual_name; fres = find_rendered_iec_child(fm, full_path.c_str(), name.filename.c_str(), - e_folder, true, false, false, + e_folder, true, false, true, actual_name, NULL); if (fres != FR_OK) { return fres; @@ -690,21 +959,85 @@ static FRESULT open_by_rendered_iec_name(FileManager *fm, IecPartition *partitio return fm->fopen(resolved.c_str(), flags, file); } +// The partition types CMD DOS defines, which are the drive's own vocabulary and not +// the file system layer's. Byte 0 of the reply to G-P is one of these codes, and the +// partition directory prints the matching three character name. +typedef enum { + e_partition_none = 0, + e_partition_native = 1, + e_partition_1541 = 2, + e_partition_1571 = 3, + e_partition_1581 = 4, +} cbm_partition_type_t; + +// Which CMD partition type a file system presents as, decided from the geometry the +// file system reports and from nothing else: +// +// no track and sector addressing a directory on the host file system NAT +// 256 sectors on track 1 a DNP image NAT +// 40 sectors on track 1 a D81 image 81 +// 21 sectors on track 1, <= 42 tracks a D64 image 41 +// 21 sectors on track 1, > 42 tracks a D71 image 71 +// +// The size of the first zone identifies three of the four layouts on its own. A 1541 +// disk and a 1571 disk share it, because a 1571 disk is the 1541 layout twice over, so +// the track count separates those two. 42 tracks is the largest extended 1541 image. +static cbm_partition_type_t cbm_partition_type_of(FileSystem *fs) +{ + if (!fs || !fs->supports_direct_sector_access()) { + return e_partition_native; + } + switch (fs->get_sectors_in_track(1)) { + case 256: // a CMD native partition addresses 256 sectors on every track + return e_partition_native; + case 40: // a 1581 disk has 40 sectors on every track + return e_partition_1581; + case 21: // the first zone of a 1541 disk, and of each side of a 1571 disk + return (fs->get_num_tracks() > 42) ? e_partition_1571 : e_partition_1541; + default: + return e_partition_native; + } +} + // The type of a partition follows the file system at its root: a mounted disk image // reports the drive model it emulates, everything else is native. Only the file // system of the returned info is used. -static const char *iec_partition_type(FileManager *fm, IecPartition *prt) +static cbm_partition_type_t iec_partition_type(FileManager *fm, IecPartition *prt) { FileInfo info(32); - if (fm->is_path_valid(prt->GetRootPath(), &info) && info.fs) { - return info.fs->get_partition_type(); + if (fm->is_path_valid(prt->GetRootPath(), &info)) { + return cbm_partition_type_of(info.fs); } - return "NAT"; + return e_partition_native; +} + +// The three character name CMD DOS prints for a partition type. The field is three +// wide, so the shorter names carry their trailing space. +static const char *cbm_partition_type_name(cbm_partition_type_t type) +{ + switch (type) { + case e_partition_1541: return "41 "; + case e_partition_1571: return "71 "; + case e_partition_1581: return "81 "; + default: return "NAT"; + } +} + +// A time stamped directory line has a fixed length: CMD DOS fills the space behind the +// stamp with 0x01 and ends the BASIC line with a zero (SI-139). `used` is the first byte +// behind the stamp and `length` the length the line must have. Returns that length. +static int pad_stamped_entry(uint8_t *buffer, int used, int length) +{ + while (used < (length - 1)) { + buffer[used++] = 1; + } + buffer[length - 1] = 0; + return length; } int IecChannel::read_dir_entry(void) { - FileInfo info(40); + FileInfo info(INFO_SIZE); // the whole host name, which an x00 file is probed by const char *partition_type = NULL; FRESULT fres; if (state == e_dir) { @@ -730,8 +1063,14 @@ int IecChannel::read_dir_entry(void) info.attrib = AM_DIR; strncpy(info.lfname, prt->GetName(), info.lfsize); info.lfname[info.lfsize - 1] = 0; - partition_type = iec_partition_type(fm, prt); + cbm_partition_type_t type = iec_partition_type(fm, prt); + partition_type = cbm_partition_type_name(type); part_idx ++; + // A type given as $=P:*=N and the like lists only partitions of that type. + if (name_to_open.dir_opt.partition_types && + !(name_to_open.dir_opt.partition_types & (1 << (int)type))) { + return 1; + } } } @@ -741,6 +1080,24 @@ int IecChannel::read_dir_entry(void) dir = NULL; } + pointer = 0; + prefetch = 0; + if (state == e_partlist) { + // A partition directory has no blocks free line (SI-045, issue #890): the + // BASIC end marker follows the last partition. + buffer[0] = 0; + buffer[1] = 0; + last_byte = 1; + prefetch_max = 2; // the count of valid bytes, so that pop_data() reaches last_byte + state = e_dir; // with no directory open, the next call returns -1 + if (drive->log_every_operation()) { + log_line("listing end", buffer, 2, NULL, NULL, 0); + } + return 0; + } + + buffer[0] = 1; + buffer[1] = 1; if (dir_free > 65535) { buffer[2] = 0xFF; buffer[3] = 0xFF; @@ -751,9 +1108,12 @@ int IecChannel::read_dir_entry(void) memcpy(&buffer[4], "BLOCKS FREE. \0\0\0", 28); last_byte = 31; pointer = 0; - prefetch_max = 31; + prefetch_max = 32; // the count of valid bytes, so that pop_data() reaches last_byte prefetch = 0; state = e_dir; // This causes a -1 to be returned next time this function is called + if (drive->log_every_operation()) { + log_line("listing end", buffer, 32, NULL, NULL, 0); + } return 0; } @@ -762,10 +1122,10 @@ int IecChannel::read_dir_entry(void) return 1; } - // convert FAT name to CBM name + // convert FAT name to CBM name; an x00 wrapper lists as what it wraps (SI-144) char cbm_name[24]; filetype_t ftype = e_any; - IecPartition::CreateIecName(&info, cbm_name, ftype); + info.size -= iec_entry_name(fm, (state == e_dir) ? dir_path.c_str() : NULL, &info, cbm_name, ftype); if (ftype == e_any) { ftype = e_seq; } @@ -809,6 +1169,12 @@ int IecChannel::read_dir_entry(void) chars++; } int spaces = 3 - chars; + // The low byte of the link carries the size remainder, (size mod 254) + 2, where the + // size is exact (SI-133). A CBM image counts whole blocks and a partition line has no + // size, so those keep the plain link. + bool exact_size = !partition_type && !(info.fs && info.fs->supports_direct_sector_access()); + buffer[0] = exact_size ? (uint8_t)((info.size % 254) + 2) : 1; + buffer[1] = 1; buffer[2] = size & 255; buffer[3] = size >> 8; int pos = 4; @@ -824,6 +1190,9 @@ int IecChannel::read_dir_entry(void) const char *types[] = { "ANY", "PRG", "SEQ", "USR", "REL", "DIR" }; memcpy(&buffer[27 - chars], partition_type ? partition_type : types[(int)ftype], 3); + if (!partition_type && (info.attrib & AM_RDO)) { + buffer[30 - chars] = '<'; // locked (SI-132) + } pointer = 0; prefetch = 0; @@ -833,13 +1202,15 @@ int IecChannel::read_dir_entry(void) prefetch_max = 32; break; case e_stamp_long: - cbmdos_time(dt, (char *)buffer + 31 - chars, true); - prefetch_max = 31 + 18 - chars; + // Three spaces follow the type, so the stamp starts four characters behind it, and + // the line is a fixed 64 bytes (SI-139). SD createentry() and HD 9-22. + cbmdos_time(dt, (char *)buffer + 33 - chars, true); + prefetch_max = pad_stamped_entry(buffer, 33 - chars + 19, 64); break; case e_stamp_short: buffer[28 - chars] = 32; // space out second letter of file type cbmdos_time(dt, (char *)buffer + 29 - chars, false); - prefetch_max = 29 + 14 - chars; + prefetch_max = pad_stamped_entry(buffer, 29 - chars + 13, 42); break; } return 0; @@ -857,6 +1228,8 @@ int IecChannel :: setup_partition_read() last_byte = -1; dir_free = 0; memcpy(buffer, c_header, 32); + // The number in front of the header name is the number of partitions (SI-046). + buffer[4] = (uint8_t)drive->vfs->CountPartitions(); memcpy(buffer+8, "ULTIMATE HD", 11); memcpy(buffer+26, "UL 64", 5); return 0; @@ -867,16 +1240,19 @@ int IecChannel :: setup_directory_read() DBGIEC("Setup dir read\n"); char fatname[48]; - // previously not closed?? + // Released and cleared before anything below can fail, so no early return leaves the + // channel pointing at a freed directory for the next open to free again (CR-5). if (dir) { delete dir; - } + dir = NULL; + } GETPARTITION(name_to_open.file.partition, partition, -1); petscii_to_fat(name_to_open.file.filename.c_str(), fatname, 48); mstring work; - FRESULT fres = resolve_directory_path(fm, partition, name_to_open.file.path, work); + mstring relative; + FRESULT fres = resolve_directory_path(fm, partition, name_to_open.file.path, work, &relative); if (fres != FR_OK) { drive->set_error(ERR_DIRECTORY_ERROR, drive->vfs->GetTargetPartitionNumber(name_to_open.file.partition), 0); state = e_error; @@ -886,6 +1262,7 @@ int IecChannel :: setup_directory_read() DBGIECV("Full Path = %s, filename = %s\n", work.c_str(), fatname); FileInfo info(40); + dir_path = work; fres = fm->open_directory(work.c_str(), &dir, &info); if (fres != FR_OK) { printf("opening dir failed %s\n", FileSystem::get_error_string(fres)); @@ -908,7 +1285,9 @@ int IecChannel :: setup_directory_read() IecPartition *part = drive->vfs->GetPartition(name_to_open.file.partition); - if (info.fs->supports_direct_sector_access()) { // might be CBM image! + FileSystem *fs = info.fs; + bool labelled = false; + if (fs->supports_direct_sector_access()) { // might be CBM image! dir->get_entry(info); // first one SHOULD be the volume label if ((info.attrib & AM_VOL) && (info.name_format & NAME_FORMAT_CBM)) { printf("Volume label found: %s\n", info.lfname); @@ -916,19 +1295,48 @@ int IecChannel :: setup_directory_read() buffer[8 + i] = info.lfname[i] & 0x7F; } buffer[8 + 16] = 0x22; - return 0; + labelled = true; } } - //const char *fullname = part->GetRelativePath(); - const char *pp = partition->GetName(); // new feature! - int pos = 8; - int len = strlen(pp); - if (len > 16) { - pp += (len - 16); + // The header names the listed directory as it appears in its parent, and the + // partition only at the root (SI-065, SD fat_getdirlabel()). + const char *rel = relative.c_str(); + int rel_len = strlen(rel); + while ((rel_len > 0) && (rel[rel_len - 1] == '/')) { + rel_len--; + } + if (labelled) { + // the image's own label and id + } else if (rel_len > 0) { + int start = rel_len; + while ((start > 0) && (rel[start - 1] != '/')) { + start--; + } + FileInfo dirinfo(40); + int n = rel_len - start; + if (n > dirinfo.lfsize - 1) { + n = dirinfo.lfsize - 1; + } + memcpy(dirinfo.lfname, rel + start, n); + dirinfo.lfname[n] = 0; + dirinfo.attrib = AM_DIR; + char cbm_name[24]; + filetype_t ftype = e_any; + IecPartition::CreateIecName(&dirinfo, cbm_name, ftype); + for (int i = 0; (i < 16) && cbm_name[i]; i++) { + buffer[8 + i] = cbm_name[i]; + } + } else { + const char *pp = partition->GetName(); + int pos = 8; + int len = strlen(pp); + if (len > 16) { + pp += (len - 16); + } + while ((pos < 24) && (*pp)) + buffer[pos++] = toupper(*(pp++)); } - while ((pos < 24) && (*pp)) - buffer[pos++] = toupper(*(pp++)); return 0; } @@ -960,7 +1368,40 @@ int IecChannel :: setup_file_access() print_file(name_to_open.file); #endif mstring work; - const char *full_path = ConstructPath(work, name_to_open.file, name_to_open.filetype, name_to_open.access ); + const char *full_path = NULL; + + // A pattern in a name to write (SI-032). Without @ it is an illegal name. With @ the + // first match is replaced under its own name if its type is the one asked for; any + // other type, a relative file, or no match at all answers 64, which is the check the + // 1541 ROM makes at $D8F5. + // A name that starts with a shifted space is no name to create (SI-148): 33, or 64 with + // @, which parse_open() has already answered. + if ((name_to_open.access == e_write) && ((uint8_t)name_to_open.file.filename.c_str()[0] == 0xA0)) { + drive->set_error(name_to_open.replace ? ERR_FILE_TYPE_MISMATCH : ERR_SYNTAX_ERROR_NAME, 0, 0); + return 0; + } + if ((name_to_open.access == e_write) && name_to_open.file.has_wildcard) { + if (!name_to_open.replace) { + drive->set_error(ERR_SYNTAX_ERROR_NAME, 0, 0); + return 0; + } + GETPARTITION(name_to_open.file.partition, partition, 0); + FileInfo matched(INFO_SIZE); + filetype_t found = e_any; + FRESULT fres = resolve_existing_iec_path(fm, partition, name_to_open.file, e_any, + false, true, true, work, &matched); + char cbm_name[24]; + if ((fres == FR_OK) && !iec_x00_probe(fm, work.c_str(), cbm_name, &found, NULL)) { + IecPartition::CreateIecName(&matched, cbm_name, found); + } + if ((fres != FR_OK) || (found != name_to_open.filetype) || (found == e_rel)) { + drive->set_error(ERR_FILE_TYPE_MISMATCH, 0, 0); + return 0; + } + full_path = work.c_str(); + } else { + full_path = ConstructPath(work, name_to_open.file, name_to_open.filetype, name_to_open.access ); + } if (!full_path) { drive->set_error(ERR_PARTITION_ERROR, drive->vfs->GetTargetPartitionNumber(name_to_open.file.partition), 0); return 0; @@ -969,20 +1410,42 @@ int IecChannel :: setup_file_access() // Existing REL files also open by name alone (for example the E.DATA editor). // Resolve the type before choosing access flags and setting up record I/O. if (name_to_open.filetype == e_any) { - FileInfo info(48); + FileInfo info(INFO_SIZE); FRESULT fres = fm->fstat(full_path, info); if (fres == FR_NO_FILE) { GETPARTITION(name_to_open.file.partition, partition, 0); fres = resolve_existing_iec_path(fm, partition, name_to_open.file, e_any, false, true, true, work, &info); - full_path = work.c_str(); + } else if (fres == FR_OK) { + use_found_name(work, info); } + full_path = work.c_str(); if (fres != FR_OK) { drive->set_error_fres(fres); return 0; } char cbm_name[24]; - IecPartition::CreateIecName(&info, cbm_name, name_to_open.filetype); + if (!iec_x00_probe(fm, full_path, cbm_name, &name_to_open.filetype, NULL)) { + IecPartition::CreateIecName(&info, cbm_name, name_to_open.filetype); + } + } + + // A name that an x00 file carries is taken, as in SD file_open(): without @ the answer is + // 63, and with @ the x00 file makes way for the new file. + if ((name_to_open.access == e_write) && !name_to_open.file.has_wildcard) { + GETPARTITION(name_to_open.file.partition, partition, 0); + FileInfo existing(4); + mstring wrapped; + if ((fm->fstat(full_path, existing) == FR_NO_FILE) && + (resolve_existing_iec_path(fm, partition, name_to_open.file, name_to_open.filetype, + false, true, false, wrapped) == FR_OK) && + iec_x00_probe(fm, wrapped.c_str(), NULL, NULL, NULL)) { + if (!name_to_open.replace) { + drive->set_error(ERR_FILE_EXISTS, 0, 0); + return 0; + } + fm->delete_file(wrapped.c_str()); + } } uint8_t flags; @@ -998,7 +1461,10 @@ int IecChannel :: setup_file_access() } break; default: - flags = FA_READ; + // FA_OPEN_FROM_CBM keeps FileInCBM::open() from wrapping a GEOS file in a CVT + // header, which belongs to the file browser and not to the bus (SI-149). 3.14d + // passed it here; commit 76d887bd rewrote this open and dropped it. + flags = FA_READ | FA_OPEN_FROM_CBM; } if (name_to_open.filetype == e_rel) { flags |= ( FA_READ | FA_WRITE ); @@ -1009,8 +1475,20 @@ int IecChannel :: setup_file_access() DBGIECV("Setup File Access %s %02x\n", full_path, flags); + // A relative file that already exists is opened by its CBM name, which finds it in an + // x00 wrapper too (SI-146), rather than created again beside it. + if ((name_to_open.filetype == e_rel) && name_to_open.record_size && !name_to_open.file.has_wildcard) { + GETPARTITION(name_to_open.file.partition, partition, 0); + mstring existing; + if (resolve_existing_iec_path(fm, partition, name_to_open.file, e_rel, + false, true, false, existing) == FR_OK) { + work = existing; + full_path = work.c_str(); + } + } + FRESULT fres = fm->fopen(full_path, flags, &f); - if ((fres == FR_NO_FILE) && (name_to_open.access == e_read)) { + if ((fres == FR_NO_FILE) && ((name_to_open.access == e_read) || (name_to_open.access == e_append))) { GETPARTITION(name_to_open.file.partition, partition, 0); fres = open_by_rendered_iec_name(fm, partition, name_to_open.file, name_to_open.filetype, flags, &f, work); @@ -1030,6 +1508,13 @@ int IecChannel :: setup_file_access() prefetch_max = 512; state = e_file; + // An existing file with an x00 name is read past its header when it has one (SI-144). + uint8_t wrapped_length = 0; + if (name_to_open.access != e_write) { + dataOffset = skip_x00_header(f, full_path, &wrapped_length); + } + bool wrapped = (dataOffset != 0); + if (name_to_open.filetype == e_rel) { uint32_t tr; if (!f->get_size()) { // the file must be newly created, because its size is 0. @@ -1038,19 +1523,42 @@ int IecChannel :: setup_file_access() drive->set_error_fres(fres); if (fres == FR_OK) { recordSize = name_to_open.record_size; + dataOffset = 2; recordOffset = 2; // First record follows the REL header, also on a reused channel. state = e_record; } } else { // file already exists - uint16_t wrd; - fres = f->read(&wrd, 2, &tr); - if (wrd >= 256) { - DBGIECV("WARNING: Illegal record size in .rel file...Is it a REL file at all? (%d)\n", wrd); + // The record length is at offset 25 of an R00 header, or the first byte of a + // plain file, which is this firmware's two byte layout or sd2iec's one byte + // layout (SI-084): a non-zero second byte can only be the one byte layout, and + // otherwise the size leaves 2 mod r over for the one and 1 mod r for the other. + // A record length of 1 leaves both the same and is read as the two byte layout. + // A disk image always presents the two byte layout, whatever its size. + int length = wrapped_length; + fres = FR_OK; + if (!wrapped) { + uint8_t head[2] = { 0, 0 }; + uint32_t head_bytes = 0; + fres = f->read(head, 2, &head_bytes); + length = head[0]; + uint32_t size = f->get_size(); + bool in_image = f->get_file_system() && f->get_file_system()->supports_direct_sector_access(); + dataOffset = 2; + if (in_image) { + // the two byte layout + } else if ((head_bytes >= 2) && head[1]) { + dataOffset = 1; + } else if ((length > 1) && ((size % length) != (2 % length)) && ((size % length) == (1 % length))) { + dataOffset = 1; + } + } + if ((fres != FR_OK) || (length == 0)) { + DBGIECV("WARNING: Illegal record size in .rel file...Is it a REL file at all? (%d)\n", length); state = e_error; drive->set_error(ERR_RECORD_NOT_PRESENT, 0, 0); return ERR_RECORD_NOT_PRESENT; } - recordSize = (uint8_t) wrd; + recordSize = (uint8_t) length; DBGIECV("Opened existing relative file. Record size found is: %d. Expected: %d\n", recordSize, name_to_open.record_size); if ((name_to_open.record_size != 0) && (recordSize != name_to_open.record_size)) { state = e_error; @@ -1087,12 +1595,15 @@ int IecChannel :: setup_file_access() return 0; } +// "#" opens a 256 byte buffer with its pointer at byte 1 (SI-090, SD README). The channel +// keeps the partition that is current now (SI-093). int IecChannel::setup_buffer_access(void) { last_byte = 255; - pointer = 0; - prefetch = 0; + pointer = 1; + prefetch = pointer; prefetch_max = 256; + buffer_partition = drive->vfs->GetTargetPartitionNumber(0); state = e_buffer; return 0; @@ -1100,44 +1611,80 @@ int IecChannel::setup_buffer_access(void) int IecChannel::open_file(void) // name should be in buffer { + // The name as the bus delivered it, kept for the failure log: setting up the stream + // reads the first block of a file into the same buffer. + static uint8_t raw_name[CBMDOS_COMMAND_BUFFER_SIZE]; + int raw_len = (pointer > (int)sizeof(raw_name)) ? (int)sizeof(raw_name) : pointer; + memcpy(raw_name, buffer, raw_len); + fault_logged = false; buffer[pointer] = 0; // string terminator DBGIECV("Open file. Raw Filename = '%s'\n", buffer); - int parse_err = parse_open((const char *)buffer, name_to_open); + // A name that fills the buffer is refused, as a command is, rather than opened under + // its first bytes (SI-022). + int parse_err = (pointer >= CBMDOS_COMMAND_BUFFER_SIZE) ? ERR_SYNTAX_ERROR_CMDLENGTH : + parse_open((const char *)buffer, name_to_open); if (parse_err) { state = e_error; drive->set_error(parse_err, 0, 0); + log_line("open failed", raw_name, raw_len, NULL, NULL, 0); return -1; } - IecPartition *partition = drive->vfs->GetPartition(name_to_open.file.partition); recordSize = 0; + dataOffset = 0; + int result = -1; switch(name_to_open.dir_opt.stream) { case e_stream_buffer: - return setup_buffer_access(); + result = setup_buffer_access(); + break; case e_stream_dir: - return setup_directory_read(); + result = setup_directory_read(); + break; case e_stream_partitions: - return setup_partition_read(); + result = setup_partition_read(); + break; case e_stream_file: - return setup_file_access(); + result = setup_file_access(); + break; default: // file DBGIEC("Unknown stream mode\n"); + break; + } + if ((state == e_error) && drive_failed()) { + log_line("open failed", raw_name, raw_len, NULL, NULL, 0); + } else if (drive->log_every_operation()) { + // The host file the name reached, or the first bytes of a listing. + if (f) { + const char *host = f->get_path(); + log_line("open", raw_name, raw_len, "host", (const uint8_t *)host, host ? strlen(host) : 0); + } else if ((state == e_dir) || (state == e_partlist)) { + log_line("open", raw_name, raw_len, "data", buffer, (prefetch_max < 32) ? prefetch_max : 32); + } else { + log_line("open", raw_name, raw_len, NULL, NULL, 0); + } } - return -1; + return result; } +// Closes the file, and releases the directory of a listing the host stopped reading +// (CR-4), which otherwise stayed allocated until the channel listed again. int IecChannel::close_file(void) // file should be open { if (f) fm->fclose(f); f = NULL; + if (dir) { + delete dir; + dir = NULL; + } state = e_idle; return 0; } int IecChannel::ext_open_file(const char *name) { + close_file(); // as an OPEN from the bus closes what the channel had open strncpy((char *) buffer, name, 255); buffer[255] = 0; pointer = strlen((char *) buffer); @@ -1156,7 +1703,7 @@ int IecChannel::ext_close_file(void) int IecChannel::seek_record(int recordNumber, int offset) { - const uint32_t c_header = 2; // 2 bytes for record size in the beginning of the file + const uint32_t c_header = dataOffset; // the record length in front of the records (SI-084) // flush write_record(); @@ -1302,7 +1849,7 @@ t_channel_retval IecCommandChannel::pop_more(int pop_size) t_channel_retval IecCommandChannel::push_data(uint8_t b) { - if (wr_pointer < 64) { + if (wr_pointer < CBMDOS_COMMAND_BUFFER_SIZE) { wr_buffer[wr_pointer++] = b; return IEC_OK; } @@ -1318,7 +1865,8 @@ const char *IecChannel :: ConstructPath(mstring& work, filename_t& name, filetyp petscii_to_fat(name.filename.c_str(), fatname, 52); // printf("After petscii_to_fat: '%s'\n", fatname); const char *ext = types[(int)ftype]; - if ((acc == e_read) || (ftype != e_any)) { // for reads, .??? is allowed, but for writes it is not + if (((acc == e_read) || (ftype != e_any)) && // for reads, .??? is allowed, but for writes it is not + !iec_name_is_raw(name.filename.c_str())) { add_extension(fatname, ext, 48); } @@ -1331,89 +1879,92 @@ const char *IecChannel :: ConstructPath(mstring& work, filename_t& name, filetyp } -int IecCommandChannel :: do_block_read(int chan, int part, int track, int sector) +// The direct access channel a block command names, or NULL with 70 set when the channel +// was not opened with #. +IecChannel *IecCommandChannel::buffer_channel(int chan) { - if ((chan < 0) || (chan > 14)) { - set_error(ERR_SYNTAX_ERROR_CMD); - return ERR_SYNTAX_ERROR_CMD; - } - if (part >= MAX_PARTITIONS) { - set_error(ERR_SYNTAX_ERROR_CMD); - return ERR_SYNTAX_ERROR_CMD; + if ((chan < 0) || (chan > 14) || (drive->get_data_channel(chan)->state != e_buffer)) { + drive->set_error(ERR_NO_CHANNEL, 0, 0); + return NULL; } - IecChannel *channel = drive->get_data_channel(chan); - GETPARTITION(part, partition, -1); - Path path(partition->GetFullPath()); - FRESULT fres; - fres = fm->fs_read_sector(&path, channel->buffer, track, sector); + return drive->get_data_channel(chan); +} + +// The result of a sector access, as the error channel reports it. +void IecCommandChannel::sector_error(FRESULT fres, int track, int sector) +{ if (fres == FR_DENIED) { drive->set_error(ERR_DENIED, track, sector); + } else if (fres == FR_INVALID_PARAMETER) { // outside the disk (SI-036) + drive->set_error(ERR_ILLEGAL_TRACK_SECTOR, track, sector); } else { drive->set_error_fres(fres); } - channel->pointer = 0; +} + +// U1 and B-R. The partition parameter is ignored: the channel reads from the partition that +// was current when it was opened (SI-093). U1 makes all 256 bytes readable from byte 0; +// B-R takes the count from byte 0 and starts at byte 1 (SI-094). +int IecCommandChannel :: do_block_read(int chan, int part, int track, int sector, bool length_byte) +{ + IecChannel *channel = buffer_channel(chan); + if (!channel) { + return 0; + } + GETPARTITION(channel->buffer_partition, partition, -1); + Path path(partition->GetFullPath()); + FRESULT fres = fm->fs_read_sector(&path, channel->buffer, track, sector); + sector_error(fres, track, sector); + channel->pointer = length_byte ? 1 : 0; + channel->last_byte = length_byte ? channel->buffer[0] : 255; channel->reset_prefetch(); state = e_idle; return 0; } -int IecCommandChannel::do_block_write(int chan, int part, int track, int sector) +// U2 and B-W, to the partition the channel was opened on; B-W first stores the buffer +// pointer minus one in byte 0 (SI-094). +int IecCommandChannel::do_block_write(int chan, int part, int track, int sector, bool length_byte) { - if ((chan < 0) || (chan > 14)) { - set_error(ERR_SYNTAX_ERROR_CMD); - return ERR_SYNTAX_ERROR_CMD; + IecChannel *channel = buffer_channel(chan); + if (!channel) { + return 0; } - if (part >= MAX_PARTITIONS) { - set_error(ERR_SYNTAX_ERROR_CMD); - return ERR_SYNTAX_ERROR_CMD; + GETPARTITION(channel->buffer_partition, partition, -1); + if (length_byte) { + channel->buffer[0] = (uint8_t)(channel->pointer - 1); } - IecChannel *channel = drive->get_data_channel(chan); - GETPARTITION(part, partition, -1); Path path(partition->GetFullPath()); - FRESULT fres; - fres = fm->fs_write_sector(&path, channel->buffer, track, sector); - if (fres == FR_DENIED) { - drive->set_error(ERR_DENIED, track, sector); - } else { - drive->set_error_fres(fres); - } + FRESULT fres = fm->fs_write_sector(&path, channel->buffer, track, sector); + sector_error(fres, track, sector); state = e_idle; return 0; } -int IecCommandChannel::do_block_allocate(int chan, int part, int track, int sector, bool alloc) +// B-A and B-F have no channel, so they act on the current partition; the partition +// parameter is ignored like that of the other direct access commands (SI-013). +int IecCommandChannel::do_block_allocate(int part, int track, int sector, bool alloc) { - if ((chan < 0) || (chan > 14)) { - set_error(ERR_SYNTAX_ERROR_CMD); - return ERR_SYNTAX_ERROR_CMD; - } - if (part >= MAX_PARTITIONS) { - set_error(ERR_SYNTAX_ERROR_CMD); - return ERR_SYNTAX_ERROR_CMD; - } - IecChannel *channel = drive->get_data_channel(chan); - GETPARTITION(part, partition, -1); + GETPARTITION(0, partition, -1); Path path(partition->GetFullPath()); - FRESULT fres; - fres = fm->fs_allocate_sector(&path, track, sector, alloc); - if (fres == FR_DENIED) { - drive->set_error(ERR_DENIED, track, sector); + FRESULT fres = fm->fs_allocate_sector(&path, track, sector, alloc); + if (fres == FR_EXIST) { // the block was allocated; track and sector name the next free one + drive->set_error(ERR_NO_BLOCK, track, sector); } else { - drive->set_error_fres(fres); + sector_error(fres, track, sector); } state = e_idle; return 0; } +// B-P on a buffer channel. int IecCommandChannel :: do_buffer_position(int chan, int pos) { - if ((chan < 0) || (chan > 14)) { - set_error(ERR_SYNTAX_ERROR_CMD); - return ERR_SYNTAX_ERROR_CMD; + IecChannel *channel = buffer_channel(chan); + if (!channel) { + return 0; } - IecChannel *channel; - channel = drive->get_data_channel(chan); - channel->pointer = pos & 0xFF; // CBM DOS keeps only the low byte, so it wraps + channel->pointer = pos & 0xFF; channel->reset_prefetch(); set_error(ERR_ALL_OK); return ERR_ALL_OK; @@ -1432,15 +1983,21 @@ int IecCommandChannel::do_change_dir(filename_t& dest) GETPARTITION(dest.partition, prt, -1); DBGIECV("Partition %d ('%s') Change dir %s:%s\n", dest.partition, prt->GetFullPath(), dest.path.c_str(), dest.filename.c_str()); - // The left arrow, PETSCII 0x5F, means the parent directory both after the command - // word, as in "CD_", and behind a colon, as in "CD:_" or "CD/SUB/:_". Only the - // first arrives as a path, so move the second there and both take one route. + // The left arrow, PETSCII 0x5F, means the parent directory in the name position: + // directly after the command word, as in "CD_", which the parser returns as a path + // of just the arrow, and behind a colon, as in "CD:_" or "CD/SUB/:_". Between + // slashes it is a directory name, so "CD/_" enters a directory called _ (SI-014, + // SI-015). Both name forms become the path component .., which is always the parent. + if ((dest.path == "_") && (dest.filename.length() == 0)) { + dest.path = ""; + dest.filename = "_"; + } if (dest.filename == "_") { dest.filename = ""; if (dest.path.length() && (dest.path[-1] != '/')) { dest.path += "/"; } - dest.path += "_"; + dest.path += ".."; } mstring full_path; @@ -1475,10 +2032,12 @@ int IecCommandChannel::do_remove_dir(filename_t& dest) if (fullpath) { DBGIECV("Directory to remove: %s\n", fullpath); FRESULT fres = fm->delete_file(fullpath); - if ((fres == FR_NO_FILE || fres == FR_NO_PATH) && !dest.has_wildcard) { + if (fres == FR_NO_FILE || fres == FR_NO_PATH) { + // A pattern names the first directory that matches it; its host name escapes + // the wildcards, so only the directory scan can find it (SI-142). GETPARTITION(dest.partition, partition, 0); fres = resolve_existing_iec_path(fm, partition, dest, e_folder, - true, false, false, work); + true, false, true, work); if (fres == FR_OK) { DBGIECV("Directory-assisted RD resolved to %s\n", work.c_str()); fres = fm->delete_file(work.c_str()); @@ -1501,24 +2060,28 @@ int IecCommandChannel::do_copy(filename_t& dest, filename_t sources[], int n) // So in order to know the destination extension, we'd need to first open the first file // using wildcards and then see what file was opened. mstring work; - FileInfo info(48); + FileInfo info(INFO_SIZE); const char *source1 = ConstructPath(work, sources[0], e_any, e_read); FRESULT fres = source1 ? fm->fstat(source1, info) : FR_NO_PATH; - if (fres != FR_OK) { + if (fres == FR_OK) { + use_found_name(work, info); + } else { GETPARTITION(sources[0].partition, partition, 0); fres = resolve_existing_iec_path(fm, partition, sources[0], e_any, false, true, sources[0].has_wildcard, work, &info); - source1 = work.c_str(); } + source1 = work.c_str(); if (fres != FR_OK) { drive->set_error_fres(fres); return ERR_FILE_NOT_FOUND; } - // convert FAT name to CBM name + // convert FAT name to CBM name, or take it from an x00 header (SI-144) char cbm_name[24]; filetype_t ftype = e_any; - IecPartition::CreateIecName(&info, cbm_name, ftype); + if (!iec_x00_probe(fm, source1, cbm_name, &ftype, NULL)) { + IecPartition::CreateIecName(&info, cbm_name, ftype); + } // ftype is now set to the type of the first original file. // Now the real copy action can begin @@ -1544,9 +2107,21 @@ int IecCommandChannel::do_copy(filename_t& dest, filename_t sources[], int n) } else { DBGIECV(" %d. unresolved by canonical path\n", i); } - fres = frompath ? fm->fopen(frompath, FA_READ, &fi) : FR_NO_PATH; + FileInfo found(INFO_SIZE); + fres = frompath ? fm->fstat(frompath, found) : FR_NO_PATH; + if (fres == FR_OK) { + use_found_name(work, found); + frompath = work.c_str(); + fres = fm->fopen(frompath, FA_READ, &fi); + } if (fres != FR_OK) { - GETPARTITION(sources[i].partition, partition, 0); + // Not GETPARTITION(), whose return would leave the target open and the copy + // buffer allocated. + IecPartition *partition = drive->vfs->GetPartition(sources[i].partition); + if (!partition) { + set_error(ERR_PARTITION_ERROR, drive->vfs->GetTargetPartitionNumber(sources[i].partition)); + break; + } fres = open_by_rendered_iec_name(fm, partition, sources[i], e_any, FA_READ, &fi, work); frompath = work.c_str(); @@ -1558,6 +2133,7 @@ int IecCommandChannel::do_copy(filename_t& dest, filename_t sources[], int n) drive->set_error_fres(fres); break; } + skip_x00_header(fi, frompath, NULL); // an x00 file copies its data, not its header uint32_t bytes_read, bytes_written; do { fres = fi->read(databuf, 32768, &bytes_read); @@ -1584,9 +2160,152 @@ int IecCommandChannel::do_initialize() return ERR_DOS; } -int IecCommandChannel::do_format(uint8_t *name, uint8_t id1, uint8_t id2) +// I: there is no medium to read in again, so what is left of initialising is what +// sd2iec does, closing the data channels a program left open (SI-053). A channel +// written to is closed the way a CLOSE from the host closes it, so its data is kept. +int IecCommandChannel::do_initialize_buffers() { - printf("Format: %s %02x %02x\n", name, id1, id2); + for (int i = 0; i < 15; i++) { + drive->get_data_channel(i)->push_command(0xE0); + } + drive->set_error(ERR_ALL_OK, 0, 0); + return 0; +} + +// UJ and U+shifted J (SI-103). Both close the data channels as I does, and U+shifted J +// also returns every partition to its root and selects partition 1, which is what +// IecDrive::reset() does to the partitions. Neither calls IecDrive::reset(): that reaches +// IecInterface::configure(), which holds the IEC processor in reset while the host is +// still addressing this drive. +int IecCommandChannel::do_reset(bool cold) +{ + do_initialize_buffers(); + if (cold) { + for (int i = 1; i < MAX_PARTITIONS; i++) { + IecPartition *p = drive->vfs->GetPartition(i); + if (p) { + p->cd("/"); + } + } + drive->vfs->SetCurrentPartition(1); + } + return ERR_DOS; +} + +// N[n][path]:name[,id] (SI-071). This drive has no medium of its own to format, so like +// sd2iec it creates a disk image, or formats one that exists, chosen by the extension: +// .D64 or .D41, .D71, .D81, and .DNP, whose id is a three digit track count and which is +// created but not formatted. A name without an image extension gets .D64, and then an +// existing file is left alone, as an existing DNP always is. A new image needs an id. +int IecCommandChannel::do_format(filename_t& dest, const char *id) +{ + GETPARTITION(dest.partition, partition, -1); + mstring dir; + FRESULT fres = resolve_directory_path(fm, partition, dest.path, dir); + if (fres != FR_OK) { + drive->set_error_fres(fres); + return 0; + } + + // Inside a disk image N would create an image in the image, which is not what a + // program formatting its disk asks for; formatting the mounted image under the file + // system that has it open is not safe, so it is refused. + FileInfo dir_info(4); + Directory *probe = NULL; + if (fm->open_directory(dir.c_str(), &probe, &dir_info) == FR_OK) { + delete probe; + if (dir_info.fs && dir_info.fs->supports_direct_sector_access()) { + return ERR_SYNTAX_ERROR_GEN; + } + } + + // A label of up to 16 characters and a four character extension. + char name[24]; + char label[24]; + strncpy(name, dest.filename.c_str(), 20); + name[20] = 0; + iec_image_t kind = iec_image_type(name); + bool extension_given = (kind != e_image_none); + if (!extension_given) { + kind = e_image_d64; + name[16] = 0; + strcat(name, ".D64"); + } + strcpy(label, name); + label[strrchr(label, '.') - label] = 0; + + int idlen = strlen(id); + if (kind == e_image_dnp) { + if (idlen && ((idlen != 3) || !isdigit(id[0]) || !isdigit(id[1]) || !isdigit(id[2]))) { + return ERR_SYNTAX_ERROR_GEN; + } + } else if (idlen && ((idlen < 2) || (idlen > 3))) { + return ERR_SYNTAX_ERROR_GEN; + } + + char host[52]; + petscii_to_fat(name, host, sizeof(host)); + mstring full(dir.c_str()); + append_path_component(full, host); + + File *f = NULL; + FileInfo existing(8); + if (fm->fstat(full.c_str(), existing) == FR_OK) { + if (!extension_given || (kind == e_image_dnp)) { + return ERR_FILE_EXISTS; + } + fres = fm->fopen(full.c_str(), FA_READ | FA_WRITE, &f); + } else { + if (!idlen) { + return ERR_SYNTAX_ERROR_GEN; + } + uint32_t size = 0; + switch (kind) { + case e_image_d64: size = 174848; break; + case e_image_d71: size = 349696; break; + case e_image_d81: size = 819200; break; + default: size = 65536 * (uint32_t)atoi(id); break; + } + if (size == 0) { + return ERR_FILE_NOT_FOUND; + } + Path dir_path(dir.c_str()); + uint32_t free_clusters = 0, cluster_size = 0; + if ((fm->get_free(&dir_path, free_clusters, cluster_size) == FR_OK) && + (((uint64_t)free_clusters * cluster_size) < size)) { + return ERR_DISK_FULL; + } + fres = fm->fopen(full.c_str(), FA_CREATE_NEW | FA_READ | FA_WRITE, &f); + if ((fres == FR_OK) && (kind == e_image_dnp)) { + fres = f->seek(size); // the space is claimed; the image is not formatted + } else if (fres == FR_OK) { + uint8_t empty[256]; + memset(empty, 0, sizeof(empty)); + for (uint32_t done = 0; (done < size) && (fres == FR_OK); done += sizeof(empty)) { + uint32_t transferred; + fres = f->write(empty, sizeof(empty), &transferred); + } + } + } + + if ((fres == FR_OK) && (kind != e_image_dnp)) { + // The file system stack borrows f, so it goes out of scope before f is closed. + char volume[32]; + snprintf(volume, sizeof(volume), "%s,%s", label, id); + BlockDevice_File blk(f, 256); + Partition prt(&blk, 0, 0, 0); + switch (kind) { + case e_image_d71: { FileSystemD71 fs(&prt, true); fres = fs.format(volume); break; } + case e_image_d81: { FileSystemD81 fs(&prt, true); fres = fs.format(volume); break; } + default: { FileSystemD64 fs(&prt, true); fres = fs.format(volume); break; } + } + } + if (f) { + fm->fclose(f); + } + if (fres != FR_OK) { + drive->set_error_fres(fres); + } return 0; } @@ -1594,25 +2313,74 @@ int IecCommandChannel::do_rename(filename_t &src, filename_t &dest) { mstring works, workd; const char *src_path = ConstructPath(works, src, e_any, e_read); - FileInfo info(48); + FileInfo info(INFO_SIZE); FRESULT fres = src_path ? fm->fstat(src_path, info) : FR_NO_PATH; - if (fres != FR_OK) { + if (fres == FR_OK) { + use_found_name(works, info); + } else { GETPARTITION(src.partition, partition, 0); + // A subdirectory is renamed under its own name, so directories are matched + // as well as files (SI-074). fres = resolve_existing_iec_path(fm, partition, src, e_any, - false, true, src.has_wildcard, + true, true, src.has_wildcard, works, &info); - src_path = works.c_str(); } + src_path = works.c_str(); if (fres != FR_OK) { drive->set_error_fres(fres); return 0; } - // convert FAT name to CBM name + // convert FAT name to CBM name, or take it from an x00 header (SI-144) char cbm_name[24]; filetype_t ftype = e_any; - IecPartition::CreateIecName(&info, cbm_name, ftype); + bool wrapped = iec_x00_probe(fm, src_path, cbm_name, &ftype, NULL); + if (!wrapped) { + IecPartition::CreateIecName(&info, cbm_name, ftype); + } // ftype is now set to the type of the original file. + // The new name must not be taken by an entry of any type, unless it is the old name + // spelled in another case (SI-074). + GETPARTITION(dest.partition, dest_partition, 0); + mstring dest_dir; + if (resolve_directory_path(fm, dest_partition, dest.path, dest_dir) != FR_OK) { + return ERR_PARTITION_ERROR; + } + if (strcasecmp(cbm_name, dest.filename.c_str()) != 0) { + mstring taken; + if (find_rendered_iec_child(fm, dest_dir.c_str(), dest.filename.c_str(), e_any, + true, true, false, taken, NULL) == FR_OK) { + return ERR_FILE_EXISTS; + } + } + + // An x00 file keeps its host name and gets the new name in its header; into another + // directory it moves under that host name. + if (wrapped) { + File *file = NULL; + fres = fm->fopen(src_path, FA_READ | FA_WRITE, &file); + if (fres == FR_OK) { + char name[16]; + uint32_t tr; + memset(name, 0, sizeof(name)); + strncpy(name, dest.filename.c_str(), sizeof(name)); + fres = file->seek(8); + if (fres == FR_OK) { + fres = file->write(name, sizeof(name), &tr); + } + fm->fclose(file); + } + mstring moved(dest_dir.c_str()); + append_path_component(moved, strrchr(src_path, '/') + 1); + if ((fres == FR_OK) && strcmp(moved.c_str(), src_path)) { + fres = fm->rename(src_path, moved.c_str()); + } + if (fres != FR_OK) { + drive->set_error_fres(fres); + } + return 0; + } + const char *dest_path = ConstructPath(workd, dest, ftype, e_write); if (!dest_path) { return ERR_PARTITION_ERROR; @@ -1625,46 +2393,79 @@ int IecCommandChannel::do_rename(filename_t &src, filename_t &dest) return 0; } +// Scratches every file in a directory whose CBM name matches a pattern, and returns how +// many went. The names are collected before anything is deleted, so the directory is +// not changed while it is being read. The host name of a pattern escapes its wildcards +// (SI-142), so the pattern is matched here rather than by the host file system. +static int scratch_matching(FileManager *fm, const char *dir_path, const char *pattern) +{ + Directory *dir = NULL; + if (fm->open_directory(dir_path, &dir) != FR_OK) { + return 0; + } + IndexedList victims(8, NULL); + IndexedList locked(4, NULL); + FileInfo info(INFO_SIZE); + while (dir->get_entry(info) == FR_OK) { + if ((info.attrib & (AM_DIR | AM_VOL)) || !info.lfname[0]) { + continue; + } + // Inside a disk image an entry is found by its name with the type extension, + // which generate_fat_name() adds; on a host file system it is the name itself. + char entry[80]; + mstring *full = new mstring(dir_path); + append_path_component(*full, info.generate_fat_name(entry, sizeof(entry))); + // Locked files are not scratched (SI-076). A delete removes the first entry of a + // name, so an entry that follows a locked one of the same name, which a damaged + // disk image can have, is not scratched either. + bool behind_locked = false; + for (int i = 0; (i < locked.get_elements()) && !behind_locked; i++) { + behind_locked = (strcmp(locked[i]->c_str(), full->c_str()) == 0); + } + char cbm_name[24]; + filetype_t ftype = e_any; + iec_entry_name(fm, dir_path, &info, cbm_name, ftype); + if (info.attrib & AM_RDO) { + locked.append(full); + } else if (!behind_locked && pattern_match(pattern, cbm_name, false)) { + victims.append(full); + } else { + delete full; + } + } + delete dir; + + int scratched = 0; + for (int i = 0; i < victims.get_elements(); i++) { + if (fm->delete_file(victims[i]->c_str()) == FR_OK) { + scratched++; + } + delete victims[i]; + } + for (int i = 0; i < locked.get_elements(); i++) { + delete locked[i]; + } + return scratched; +} + +// Every name, with or without a pattern, is scratched through the directory scan, which +// removes each unlocked entry of that name once and then stops. Deleting the name until +// the file system refused, as this did before, depended on the refusal for termination +// and deleted a locked entry that followed an unlocked one (CR-8, SI-076). int IecCommandChannel::do_scratch(filename_t filenames[], int n) { DBGIECV("Scratch %d files:\n", n); mstring work; int scratched = 0; for(int i=0;idelete_file(fp); - if (fres == FR_OK) { - scratched ++; - scratched_this_file ++; - } - } while(fres == FR_OK); - } - if (!scratched_this_file && !filenames[i].has_wildcard && - (fres == FR_NO_FILE || fres == FR_NO_PATH)) { - GETPARTITION(filenames[i].partition, partition, 0); - fres = resolve_existing_iec_path(fm, partition, filenames[i], e_any, - false, true, false, work); - if (fres == FR_OK) { - DBGIECV(" %d. directory-assisted scratch %s\n", i, work.c_str()); - fres = fm->delete_file(work.c_str()); - if (fres == FR_OK) { - scratched ++; - } - } + GETPARTITION(filenames[i].partition, partition, 0); + if (resolve_directory_path(fm, partition, filenames[i].path, work) != FR_OK) { + drive->set_error(ERR_DIRECTORY_ERROR, partition->GetPartitionNumber(), 0); + return 0; } + scratched += scratch_matching(fm, work.c_str(), filenames[i].filename.c_str()); } - if (scratched == 0) { - return ERR_FILE_NOT_FOUND; - } + // Scratching nothing is not an error: the answer is 01 with a count of zero (SI-033). set_error(ERR_FILES_SCRATCHED, scratched); return 0; } @@ -1729,7 +2530,35 @@ int IecCommandChannel::do_set_position(int chan, uint32_t pos, int recnr, int re case e_buffer: return do_buffer_position(chan, pos); case e_file: - fres = channel->f->seek(pos); + if ((channel->name_to_open.access == e_write) || (channel->name_to_open.access == e_append)) { + // A channel that writes (SI-083): what it holds goes out at the old position, + // then the file moves, past its end if the medium can grow a file that way, and + // the next byte lands there. Nothing is read back, because the file is not open + // for reading. A medium that cannot put the file there is full, 72, which CBM + // DOS names, rather than 69 (SI-036). + if (channel->pointer > 0) { + uint32_t written; + fres = channel->f->write(channel->buffer, channel->pointer, &written); + if (fres != FR_OK) { + drive->set_error_fres(fres); + return 0; + } + channel->pointer = 0; + } + fres = channel->f->seek(pos); + if ((fres != FR_OK) || (channel->f->get_size() < pos)) { + if (pos > channel->f->get_size()) { + drive->set_error(ERR_DISK_FULL, 0, 0); + } else { + drive->set_error_fres(fres); + } + return 0; + } + drive->set_error(ERR_ALL_OK, 0, 0); + state = e_idle; + return 0; + } + fres = channel->f->seek(pos + channel->dataOffset); // past an x00 header if (fres != FR_OK) { drive->set_error_fres(fres); return 0; @@ -1766,31 +2595,66 @@ int IecCommandChannel::do_set_position(int chan, uint32_t pos, int recnr, int re int IecCommandChannel::do_get_partition_info(int part) { - IecPartition *p = drive->vfs->GetPartition(part); - buffer[30] = 0x0d; + // -1 is the current partition. 0 is the system partition, which this drive does not + // have, so it reads back as a partition that is not there, numbered 0 (SI-041). + IecPartition *p = (part == 0) ? NULL : drive->vfs->GetPartition(part); memset(buffer, 0, 30); + buffer[30] = 0x0d; + drive->set_error(0, 0, 0); + + // Byte 0 is the type, byte 1 is reserved and byte 2 is the partition number. A + // partition that does not exist is not an error: type 0 is what CMD DOS calls + // "not created", and the caller asked for exactly that answer. + buffer[2] = (part == 0) ? 0 : (uint8_t)drive->vfs->GetTargetPartitionNumber(part); if (p) { - drive->set_error(0, 0, 0); - buffer[1] = 1; - buffer[2] = (uint8_t)part; + buffer[0] = (uint8_t)iec_partition_type(fm, p); + // The name in bytes 3 to 18 is the one the partition directory shows, which + // is the partition's own name rather than the path it is rooted at. char cbm_name[24]; FileInfo info(40); filetype_t ftype = e_any; - strncpy(info.lfname, p->GetRootPath(), info.lfsize); + strncpy(info.lfname, p->GetName(), info.lfsize); + info.lfname[info.lfsize - 1] = 0; IecPartition::CreateIecName(&info, cbm_name, ftype); strncpy((char *)(buffer+3), cbm_name, 16); - buffer[27] = 0xFF; // for now always reporting 0xFF0000 as partition size - } else { - drive->set_error(77, part, 0); + + // Bytes 27 to 29, the size in 512 byte blocks, as the HD counts them, clamped to + // 24 bits: the image file for a partition rooted in a disk image, the volume for + // one rooted in a directory (SI-041, SD parse_getpartition()). + uint32_t blocks = 0; + FileInfo root(8); + if (fm->is_path_valid(p->GetRootPath(), &root) && root.fs && root.fs->supports_direct_sector_access()) { + mstring image(p->GetRootPath()); + const char *ip = image.c_str(); + if (image.length() && (ip[image.length() - 1] == '/')) { + mstring trimmed(ip, 0, image.length() - 2); + image = trimmed; + } + FileInfo file(8); + if (fm->fstat(image.c_str(), file) == FR_OK) { + blocks = (file.size + 511) / 512; + } + } else { + Path root_path(p->GetRootPath()); + uint32_t clusters = 0, cluster_size = 0; + if (fm->get_total(&root_path, clusters, cluster_size) == FR_OK) { + uint64_t total = ((uint64_t)clusters * cluster_size) / 512; + blocks = (total > 0xFFFFFF) ? 0xFFFFFF : (uint32_t)total; + } + } + buffer[27] = (uint8_t)(blocks >> 16); + buffer[28] = (uint8_t)(blocks >> 8); + buffer[29] = (uint8_t)blocks; } + // Thirty bytes of information plus the carriage return that ends the reply. last_byte = 30; pointer = 0; prefetch = 0; - prefetch_max = 30; + prefetch_max = 31; state = e_status; return 0; @@ -1819,10 +2683,39 @@ int IecCommandChannel::do_get_partition_info(int part) // Byte 30 - CHR$(13) } +// L[n][path]:name toggles the lock of the first file or directory whose CBM name matches +// (SI-076, HD 9-30). The entry is found through the directory, as a scratch finds it, so +// the name matches the entry a listing shows. +int IecCommandChannel::do_lock(filename_t& name) +{ + GETPARTITION(name.partition, partition, -1); + mstring work; + FileInfo info(INFO_SIZE); + FRESULT fres = resolve_existing_iec_path(fm, partition, name, e_any, true, true, true, work, &info); + if (fres == FR_OK) { + fres = fm->set_attributes(work.c_str(), info.attrib ^ AM_RDO, AM_RDO); + } + if (fres == FR_NOT_ENABLED) { + return ERR_SYNTAX_ERROR_GEN; // the medium has no lock + } + if (fres != FR_OK) { + drive->set_error_fres(fres); + } + return 0; +} + +// U0> (SI-100). The drive answers this command on the number it was addressed on and +// every later one on the new number. +int IecCommandChannel::do_set_device_number(int dev) +{ + drive->set_device_number(dev); + return 0; +} + int IecCommandChannel::ext_open_file(const char *filenameOrCommand) { - strncpy((char *) wr_buffer, filenameOrCommand, 63); - wr_buffer[63] = 0; + strncpy((char *) wr_buffer, filenameOrCommand, CBMDOS_COMMAND_BUFFER_SIZE - 1); + wr_buffer[CBMDOS_COMMAND_BUFFER_SIZE - 1] = 0; wr_pointer = strlen((char *) wr_buffer); push_command(0x60); return push_command(0x00); @@ -1847,17 +2740,18 @@ t_channel_retval IecCommandChannel::push_command(uint8_t b) wr_pointer = 0; break; case 0x00: // end of data, command received in buffer - // BASIC's PRINT# ends every command with a carriage return, which CBM DOS - // takes as the end of the command rather than as part of it. Only the last - // byte goes, so a command carrying binary parameters keeps them. - if (wr_pointer && (wr_buffer[wr_pointer - 1] == 0x0D)) { - wr_pointer--; - } wr_buffer[wr_pointer] = 0; if (wr_pointer) { drive->set_error(0, 0, 0); err = parser->execute_command(wr_buffer, wr_pointer); if (err) set_error(err); + if (drive_failed()) { + log_line("command failed", wr_buffer, wr_pointer, NULL, NULL, 0); + } else if (drive->log_every_operation()) { + // A command that answers with data, such as M-R or G-P, has it in the buffer. + bool reply = (state == e_status) && (last_byte >= 0) && (last_byte < 256); + log_line("command", wr_buffer, wr_pointer, reply ? "reply" : NULL, buffer, reply ? (last_byte + 1) : 0); + } } wr_pointer = 0; break; @@ -1874,6 +2768,7 @@ bool IecPartition::IsValid() void IecFileSystem :: LoadPartitions(const char *path, const char *file) { + IecDriveLock guard(drive); File *fi; FRESULT fres = fm->fopen(path, file, FA_READ, &fi); if (fres == FR_OK) { @@ -1884,6 +2779,7 @@ void IecFileSystem :: LoadPartitions(const char *path, const char *file) FRESULT IecFileSystem :: SavePartitions(const char *path, const char *filename) { + IecDriveLock guard(drive); File *fo; uint32_t tr; diff --git a/software/io/iec/iec_channel.h b/software/io/iec/iec_channel.h index d58b009f2..9847d950b 100644 --- a/software/io/iec/iec_channel.h +++ b/software/io/iec/iec_channel.h @@ -14,7 +14,9 @@ typedef enum _t_channel_state { } t_channel_state; -static uint8_t c_header[32] = { 1, 1, 4, 1, 0, 0, 18, 34, +// A listing is a BASIC program: load address $0401, then the header line with a link +// of $0101 (SI-130). +static uint8_t c_header[32] = { 1, 4, 1, 1, 0, 0, 18, 34, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 34, 32, 48, 48, 32, 50, 65, 0 }; @@ -23,6 +25,11 @@ class IecCommandChannel; #define MAX_PARTITIONS 256 +// x00 wrappers (SI-144): the header in front of the data of a P00, S00, U00 or R00 file. +#define X00_HEADER_SIZE 26 +bool iec_x00_probe(FileManager *fm, const char *path, char *cbm_name, filetype_t *type, uint8_t *record_length); +int iec_entry_name(FileManager *fm, const char *dir_path, FileInfo *info, char *cbm_name, filetype_t& type); + static inline bool is_valid_partition_number(int p) { return (p > 0) && (p < MAX_PARTITIONS); @@ -113,8 +120,17 @@ class IecPartition { memset(out, 0, 24); bool cutExtension = false; + // A CBM file system reports the directory entry's own type, which the extension + // cannot always carry: a GEOS file is given the extension CVT for the host file + // system while its type bits say SEQ, PRG or USR (SI-149). + static const filetype_t cbm_types[8] = { + e_any, e_seq, e_prg, e_usr, e_rel, e_any, e_folder, e_any + }; if (dir) { type = e_folder; + } else if (inf->cbm_filetype) { + type = cbm_types[inf->cbm_filetype & 7]; + cutExtension = true; } else if (strcmp(ext, "PRG") == 0) { type = e_prg; cutExtension = true; @@ -185,11 +201,15 @@ class IecFileSystem { } } + // The drive's lock (CR-6), which the menu's partition list also takes. + IecDrive *get_drive(void) { return drive; } + void add_partition(int p, const char *path, const char *name) { if (!is_valid_partition_number(p)) { return; } + IecDriveLock guard(drive); if (partitions[p]) { partitions[p]->SetName(name); partitions[p]->SetRoot(path); @@ -203,6 +223,7 @@ class IecFileSystem { if (!is_valid_partition_number(p)) { return; } + IecDriveLock guard(drive); if (partitions[p]) { delete partitions[p]; partitions[p] = NULL; @@ -248,6 +269,16 @@ class IecFileSystem { } } + int CountPartitions(void) { + int count = 0; + for(int i=1;iset_sort_order(SORT_ORDER_CFG_SOFTIEC); @@ -183,6 +191,28 @@ IecDrive :: ~IecDrive() intf->unregister_slave(slot_id); } +void IecDrive :: lock(void) +{ +#ifndef RUNS_ON_PC + xSemaphoreTakeRecursive(mutex, portMAX_DELAY); +#endif + lock_depth++; +} + +void IecDrive :: unlock(void) +{ + lock_depth--; +#ifndef RUNS_ON_PC + xSemaphoreGiveRecursive(mutex); +#endif +} + +// How deep the holder of the drive's lock is, 0 when nobody holds it; for the tests. +int iec_drive_lock_depth(IecDrive *drive) +{ + return drive->lock_depth; +} + IecCommandChannel *IecDrive :: get_command_channel(void) { return (IecCommandChannel *)channels[15]; @@ -195,12 +225,20 @@ IecChannel *IecDrive :: get_data_channel(int chan) void IecDrive :: effectuate_settings(void) { - my_bus_id = cfg->get_value(CFG_IEC_BUS_ID); + IecDriveLock guard(this); // configure() holds the IEC processor in reset (CR-6) + int bus_id = cfg->get_value(CFG_IEC_BUS_ID); + bool enabled = cfg->get_value(CFG_IEC_ENABLE) != 0; + // Holding the processor in reset drops a transfer on the bus, so a change of Log Every + // Operation alone, which is read where it is used, leaves the processor running. + bool reconfigure = (bus_id != my_bus_id) || (enabled != enable); + my_bus_id = bus_id; cmd_if.set_kernal_device_id(my_bus_id); - - enable = uint8_t(cfg->get_value(CFG_IEC_ENABLE)); - intf->configure(); + enable = enabled; + + if (reconfigure) { + intf->configure(); + } } void IecDrive :: create_task_items(void) @@ -244,15 +282,13 @@ SubsysResultCode_e IecDrive :: executeCommand(SubsysCommand *cmd) switch(cmd->functionID) { case MENU_IEC_ON: - enable = 1; - cfg->set_value(CFG_IEC_ENABLE, enable); - intf->configure(); - break; - case MENU_IEC_OFF: - enable = 0; + case MENU_IEC_OFF: { + IecDriveLock guard(this); + enable = (cmd->functionID == MENU_IEC_ON) ? 1 : 0; cfg->set_value(CFG_IEC_ENABLE, enable); intf->configure(); break; + } case MENU_IEC_RESET: reset(); break; @@ -262,6 +298,7 @@ SubsysResultCode_e IecDrive :: executeCommand(SubsysCommand *cmd) form_fields->set("Path", cmd->path.c_str()); form_fields->set("Number", vfs->GetUnusedPartition()); + // The form waits for the user, so the lock is only taken for the change itself. if (form_new_partition(cmd->user_interface, form_fields) == MENU_DONE) { vfs->add_partition(form_fields->int_or("Number", 99), form_fields->string_or("Path", "/"), form_fields->string_or("Name", "NO NAME")); } @@ -291,6 +328,7 @@ SubsysResultCode_e IecDrive :: executeCommand(SubsysCommand *cmd) void IecDrive :: reset(void) { + IecDriveLock guard(this); effectuate_registered_settings(); for(int i=0; i < 16; i++) { channels[i]->reset(); @@ -310,16 +348,19 @@ void IecDrive :: reset(void) t_channel_retval IecDrive :: prefetch_data(uint8_t& data) { + IecDriveLock guard(this); return channels[current_channel]->prefetch_data(data); } t_channel_retval IecDrive :: prefetch_more(int bufsize, uint8_t*&pointer, int &available) { + IecDriveLock guard(this); return channels[current_channel]->prefetch_more(bufsize, pointer, available); } t_channel_retval IecDrive :: push_ctrl(uint16_t ctrl) { + IecDriveLock guard(this); switch(ctrl) { case SLAVE_CMD_ATN: current_channel = 0; @@ -338,29 +379,49 @@ t_channel_retval IecDrive :: push_ctrl(uint16_t ctrl) t_channel_retval IecDrive :: push_data(uint8_t data) { + IecDriveLock guard(this); return channels[current_channel]->push_data(data); } t_channel_retval IecDrive :: pop_data(void) { + IecDriveLock guard(this); return channels[current_channel]->pop_data(); } t_channel_retval IecDrive :: pop_more(int byte_count) { + IecDriveLock guard(this); return channels[current_channel]->pop_more(byte_count); } void IecDrive :: talk(void) { + IecDriveLock guard(this); channels[current_channel]->talk(); } +// Whether every command, open and close is logged, and not only the failures (iec_log.h). +bool IecDrive :: log_every_operation(void) +{ + return cfg->get_value(CFG_IEC_LOG) > 0; +} + +// The device number for as long as the drive runs, from U0> (SI-100). It is not written to +// the configuration: HD 9-49 describes the change as temporary. +void IecDrive :: set_device_number(int dev) +{ + my_bus_id = dev; + cmd_if.set_kernal_device_id(my_bus_id); + intf->readdress(slot_id); +} + // called from IEC task, statically void IecDrive :: set_iec_dir(IecSlave *sl, void *data) { IecDrive *drive = (IecDrive *)sl; struct set_part_t *pd = (struct set_part_t *)data; + IecDriveLock guard(drive); IecPartition *p = drive->vfs->GetPartition(pd->partition); if (!p) { drive->vfs->add_partition(pd->partition, pd->path, pd->name); @@ -381,6 +442,7 @@ const char *IecDrive :: get_partition_dir(int p) void IecDrive :: add_partition(int p, const char *path, const char *name) { + IecDriveLock guard(this); vfs->add_partition(p, path, name); } @@ -462,6 +524,7 @@ int IecDrive ::get_error_string(char *buffer) void IecDrive :: info(StreamTextLog &b) { + IecDriveLock guard(this); char buffer[64]; if(enable) { iec_drive->get_error_string(buffer); @@ -478,6 +541,7 @@ void IecDrive :: info(StreamTextLog &b) void IecDrive :: info(JSON_Object *obj) { + IecDriveLock guard(this); char buffer[64]; int len = iec_drive->get_error_string(buffer); if (len) { @@ -499,6 +563,7 @@ void IecDrive :: info(JSON_Object *obj) void IecDrive :: load_partitions(const char *p, const char *f) { + IecDriveLock guard(this); vfs->LoadPartitions(p, f); } diff --git a/software/io/iec/iec_drive.h b/software/io/iec/iec_drive.h index 34861c293..8d9eaa1d8 100644 --- a/software/io/iec/iec_drive.h +++ b/software/io/iec/iec_drive.h @@ -51,6 +51,14 @@ class IecDrive : public IecSlave, SubSystem, ObjectWithMenu, ConfigurableObject } myActions; JSON_Object *form_fields; + + // CR-6: the IEC task, the GUI, the REST server and the UCI target all reach the channels + // and the partitions. Each entry point holds this recursive lock while it does, and + // lock_depth counts how deep the holder is. +#ifndef RUNS_ON_PC + SemaphoreHandle_t mutex; +#endif + int lock_depth; public: IecDrive(); virtual ~IecDrive(); @@ -85,6 +93,8 @@ class IecDrive : public IecSlave, SubSystem, ObjectWithMenu, ConfigurableObject t_channel_retval pop_more(int); // Local Functions + void set_device_number(int dev); + bool log_every_operation(void); void set_error(int err, int track, int sector); void set_error_fres(FRESULT fres); @@ -96,8 +106,21 @@ class IecDrive : public IecSlave, SubSystem, ObjectWithMenu, ConfigurableObject void add_partition(int p, const char *path, const char *name); void load_partitions(const char *p, const char *f); + void lock(void); + void unlock(void); + friend class IecChannel; friend class IecCommandChannel; + friend int iec_drive_lock_depth(IecDrive *drive); +}; + +// Holds a drive's lock for as long as it is in scope. +class IecDriveLock +{ + IecDrive *drive; +public: + IecDriveLock(IecDrive *d) : drive(d) { drive->lock(); } + ~IecDriveLock() { drive->unlock(); } }; #define ERR_ALL_OK 00 @@ -120,6 +143,8 @@ class IecDrive : public IecSlave, SubSystem, ObjectWithMenu, ConfigurableObject #define ERR_FILE_NOT_FOUND 62 #define ERR_FILE_EXISTS 63 #define ERR_FILE_TYPE_MISMATCH 64 +#define ERR_NO_BLOCK 65 +#define ERR_ILLEGAL_TRACK_SECTOR 66 #define ERR_FRESULT_CODE 69 #define ERR_NO_CHANNEL 70 #define ERR_DIRECTORY_ERROR 71 diff --git a/software/io/iec/iec_interface.cc b/software/io/iec/iec_interface.cc index e5f27c6e1..271f0dea7 100644 --- a/software/io/iec/iec_interface.cc +++ b/software/io/iec/iec_interface.cc @@ -2,6 +2,9 @@ #include "json.h" #include "dump_hex.h" +// How long a JiffyDOS talk waits for the host to take a byte before the pass ends. +#define JIFFY_SPIN_TICKS (configTICK_RATE_HZ / 10) + IecInterface *iec_if = NULL; IecInterface *IecInterface :: get_iec_interface(void) @@ -144,6 +147,17 @@ void IecInterface :: configure(void) } } +// Writes one slave's device number into the processor, for a number that changes +// while the drive is in use (U0>). Unlike configure(), the processor is not held +// in reset, because the command that asks for this is still on the bus. +void IecInterface :: readdress(int slot) +{ + if ((slot < 0) || (slot >= MAX_SLOTS) || !slaves[slot] || !slaves[slot]->is_enabled()) { + return; + } + set_slot_devnum(slot, slaves[slot]->get_address()); +} + void IecInterface :: reset(void) { HW_IEC_RESET_ENABLE = 0; @@ -172,12 +186,25 @@ void IecInterface :: task() gotSomething = xQueueReceive(queueToIec, &closure, 2); // here is the vTaskDelay(2) that used to be here + // A closure runs before the slaves are locked, because it can run for long, as a warp + // copy does, and must not keep other tasks from a drive meanwhile. if (gotSomething == pdTRUE) { if (closure.func) { closure.func(closure.obj, closure.data); } } + // The slaves are locked for one pass over the bus, so the drive's own entry points, + // which lock again for every byte, only count up and down (CR-6). The pass unlocks + // exactly the slaves it locked. + IecSlave *locked[MAX_SLOTS]; + for (int i = 0; i < MAX_SLOTS; i++) { + locked[i] = slaves[i]; + if (locked[i]) { + locked[i]->lock(); + } + } + uint8_t a; for (int loopcnt = 0; loopcnt < 500; loopcnt++) { a = HW_IEC_RX_FIFO_STATUS; @@ -281,9 +308,15 @@ void IecInterface :: task() if(talking) { while(1) { if (jiffy_load) { - // Simply spin while fifo is full - while(HW_IEC_TX_FIFO_STATUS & IEC_FIFO_FULL) + // Spin while the fifo is full, which does not last while the host takes + // the bytes. A host that stops taking them must not hold this task, and + // the slaves' locks, for ever: the pass then ends, as for a normal talk. + TickType_t spin_start = xTaskGetTickCount(); + while ((HW_IEC_TX_FIFO_STATUS & IEC_FIFO_FULL) && + ((xTaskGetTickCount() - spin_start) < JIFFY_SPIN_TICKS)) ; + if (HW_IEC_TX_FIFO_STATUS & IEC_FIFO_FULL) + break; } else { // Exit loop when fifo is full if(HW_IEC_TX_FIFO_STATUS & IEC_FIFO_FULL) @@ -332,6 +365,12 @@ void IecInterface :: task() jiffy_load = false; } } + + for (int i = MAX_SLOTS - 1; i >= 0; i--) { + if (locked[i]) { + locked[i]->unlock(); + } + } } } diff --git a/software/io/iec/iec_interface.h b/software/io/iec/iec_interface.h index 906ea3560..ecfc8afe2 100644 --- a/software/io/iec/iec_interface.h +++ b/software/io/iec/iec_interface.h @@ -125,6 +125,10 @@ class IecSlave virtual t_channel_retval pop_data(void) { return IEC_OK; } virtual t_channel_retval pop_more(int) { return IEC_OK; } virtual void talk(void) { } + // Held by the IEC task while it serves the bus, so a slave shared with other tasks can + // exclude them (CR-6). + virtual void lock(void) { } + virtual void unlock(void) { } }; typedef void (*iec_callback_t)(IecSlave *obj, void *data); @@ -171,6 +175,7 @@ class IecInterface void unregister_slave(int slot); void configure(void); void reset(void); + void readdress(int slot); // Slave Info static void info(StreamTextLog &b); diff --git a/software/io/iec/iec_log.h b/software/io/iec/iec_log.h new file mode 100644 index 000000000..2e76c5fa9 --- /dev/null +++ b/software/io/iec/iec_log.h @@ -0,0 +1,90 @@ +/* + * iec_log.h - the Software IEC log. + * + * The drive always writes one line for a command channel command that leaves an error, for + * an open that fails, and for the first failure of a channel. With the setting "Log Every + * Operation" in the Software IEC settings on, it also writes one line for every other + * command, open and close, with the reply of a command that answers with data, the host + * file an open reached or the first bytes of a listing, and the last line of a listing. + * Each line starts with SOFTIEC_LOG_PREFIX and carries the bytes the host sent, the current + * partition and directory, and the error channel's answer, and ends in " #" and a sequence + * number that counts every line, so what a program does can be + * followed in a device log without a special build. Bytes are never logged per bus byte. + * + * The formatter below takes an explicit length and never treats IEC data as a C string, + * so an embedded zero, a carriage return and a shifted PETSCII character all survive + * into the log and stay distinguishable from each other. + */ +#ifndef IEC_LOG_H +#define IEC_LOG_H + +#include + +// Shared by every line. Grep for it in a device log. +#define SOFTIEC_LOG_PREFIX "SoftIEC: " + +// The command buffer and a file name hold up to 254 bytes, more than a log line should +// carry, so a payload is rendered up to this many bytes; a longer one is cut, the cut is +// marked with "..", and the line still reports the real length (SI-152). +#define SOFTIEC_LOG_MAX_BYTES 64 + +// Room a caller has to provide for the rendering of SOFTIEC_LOG_MAX_BYTES. +#define SOFTIEC_LOG_TEXT_SIZE (4 * SOFTIEC_LOG_MAX_BYTES + 4) + +static const char softiec_log_digits[] = "0123456789ABCDEF"; + +// Renders len bytes as readable text. A printable ASCII byte stands for itself; a +// carriage return, a line feed and a zero get the usual short escapes, and every +// other byte, which includes shifted PETSCII and binary parameters, is written as +// \xNN. Writes at most out_size - 1 characters and always terminates. A rendering that +// did not fit ends in ".." so a reader can tell a short line from a short payload. +// Returns the number of characters written, not counting the terminator. +static inline int softiec_log_text(const uint8_t *data, int len, char *out, int out_size) +{ + int w = 0; + if (!out || (out_size < 1)) { + return 0; + } + out[0] = 0; + if (!data || (len < 0)) { + return 0; + } + for (int i = 0; i < len; i++) { + uint8_t b = data[i]; + char esc[4]; + int n = 0; + switch (b) { + case 0x00: esc[0] = '\\'; esc[1] = '0'; n = 2; break; + case 0x0A: esc[0] = '\\'; esc[1] = 'n'; n = 2; break; + case 0x0D: esc[0] = '\\'; esc[1] = 'r'; n = 2; break; + case '"': esc[0] = '\\'; esc[1] = '"'; n = 2; break; + case '\\': esc[0] = '\\'; esc[1] = '\\'; n = 2; break; + default: + if ((b >= 0x20) && (b < 0x7F)) { + esc[0] = (char)b; + n = 1; + } else { + esc[0] = '\\'; + esc[1] = 'x'; + esc[2] = softiec_log_digits[(b >> 4) & 15]; + esc[3] = softiec_log_digits[b & 15]; + n = 4; + } + break; + } + if ((w + n) >= (out_size - 2)) { + if ((w + 2) < out_size) { + out[w++] = '.'; + out[w++] = '.'; + } + break; + } + for (int k = 0; k < n; k++) { + out[w++] = esc[k]; + } + } + out[w] = 0; + return w; +} + +#endif /* IEC_LOG_H */ diff --git a/software/io/iec/iec_ui.h b/software/io/iec/iec_ui.h index aedc37b47..2bf6604d8 100644 --- a/software/io/iec/iec_ui.h +++ b/software/io/iec/iec_ui.h @@ -53,6 +53,7 @@ class BrowsableIecPartitions : public Browsable void setBrowser(TreeBrowser *tb) { browser = tb; } IndexedList *getSubItems(int &error) { error = 0; + IecDriveLock guard(vfs->get_drive()); // the names are copied under the drive's lock (CR-6) for(int i=1; iGetPartition(i); if (p) { diff --git a/software/io/stream/stream_textlog.h b/software/io/stream/stream_textlog.h index 4b191a6fb..2350bacc7 100644 --- a/software/io/stream/stream_textlog.h +++ b/software/io/stream/stream_textlog.h @@ -45,10 +45,15 @@ class StreamTextLog } } + // Every task that prints writes here, and nothing locks it. The position is read once + // and checked before it is used, so two writers can lose a character to each other but + // cannot write outside the buffer, however they interleave. void charout(int c) { - if (offset >= size) { - offset = 0; // clear! + int o = offset; + if ((o < 0) || (o >= size)) { + o = 0; // clear! } + offset = o; if (!enabled) { return; } @@ -59,7 +64,8 @@ class StreamTextLog } else if ((c < 32) && (c != 10) && (c != 13)) { return; } - buffer[offset++] = (char)c; + buffer[o] = (char)c; + offset = o + 1; } void raw(const char *data) { diff --git a/software/network/syslog.cc b/software/network/syslog.cc index de8f70487..28f70e54a 100644 --- a/software/network/syslog.cc +++ b/software/network/syslog.cc @@ -65,18 +65,20 @@ void Syslog::charout(int c) if (c == '\r') { return; } + // Tasks print concurrently, so the position is tested and used inside one safe section; + // tested outside it, another writer could move it past the end between test and store. + ENTER_SAFE_SECTION; if (bufpos < bufsize) { buf[bufpos] = (char)c; - ENTER_SAFE_SECTION; if (c == '\n') { newlinepos = bufpos; } ++bufpos; - LEAVE_SAFE_SECTION; } else { overflow = true; } + LEAVE_SAFE_SECTION; } void Syslog::syslogTask(void *arg) diff --git a/software/test/iecdrive/d64.cc b/software/test/iecdrive/d64.cc index 89efb3043..9ae95fd92 100644 --- a/software/test/iecdrive/d64.cc +++ b/software/test/iecdrive/d64.cc @@ -130,3 +130,88 @@ void create_iec_d64_fixture(const char *path) } + +// A D64 holding GEOS files, for SI-149. A GEOS file is an ordinary directory entry +// whose type bits say SEQ, PRG or USR, with the info block pointer at offset $15 and +// the file structure at offset $17 filled in as well. The image also holds a plain PRG +// so that the two cases can be compared. +static void d64_make_geos(uint8_t *disk, int dir_index, int info_track, int info_sector, + uint8_t structure) +{ + uint8_t *entry = d64_sector(disk, 18, 1) + 32 * dir_index; + entry[0x15] = (uint8_t)info_track; + entry[0x16] = (uint8_t)info_sector; + entry[0x17] = structure; // 0 is sequential, 1 is VLIR + entry[0x18] = 6; // GEOS file type +} + +void create_iec_geos_fixture(const char *path) +{ + const char *testname = "create_iec_geos_fixture"; + uint8_t *disk = new uint8_t[D64_SIZE]; + memset(disk, 0, D64_SIZE); + + uint8_t *bam = d64_sector(disk, 18, 0); + bam[0] = 18; + bam[1] = 1; + bam[2] = 0x41; + bam[3] = 0x00; + for (int track = 1; track <= D64_TRACKS; track++) { + uint8_t *entry = bam + 4 * track; + entry[0] = (uint8_t)D64_SECTORS_PER_TRACK[track]; + entry[1] = entry[2] = entry[3] = 0; + for (int sector = 0; sector < D64_SECTORS_PER_TRACK[track]; sector++) { + entry[1 + (sector >> 3)] |= (uint8_t)(1 << (sector & 7)); + } + } + memset(bam + 144, 0xA0, 27); + memcpy(bam + 144, "GEOS TEST", 9); + bam[144 + 21] = '2'; + bam[144 + 22] = 'A'; + d64_set_allocated(bam, 18, 0); + d64_set_allocated(bam, 18, 1); + + uint8_t *dir = d64_sector(disk, 18, 1); + dir[0] = 0; + dir[1] = 0xFF; + + static const uint8_t geosprg[] = "GEOSPRG"; + static const uint8_t geosseq[] = "GEOSSEQ"; + static const uint8_t geosusr[] = "GEOSUSR"; + static const uint8_t plainprg[] = "PLAINPRG"; + + // A load address of $0801 in front, so that the PRG case is one a C64 could run. + d64_add_file(disk, 0, geosprg, sizeof(geosprg) - 1, 2, 17, 0, "\x01\x08GEOS:PRG"); + d64_add_file(disk, 1, geosseq, sizeof(geosseq) - 1, 1, 17, 1, "GEOS:SEQ"); + d64_add_file(disk, 2, geosusr, sizeof(geosusr) - 1, 3, 17, 2, "GEOS:VLIR"); + d64_add_file(disk, 3, plainprg, sizeof(plainprg) - 1, 2, 17, 3, "\x01\x08PLAIN:PRG"); + + // One info block, shared by the three GEOS entries. Its first byte is the $03 an + // info block carries; the rest only has to be recognisable in a CVT stream. + uint8_t *info = d64_sector(disk, 17, 10); + info[0] = 0; + info[1] = 0xFF; + info[2] = 0x03; + memcpy(info + 4, "INFO BLOCK", 10); + d64_set_allocated(bam, 17, 10); + + d64_make_geos(disk, 0, 17, 10, 0); + d64_make_geos(disk, 1, 17, 10, 0); + d64_make_geos(disk, 2, 17, 10, 1); + + // The VLIR entry points at a record block, not at a chain of data. A drive hands + // that block over as it stands, so it is a full sector. + uint8_t *records = d64_sector(disk, 17, 2); + memset(records, 0, 256); + records[0] = 0; + records[1] = 0xFF; + records[2] = 17; // record 0 lives at 17:11 + records[3] = 11; + memcpy(records + 4, "VLIR", 4); + + FILE *f = fopen(path, "wb"); + REQUIRE(f != NULL); + REQUIRE(fwrite(disk, 1, D64_SIZE, f) == D64_SIZE); + REQUIRE(fclose(f) == 0); + delete[] disk; +} diff --git a/software/test/iecdrive/macros.h b/software/test/iecdrive/macros.h index 27e53b95a..58b53fb77 100644 --- a/software/test/iecdrive/macros.h +++ b/software/test/iecdrive/macros.h @@ -4,6 +4,7 @@ bool require_ok = (expr); \ if (!require_ok) { \ printf("%s: ASSERT FAILED %s:%d: %s\n", testname, __FILE__, __LINE__, #expr); \ + fflush(stdout); /* the abort below discards what stdout still buffers */ \ } \ assert(require_ok); \ } while (0) diff --git a/software/test/iecdrive/testdrive.cc b/software/test/iecdrive/testdrive.cc index 63b2af26a..192c0c531 100644 --- a/software/test/iecdrive/testdrive.cc +++ b/software/test/iecdrive/testdrive.cc @@ -4,6 +4,8 @@ #include "file_device.h" #include "filesystem_fat.h" #include "macros.h" +#include +#include void outbyte(int c) { putc(c, stdout); } CommandInterface cmd_if; @@ -14,9 +16,11 @@ FileDevice *ramdisk_node; BlockDevice *flashdisk_blk; FileDevice *flashdisk_node; -char last_status[128]; +char last_status[300]; // a status, or a binary reply of up to 256 bytes +int negative_fetches = 0; // prefetch_more offering fewer than zero bytes, which a real reader copies int last_status_size; void create_iec_d64_fixture(const char *path); +void create_iec_geos_fixture(const char *path); void execute_suite12(FileManager *fm); void create_iec_d81_fixture(const char *path); FRESULT copy_to(const char *from, const char *to); @@ -216,11 +220,13 @@ static void open_buffer_channel(const char *testname, IecDrive *dr, uint8_t chan static void read_buffer_channel(const char *testname, IecDrive *dr, uint8_t chan, uint8_t *buffer, int len); +// U1 and U2 move whole blocks; B-R and B-W use the first byte as a length (SI-094). The +// partition number is ignored: the channel uses the partition current at its open (SI-093). static void capture_block_sector(const char *testname, IecDrive *dr, uint8_t chan, int part, int track, int sector, uint8_t *out) { char cmd[64]; - snprintf(cmd, sizeof(cmd), "B-R %u %d %d %d", chan, part, track, sector); + snprintf(cmd, sizeof(cmd), "U1 %u %d %d %d", chan, part, track, sector); expect_command_ok(testname, dr, cmd); read_buffer_channel(testname, dr, chan, out, 256); } @@ -241,7 +247,7 @@ static void expect_buffer_sector(const char *testname, IecDrive *dr, uint8_t cha int part, int track, int sector, const uint8_t *expected) { char cmd[64]; - snprintf(cmd, sizeof(cmd), "B-R %u %d %d %d", chan, part, track, sector); + snprintf(cmd, sizeof(cmd), "U1 %u %d %d %d", chan, part, track, sector); expect_command_ok(testname, dr, cmd); uint8_t actual[256]; read_buffer_channel(testname, dr, chan, actual, sizeof(actual)); @@ -256,10 +262,10 @@ static void expect_block_write_sector(const char *testname, IecDrive *dr, uint8_ int part, int track, int sector, const uint8_t *payload) { char cmd[64]; - snprintf(cmd, sizeof(cmd), "B-W %u %d %d %d", chan, part, track, sector); + snprintf(cmd, sizeof(cmd), "U2 %u %d %d %d", chan, part, track, sector); expect_command_ok(testname, dr, cmd); uint8_t actual[256]; - snprintf(cmd, sizeof(cmd), "B-R %u %d %d %d", chan, part, track, sector); + snprintf(cmd, sizeof(cmd), "U1 %u %d %d %d", chan, part, track, sector); expect_command_ok(testname, dr, cmd); read_buffer_channel(testname, dr, chan, actual, sizeof(actual)); if (memcmp(actual, payload, sizeof(actual)) != 0) { @@ -274,7 +280,7 @@ static void expect_bam_sector_state(const char *testname, IecDrive *dr, uint8_t bool expect_allocated, int expected_free_delta) { char cmd[64]; - snprintf(cmd, sizeof(cmd), "B-R %u %d %d %d", chan, c.partition, c.bam_track, c.bam_sector); + snprintf(cmd, sizeof(cmd), "U1 %u %d %d %d", chan, c.partition, c.bam_track, c.bam_sector); expect_command_ok(testname, dr, cmd); uint8_t now[256]; read_buffer_channel(testname, dr, chan, now, sizeof(now)); @@ -361,10 +367,38 @@ void create_file(const char *filename, int blocks) } #include "blockdev_emul.h" +#include "stream_textlog.h" +#include + +// The FAT file, which also tells Suite11-CR6-Lock whether a watched drive held its lock +// when one of its entry points reached storage. +extern IecDrive *s11_lock_watch; +extern int s11_lock_watch_locked; +extern int s11_lock_watch_unlocked; +extern int iec_drive_lock_depth(IecDrive *drive) __attribute__((weak)); +class LockWatchingBlockDevice : public BlockDevice_Emulated +{ + void note(void) + { + if (!s11_lock_watch) { + return; + } + if (iec_drive_lock_depth && iec_drive_lock_depth(s11_lock_watch)) { + s11_lock_watch_locked++; + } else { + s11_lock_watch_unlocked++; + } + } +public: + LockWatchingBlockDevice(const char *name, int sec_size) : BlockDevice_Emulated(name, sec_size) { } + DRESULT read(uint8_t *buf, uint32_t sector, int count) { note(); return BlockDevice_Emulated::read(buf, sector, count); } + DRESULT write(const uint8_t *buf, uint32_t sector, int count) { note(); return BlockDevice_Emulated::write(buf, sector, count); } +}; + void init_fat_file() { - create_file("format.fat", 16*1024); // 4 MB: room for the images Suite10 mounts - static BlockDevice_Emulated blk("format.fat", 512); + create_file("format.fat", 64*1024); // 16 MB: room for the images Suite10 and Suite11 create + static LockWatchingBlockDevice blk("format.fat", 512); static Partition prt(&blk, 0, 0, 0); static FileSystemFAT fs(&prt); fs.format("GIDEON"); @@ -484,6 +518,11 @@ int read_file(IecDrive *dr, uint8_t chan, uint8_t *out, int len) while(len > 0) { ret = dr->prefetch_more(256, data, data_size); // printf("Ret: %d Count = %d\n", ret, data_size); + if (data_size < 0) { + printf("TESTDRIVE: channel %u prefetch_more offered %d bytes\n", chan, data_size); + negative_fetches++; + break; + } if (data_size == 0) { break; } @@ -518,6 +557,11 @@ int read_file_limited(IecDrive *dr, uint8_t chan, uint8_t *out, int len) int total_read = 0; while(len > 0) { ret = dr->prefetch_more(len, data, data_size); + if (data_size < 0) { + printf("TESTDRIVE: channel %u prefetch_more offered %d bytes\n", chan, data_size); + negative_fetches++; + break; + } if (data_size == 0) { break; } @@ -632,6 +676,21 @@ static void expect_command_ok(const char *testname, IecDrive *dr, const char *cm expect_command_response(testname, dr, cmd, "00, OK,00,00\r"); } +// The same, for a command whose parameters are binary and so cannot be a C string. +static void send_command_data(IecDrive *dr, const uint8_t *data, int len); + +static void expect_command_data_response(const char *testname, IecDrive *dr, + const uint8_t *cmd, int len, const char *expected) +{ + send_command_data(dr, cmd, len); + get_status(dr); + if (strcmp(last_status, expected) != 0) { + printf("%s: response was '%s', expected '%s'\n", testname, last_status, expected); + dump_hex_relative(cmd, len); + } + REQUIRE(strcmp(last_status, expected) == 0); +} + static void expect_command_bytes(const char *testname, IecDrive *dr, const char *cmd, const uint8_t *expected, int expected_len) { @@ -1025,7 +1084,7 @@ static void run_iec_partition3_sequence(IecDrive *dr, const char *label) expect_command_response("TEST13", dr, "CP3", "02,PARTITION SELECTED,03,00\r"); expect_command_response("TEST14", dr, "XPWD", "3:/"); expect_command_response("TEST15", dr, "T-RI", "2025-06-26T00:41:01 WED\r"); - expect_command_response("TEST16", dr, "C3:BAD=", "32,SYNTAX ERROR,00,00\r"); + expect_command_response("TEST16", dr, "C3:BAD=", "34,SYNTAX ERROR,00,00\r"); expect_command_ok("TEST17", dr, "C3:COMBO=3:BASIC,3:LITERAL"); expect_iec_file("TEST18", dr, 0, "3:COMBO", "BASIC:PRGLITERAL:PRG"); @@ -1306,7 +1365,10 @@ void execute_suite6(FileManager *fm, IecDrive *dr) expect_command_ok("Suite6-MDRenderedParentPath", dr, "MD6/PARENT:CHILD"); expect_command_ok("Suite6-CDRenderedParentCreatedChild", dr, "CD6/PARENT/CHILD"); expect_command_ok("Suite6-CDRootAfterMD", dr, "CD6//"); - expect_command_ok("Suite6-RDRenderedParentPath", dr, "RD6/PARENT:CHILD"); + // RD takes no path (SI-063), so the parent is entered first. + expect_command_ok("Suite6-CDRenderedParentForRD", dr, "CD6/PARENT"); + expect_command_ok("Suite6-RDRenderedParentPath", dr, "RD6:CHILD"); + expect_command_ok("Suite6-CDRootAfterRD", dr, "CD6//"); expect_command_ok("Suite6-RDRenderedFinalDirectory", dr, "RD6:RDIR"); expect_command_ok("Suite6-CopyRenderedSource", dr, "C6:COPYDST=6:COPYSRC"); @@ -1339,7 +1401,7 @@ void execute_suite7(FileManager *fm, IecDrive *dr) expect_iec_open_status_prefix("Suite7-OpenBadModifier", dr, 0, "7:BAD,X", "30,SYNTAX ERROR"); expect_iec_open_status_prefix("Suite7-OpenBadRecordType", dr, 0, "7:BAD,P,L", "30,SYNTAX ERROR"); - expect_iec_open_status_prefix("Suite7-OpenMalformedReplace", dr, 0, "@345:", "32,SYNTAX ERROR"); + expect_iec_open_status_prefix("Suite7-OpenMalformedReplace", dr, 0, "@345:", "34,SYNTAX ERROR"); expect_iec_open_status_prefix("Suite7-OpenMalformedDollar", dr, 0, "$", "00"); //expect_iec_open_status_prefix("Suite7-OpenMalformedHash", dr, 0, "#", "30,SYNTAX ERROR"); @@ -1370,7 +1432,9 @@ static void run_suite8_control_plane(FileManager *fm, IecDrive *dr) expect_command_response("Suite8-CP1", dr, "CP1", "02,PARTITION SELECTED,01,00\r"); expect_command_response("Suite8-CD-TEMP", dr, "CD/TEMP", "71,DIRECTORY ERROR,01,00\r"); expect_command_ok("Suite8-CD-SOMEDIR", dr, "CD/SOMEDIR"); - expect_command_ok("Suite8-CD-PARENT-OTHERDIR", dr, "CD/_/OTHERDIR"); + // Up and down again in one command is spelled with .., because a left arrow in a + // path component is a directory name (SI-014). + expect_command_ok("Suite8-CD-PARENT-OTHERDIR", dr, "CD/../OTHERDIR"); expect_command_ok("Suite8-CD-LEVEL2", dr, "CD:LEVEL2"); expect_command_ok("Suite8-CD-ROOT", dr, "CD//"); expect_command_ok("Suite8-CD-ABS-LEVEL2", dr, "CD/OTHERDIR/LEVEL2"); @@ -1405,7 +1469,7 @@ static void run_suite8_time_copy_rename_scratch(IecDrive *dr) expect_command_bytes("Suite8-T-RD", dr, "T-RD", t_rd, sizeof(t_rd)); expect_command_bytes("Suite8-T-RB", dr, "T-RB", t_rb, sizeof(t_rb)); - expect_command_response("Suite8-COPY-MISSING-SOURCE", dr, "C2:DEST=", "32,SYNTAX ERROR,00,00\r"); + expect_command_response("Suite8-COPY-MISSING-SOURCE", dr, "C2:DEST=", "34,SYNTAX ERROR,00,00\r"); expect_command_ok("Suite8-COPY-A-BB", dr, "C2:DEST=1:A,1:BB"); expect_iec_file("Suite8-COPY-DEST", dr, 0, "2:DEST", "This is really a silly test.This is really a silly test."); @@ -1455,7 +1519,7 @@ static void run_suite8_partition_listing(FileManager *fm, IecDrive *dr) expect_command_ok("Suite8-CD-SUBDIR", dr, "CD/Subdir"); expect_command_response("Suite8-XPWD-SUBDIR", dr, "XPWD", "11:/SUBDIR/"); expect_directory_read("Suite8-DIR-ROOT", dr, "$//"); - expect_directory_read("Suite8-DIR-PARENT", dr, "$_"); + expect_directory_read("Suite8-DIR-PARENT", dr, "$/../"); } void execute_suite8(FileManager *fm, IecDrive *dr) @@ -1482,6 +1546,9 @@ static void run_suite9_block_matrix(FileManager *fm, IecDrive *dr) const BlockCase &c = cases[i]; c.create_fixture(c.source); prepare_disk_partition(c.source, c.mount, dr, c.partition, c.label); + char select[16]; + snprintf(select, sizeof(select), "CP%d", c.partition); + expect_command_status_prefix("Suite9-SelectPartition", dr, select, "02,PARTITION SELECTED"); uint8_t expected_read[256]; make_sector_payload(expected_read, "BASIC:PRG"); @@ -1493,6 +1560,7 @@ static void run_suite9_block_matrix(FileManager *fm, IecDrive *dr) uint8_t write_payload[256]; make_increment_pattern(write_payload); open_buffer_channel("Suite9-OpenBufferWrite", dr, 2); + expect_command_ok("Suite9-RewindBuffer", dr, "B-P 2 0"); // a new buffer starts at byte 1 (SI-090) send_channel_data(dr, 2, write_payload, sizeof(write_payload)); expect_block_write_sector("Suite9-BlockWrite", dr, 2, c.partition, c.write_track, c.write_sector, write_payload); close_file(dr, 2); @@ -1500,21 +1568,24 @@ static void run_suite9_block_matrix(FileManager *fm, IecDrive *dr) uint32_t free_before = get_free_sectors(fm, c.mount); - expect_command_ok("Suite9-BlockAllocate", dr, "B-A 2 9 17 10"); + expect_command_ok("Suite9-BlockAllocate", dr, "B-A 9 17 10"); uint32_t free_after_alloc = get_free_sectors(fm, c.mount); REQUIRE(free_after_alloc + 1 == free_before); - expect_command_ok("Suite9-BlockFree", dr, "B-F 2 9 17 10"); + expect_command_ok("Suite9-BlockFree", dr, "B-F 9 17 10"); uint32_t free_after_free = get_free_sectors(fm, c.mount); REQUIRE(free_after_free == free_before); } print_scenario(suite, "Block commands on FAT fail"); prepare_fat_partition(fm, dr, fat_path, 8, "FAT-BLOCK"); + expect_command_status_prefix("Suite9-FAT-Select", dr, "CP8", "02,PARTITION SELECTED"); + open_buffer_channel("Suite9-FAT-OpenBuffer", dr, 2); expect_command_status_prefix("Suite9-FAT-BlockRead", dr, "B-R 2 8 17 0", "78,BLOCK ACCESS DENIED"); expect_command_status_prefix("Suite9-FAT-BlockWrite", dr, "B-W 2 8 17 0", "78,BLOCK ACCESS DENIED"); - expect_command_status_prefix("Suite9-FAT-BlockAllocate", dr, "B-A 2 8 17 0", "78,BLOCK ACCESS DENIED"); - expect_command_status_prefix("Suite9-FAT-BlockFree", dr, "B-F 2 8 17 0", "78,BLOCK ACCESS DENIED"); + expect_command_status_prefix("Suite9-FAT-BlockAllocate", dr, "B-A 8 17 0", "78,BLOCK ACCESS DENIED"); + expect_command_status_prefix("Suite9-FAT-BlockFree", dr, "B-F 8 17 0", "78,BLOCK ACCESS DENIED"); + close_file(dr, 2); printf("Suite9 completed successfully!\n"); } @@ -1665,17 +1736,38 @@ static void run_suite10_command_terminator(FileManager *fm, IecDrive *dr) close_file(dr, chan); expect_status_ok("Suite10-RelClose", "12:RELPOS"); - // A command that fills the 64 byte command buffer still has to be executed: the - // zero written after its last byte must not reach the byte count itself. + // A 64 byte command, which filled the buffer before it held 254 bytes, is executed + // with its 64th byte: the partition number ends there. A command that fills the + // buffer now is refused (SI-022), which Suite11-SI022-TooLong checks. char full[65]; - memset(full, 'Z', 64); + memset(full, ' ', 64); + memcpy(full, "CP", 2); + memcpy(full + 62, "12", 2); full[64] = 0; - expect_command_status_prefix("Suite10-FullBuffer", dr, full, "33,SYNTAX ERROR"); + expect_command_response("Suite10-FullBuffer", dr, full, "02,PARTITION SELECTED,12,00\r"); // A command that is nothing but a carriage return carries no command at all, and // has to leave the command channel usable. send_command(dr, "\r"); expect_command_response("Suite10-AFTER-EMPTY-COMMAND", dr, "CP12\r", "02,PARTITION SELECTED,12,00\r"); + + // C takes its partition number as a byte, and that byte can be the same + // carriage return BASIC appends. Partition 13 is the case, and it is what the + // JiffyDOS command @"C"+CHR$(13) sends: three bytes and no terminator. + prepare_fat_partition(fm, dr, "/Fat/s10_p13", 13, "PART13"); + const uint8_t cp13[3] = { 'C', 0xD0, 0x0D }; + expect_command_data_response("Suite10-CP-BINARY-13", dr, cp13, sizeof(cp13), + "02,PARTITION SELECTED,13,00\r"); + // The same command from BASIC, where PRINT# adds the terminator behind it. + const uint8_t cp13_term[4] = { 'C', 0xD0, 0x0D, 0x0D }; + expect_command_data_response("Suite10-CP-BINARY-13-TERMINATED", dr, cp13_term, sizeof(cp13_term), + "02,PARTITION SELECTED,13,00\r"); + const uint8_t cp12[3] = { 'C', 0xD0, 12 }; + expect_command_data_response("Suite10-CP-BINARY-12", dr, cp12, sizeof(cp12), + "02,PARTITION SELECTED,12,00\r"); + const uint8_t cp_missing[2] = { 'C', 0xD0 }; + expect_command_data_response("Suite10-CP-BINARY-NO-PARAMETER", dr, cp_missing, sizeof(cp_missing), + "30,SYNTAX ERROR,00,00\r"); } static void run_suite10_directory_navigation(FileManager *fm, IecDrive *dr) @@ -1738,8 +1830,11 @@ static void run_suite10_directory_navigation(FileManager *fm, IecDrive *dr) expect_path_exists("Suite10-MdNestedExists", fm, "/Fat/nav/MD1/MD2"); expect_path_exists("Suite10-MdNestedFromRootExists", fm, "/Fat/nav/MD1/MD3"); expect_command_response("Suite10-RdNotEmpty", dr, "RD:MD1\r", "63,FILE EXISTS,00,00\r"); - expect_command_ok("Suite10-RdNested", dr, "RD//MD1/:MD2\r"); - expect_command_ok("Suite10-RdNestedFromRoot", dr, "RD//MD1/:MD3\r"); + // RD takes no path (SI-063): the parent is entered first. + expect_command_ok("Suite10-RdEnterParent", dr, "CD//MD1\r"); + expect_command_ok("Suite10-RdNested", dr, "RD:MD2\r"); + expect_command_ok("Suite10-RdNestedFromRoot", dr, "RD:MD3\r"); + expect_command_ok("Suite10-RdLeaveParent", dr, "CD//\r"); expect_command_ok("Suite10-RdNowEmpty", dr, "RD:MD1\r"); expect_path_absent("Suite10-RdRemoved", fm, "/Fat/nav/MD1"); expect_command_response("Suite10-RdMissing", dr, "RD:NOSUCH\r", "62,FILE NOT FOUND,00,00\r"); @@ -1856,21 +1951,32 @@ static void run_suite10_block_commands(FileManager *fm, IecDrive *dr) // Allocating and freeing in the same form. Sector 17/11 is free on a disk that // was just formatted. + // The manuals write these with three numbers: the drive or partition, the track + // and the sector. There is no channel, because neither command touches a buffer. uint32_t free_before = get_free_sectors(fm, image); - expect_command_ok("Suite10-BA-SpaceForm", dr, "B-A: 2 0 17 11 \r"); + expect_command_ok("Suite10-BA-SpaceForm", dr, "B-A: 0 17 11 \r"); REQUIRE(get_free_sectors(fm, image) + 1 == free_before); - expect_command_ok("Suite10-BF-CommaForm", dr, "B-F:2,0,17,11\r"); + expect_command_ok("Suite10-BF-CommaForm", dr, "B-F:0,17,11\r"); REQUIRE(get_free_sectors(fm, image) == free_before); // Refusals. Too few parameters is a syntax error whatever the separators are, a // track or sector outside the disk is refused, and a partition that is a plain // directory has no sectors to address at all. + open_buffer_channel("Suite10-ReopenBuffer", dr, chan); expect_command_status_prefix("Suite10-U1-TooFew", dr, "U1: 2 0 \r", "30,SYNTAX ERROR"); expect_command_status_prefix("Suite10-BR-NoParams", dr, "B-R:\r", "30,SYNTAX ERROR"); expect_command_status_prefix("Suite10-BR-NotNumeric", dr, "B-R:X,0,18,0\r", "30,SYNTAX ERROR"); - expect_command_status_prefix("Suite10-U1-BadTrack", dr, "U1:2,0,99,0\r", "69,FILESYSTEM ERROR"); - expect_command_status_prefix("Suite10-U1-BadSector", dr, "U1:2,0,18,99\r", "69,FILESYSTEM ERROR"); - expect_command_status_prefix("Suite10-U1-OnDirectory", dr, "U1:2,12,18,0\r", "78,BLOCK ACCESS DENIED"); + expect_command_status_prefix("Suite10-U1-BadTrack", dr, "U1:2,0,99,0\r", "66,ILLEGAL TRACK OR SECTOR"); + expect_command_status_prefix("Suite10-U1-BadSector", dr, "U1:2,0,18,99\r", "66,ILLEGAL TRACK OR SECTOR"); + close_file(dr, chan); + // A channel opened while a directory partition is current has no sectors to address; + // the partition number in the command does not change which partition it uses. + expect_command_response("Suite10-CP12", dr, "CP12\r", "02,PARTITION SELECTED,12,00\r"); + open_buffer_channel("Suite10-OpenBufferOnDirectory", dr, chan); + expect_command_status_prefix("Suite10-U1-OnDirectory", dr, "U1:2,13,18,0\r", "78,BLOCK ACCESS DENIED"); + close_file(dr, chan); + // A block command on a channel that is not a direct access channel names no buffer. + expect_command_status_prefix("Suite10-U1-NoBuffer", dr, "U1:2,0,18,0\r", "70,NO CHANNEL"); expect_command_response("Suite10-CP13-Again", dr, "CP13\r", "02,PARTITION SELECTED,13,00\r"); } @@ -1887,11 +1993,13 @@ static void run_suite10_user_commands(IecDrive *dr) expect_command_status_prefix("Suite10-U9", dr, "U9\r", "73,"); expect_command_status_prefix("Suite10-UJ", dr, "UJ\r", "73,"); expect_command_status_prefix("Suite10-UColon", dr, "U:\r", "73,"); - expect_command_status_prefix("Suite10-I", dr, "I0\r", "73,"); + // I is not UI: it initialises and answers OK (SI-053). + expect_command_status_prefix("Suite10-I", dr, "I0\r", "00, OK"); - // U3 to U8 jump into a drive buffer, which this drive has no equivalent for. - expect_command_status_prefix("Suite10-U3", dr, "U3:2,0,18,0\r", "33,SYNTAX ERROR"); - expect_command_status_prefix("Suite10-Unknown", dr, "ZZ\r", "33,SYNTAX ERROR"); + // U3 to U8 jump into a drive buffer, which this drive has no equivalent for. U is + // a command letter, so that is 30 (SI-104); Z is not, so that is 31 (SI-031). + expect_command_status_prefix("Suite10-U3", dr, "U3:2,0,18,0\r", "30,SYNTAX ERROR"); + expect_command_status_prefix("Suite10-Unknown", dr, "ZZ\r", "31,SYNTAX ERROR"); // Reading the error channel clears it, as it does on a real drive. expect_command_status_prefix("Suite10-ErrorSet", dr, "CD//NOSUCH\r", "71,DIRECTORY ERROR"); @@ -1938,6 +2046,19 @@ static void expect_partition_line(const char *testname, const uint8_t *listing, REQUIRE(false); } +// The other half of the check above: a partition the filter was meant to leave out. +static void expect_partition_absent(const char *testname, const uint8_t *listing, int length, int part) +{ + for (int offset = 32; offset + 32 <= length; offset += 32) { + int blocks = listing[offset + 2] | (listing[offset + 3] << 8); + if (blocks == part) { + printf("%s: partition %d is in the listing and should not be\n", testname, part); + dump_hex_relative(listing + offset, 32); + } + REQUIRE(blocks != part); + } +} + // Reads a whole directory stream, whether of files or of partitions. static int read_directory_stream(const char *testname, IecDrive *dr, const char *name, uint8_t *listing, int size) @@ -1984,13 +2105,94 @@ static void run_suite10_partition_directory(FileManager *fm, IecDrive *dr) got = read_directory_stream(testname, dr, "$=P:IMAGE 15?1", listing, sizeof(listing)); expect_partition_line("Suite10-PartFilteredD64", listing, got, 21, "IMAGE 1541", "41 "); expect_partition_line("Suite10-PartFilteredD81", listing, got, 23, "IMAGE 1581", "81 "); - for (int offset = 32; offset + 32 <= got; offset += 32) { - int blocks = listing[offset + 2] | (listing[offset + 3] << 8); - if (blocks == 20) { - printf("%s: the pattern did not exclude partition 20\n", testname); - } - REQUIRE(blocks != 20); + expect_partition_absent("Suite10-PartPatternExcludes", listing, got, 20); + + // It also takes a type, which is what the second half of LOAD"$=P:*=tp" selects. + got = read_directory_stream(testname, dr, "$=P:*=4", listing, sizeof(listing)); + expect_partition_line("Suite10-PartTypeD64", listing, got, 21, "IMAGE 1541", "41 "); + expect_partition_absent("Suite10-PartTypeExcludesNative", listing, got, 20); + expect_partition_absent("Suite10-PartTypeExcludesD71", listing, got, 22); + + got = read_directory_stream(testname, dr, "$=P:*=N", listing, sizeof(listing)); + expect_partition_line("Suite10-PartTypeNativeDir", listing, got, 20, "NATIVE DIR", "NAT"); + expect_partition_line("Suite10-PartTypeNativeDnp", listing, got, 24, "IMAGE NATIVE", "NAT"); + expect_partition_absent("Suite10-PartTypeNativeExcludesD64", listing, got, 21); + + // Several types at once, and one this drive can never have. + got = read_directory_stream(testname, dr, "$=P:*=4,8", listing, sizeof(listing)); + expect_partition_line("Suite10-PartTypesD64", listing, got, 21, "IMAGE 1541", "41 "); + expect_partition_line("Suite10-PartTypesD81", listing, got, 23, "IMAGE 1581", "81 "); + expect_partition_absent("Suite10-PartTypesExcludeD71", listing, got, 22); + + got = read_directory_stream(testname, dr, "$=P:*=C", listing, sizeof(listing)); + for (int part = 20; part <= 24; part++) { + expect_partition_absent("Suite10-PartTypeCpm", listing, got, part); + } +} + +// The reply to G-P: thirty bytes and a carriage return. Byte 0 is the CMD partition +// type, byte 1 is reserved, byte 2 is the partition number and bytes 3 to 18 carry +// the name the partition directory shows. +static void expect_partition_info(const char *testname, IecDrive *dr, const uint8_t *cmd, + int len, int type, int part, const char *name) +{ + send_command_data(dr, cmd, len); + get_status(dr); + bool ok = (last_status_size == 31) && (last_status[0] == type) && (last_status[1] == 0) && + (last_status[2] == part) && (last_status[30] == 0x0D) && + (strncmp(last_status + 3, name, 16) == 0); + if (!ok) { + char got_name[17] = { 0 }; + memcpy(got_name, last_status + 3, 16); + printf("%s: %d bytes, type %d, partition %d, name '%s'; expected 31 bytes, type %d, " + "partition %d, name '%s'\n", testname, last_status_size, last_status[0], + last_status[2], got_name, type, part, name); + dump_hex_relative((uint8_t *)last_status, last_status_size); } + REQUIRE(ok); +} + +static void run_suite10_partition_info(FileManager *fm, IecDrive *dr) +{ + print_scenario("Suite10", "Partition information"); + // Partition 13 is the one whose number is the same byte as the terminator, and + // an earlier scenario has since mounted an image there. + prepare_fat_partition(fm, dr, "/Fat/s10_p13", 13, "PART13"); + + // The partitions the directory scenario above created, read back one at a time. + // The type is the CMD code the directory prints as NAT, 41, 71 and 81. + const uint8_t native_dir[4] = { 'G', '-', 'P', 20 }; + expect_partition_info("Suite10-InfoNativeDir", dr, native_dir, sizeof(native_dir), 1, 20, "NATIVE DIR"); + const uint8_t d64[4] = { 'G', '-', 'P', 21 }; + expect_partition_info("Suite10-InfoD64", dr, d64, sizeof(d64), 2, 21, "IMAGE 1541"); + const uint8_t d71[4] = { 'G', '-', 'P', 22 }; + expect_partition_info("Suite10-InfoD71", dr, d71, sizeof(d71), 3, 22, "IMAGE 1571"); + const uint8_t d81[4] = { 'G', '-', 'P', 23 }; + expect_partition_info("Suite10-InfoD81", dr, d81, sizeof(d81), 4, 23, "IMAGE 1581"); + const uint8_t dnp[4] = { 'G', '-', 'P', 24 }; + expect_partition_info("Suite10-InfoDnp", dr, dnp, sizeof(dnp), 1, 24, "IMAGE NATIVE"); + + // With the terminator BASIC appends, and with a number that is not a partition. + const uint8_t d64_term[5] = { 'G', '-', 'P', 21, 0x0D }; + expect_partition_info("Suite10-InfoTerminated", dr, d64_term, sizeof(d64_term), 2, 21, "IMAGE 1541"); + // A partition that does not exist reports type 0, which CMD DOS calls "not + // created". Asking about one is not an error. + const uint8_t missing[4] = { 'G', '-', 'P', 99 }; + expect_partition_info("Suite10-InfoAbsent", dr, missing, sizeof(missing), 0, 99, ""); + + // No number and 255 both ask about the partition already selected. + expect_command_response("Suite10-InfoSelect", dr, "CP22\r", "02,PARTITION SELECTED,22,00\r"); + const uint8_t current[3] = { 'G', '-', 'P' }; + expect_partition_info("Suite10-InfoCurrent", dr, current, sizeof(current), 3, 22, "IMAGE 1571"); + const uint8_t current255[4] = { 'G', '-', 'P', 255 }; + expect_partition_info("Suite10-InfoCurrent255", dr, current255, sizeof(current255), 3, 22, "IMAGE 1571"); + // Partition 13 is the number whose byte is the terminator. The CMD manual asks + // for the terminator to be sent as well, and with it the partition is reached; + // without it the command reads as though it carried no number at all. + const uint8_t part13[5] = { 'G', '-', 'P', 0x0D, 0x0D }; + expect_partition_info("Suite10-InfoPartition13", dr, part13, sizeof(part13), 1, 13, "PART13"); + const uint8_t part13_bare[4] = { 'G', '-', 'P', 0x0D }; + expect_partition_info("Suite10-InfoPartition13Bare", dr, part13_bare, sizeof(part13_bare), 3, 22, "IMAGE 1571"); } static void run_suite10_directory_streams(FileManager *fm, IecDrive *dr) @@ -2046,36 +2248,2781 @@ void execute_suite10(FileManager *fm, IecDrive *dr) run_suite10_block_commands(fm, dr); run_suite10_user_commands(dr); run_suite10_partition_directory(fm, dr); + run_suite10_partition_info(fm, dr); run_suite10_directory_streams(fm, dr); printf("Suite10 completed successfully!\n"); } -int main(int argc, const char **argv) +// --------------------------------------------------------------------------- +// Suite11: doc/softiec_compatibility_spec.md, one case per requirement, each named +// after the paragraph it checks. +// +// Every case works on a partition of its own and sets it up itself, so a case can be +// run alone: `./result/testdrive SI031` runs only the Suite11 cases whose name +// contains SI031 and skips every other suite. That is how a requirement is shown to +// fail on its own before its change and to pass after it. +// --------------------------------------------------------------------------- + +#include "iec_channel.h" +#include "iec_log.h" + +// A fresh directory on the FAT file, mounted as partition 40, selected, and entered at +// its root. +static const char *s11_partition(FileManager *fm, IecDrive *dr, const char *dir) { - UserInterface *ui = new UserInterface("Test Drive"); + const char *testname = "Suite11"; + static char path[64]; + snprintf(path, sizeof(path), "/Fat/s11_%s", dir); + FRESULT fres = fm->create_dir(path); + REQUIRE(fres == FR_OK || fres == FR_EXIST); + dr->add_partition(40, path, "SUITE11"); + expect_command_response(testname, dr, "CP40\r", "02,PARTITION SELECTED,40,00\r"); + expect_command_ok(testname, dr, "CD//\r"); + return path; +} - init_ram_disk(); - init_flash_disk(); - init_fat_file(); +// SI-031: a command whose first byte is not a command letter answers 31, which is +// what the 1541 ROM loads at $C175 when its command table has no match. +static void s11_si031_unrecognised(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI031-Unrecognised"; + s11_partition(fm, dr, "si031"); + // CHR$(0) is the command C64 OS sends during its boot, measured as 33 on #877. + const uint8_t chr0[1] = { 0 }; + expect_command_data_response(testname, dr, chr0, 1, "31,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "Z\r", "31,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "Q", "31,SYNTAX ERROR,00,00\r"); +} - IecDrive *dr = new IecDrive(); - t_channel_retval ret; +// SI-030: a command letter followed by a sub-command that does not exist answers 30, +// because the command was recognised. U3 jumps into drive memory (SI-104) and B-E +// executes a drive buffer (SI-095); neither exists here. +static void s11_si030_unknown_subcommand(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI030-UnknownSubcommand"; + s11_partition(fm, dr, "si030a"); + expect_command_response(testname, dr, "U3:2,0,18,0\r", "30,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "B-E:2,0,18,0\r", "30,SYNTAX ERROR,00,00\r"); +} + +// SI-030: a colon with nothing after it is a missing name, 34. +static void s11_si030_missing_name(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI030-MissingName"; + s11_partition(fm, dr, "si030b"); + expect_command_response(testname, dr, "C:NEW=\r", "34,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "R:NEW=\r", "34,SYNTAX ERROR,00,00\r"); +} + +// SI-030: a wildcard in the target of a copy or a rename is an illegal name, 33. +static void s11_si030_wildcard_target(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI030-WildcardTarget"; + s11_partition(fm, dr, "si030c"); + expect_command_response(testname, dr, "C:NEW*=OLD\r", "33,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "R:NEW?=OLD\r", "33,SYNTAX ERROR,00,00\r"); +} + +// SI-036: a block command outside the disk is error 66, which CBM DOS names, and not +// the Ultimate's own 69 with a file system result code in the track field. +static void s11_si036_block_range(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI036-BlockRange"; + const char *image = "/Fat/s11_si036.d64"; + create_formatted_image(fm, image, "RANGE", 683, e_image_d64); + dr->add_partition(41, image, "RANGE"); + expect_command_response(testname, dr, "CP41\r", "02,PARTITION SELECTED,41,00\r"); + open_buffer_channel(testname, dr, 2); + expect_command_response(testname, dr, "U1:2,0,99,0\r", "66,ILLEGAL TRACK OR SECTOR,99,00\r"); + expect_command_response(testname, dr, "U1:2,0,18,99\r", "66,ILLEGAL TRACK OR SECTOR,18,99\r"); + expect_command_response(testname, dr, "U2:2,0,36,0\r", "66,ILLEGAL TRACK OR SECTOR,36,00\r"); + expect_command_response(testname, dr, "B-A:0,40,1\r", "66,ILLEGAL TRACK OR SECTOR,40,01\r"); + close_file(dr, 2); +} + +// B-A of a block that is already allocated answers 65, NO BLOCK, with the next higher +// free track and sector, or track 0 when no higher block is free (1541-II User's Guide, +// error 65; HD 9-43 and appendix B). B-F of a block that is already free changes nothing +// and is not an error; neither manual lists one. Both answered 74, DRIVE NOT READY. +static void s11_block_allocate_answers(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-BlockAllocateAnswers"; + const char *image = "/Fat/s11_ba.d64"; + create_formatted_image(fm, image, "ALLOC", 683, e_image_d64); + dr->add_partition(42, image, "ALLOC"); + expect_command_response(testname, dr, "CP42\r", "02,PARTITION SELECTED,42,00\r"); + uint8_t listing[4096]; + int got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + int free_before = listing[got - 30] | (listing[got - 29] << 8); // the BLOCKS FREE line + + // A formatted disk holds the BAM at 18/0 and the first directory block at 18/1. + expect_command_response(testname, dr, "B-A:0,18,0\r", "65,NO BLOCK,18,02\r"); + expect_command_response(testname, dr, "B-A:0,1,0\r", "00, OK,00,00\r"); + expect_command_response(testname, dr, "B-A:0,1,0\r", "65,NO BLOCK,01,01\r"); + got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + REQUIRE((listing[got - 30] | (listing[got - 29] << 8)) == free_before - 1); + expect_command_response(testname, dr, "B-F:0,1,0\r", "00, OK,00,00\r"); + expect_command_response(testname, dr, "B-F:0,1,0\r", "00, OK,00,00\r"); + got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + REQUIRE((listing[got - 30] | (listing[got - 29] << 8)) == free_before); + + // The last block of track 35 has no higher block after it. + expect_command_response(testname, dr, "B-A:0,35,16\r", "00, OK,00,00\r"); + expect_command_response(testname, dr, "B-A:0,35,16\r", "65,NO BLOCK,00,00\r"); + expect_command_response(testname, dr, "B-F:0,35,16\r", "00, OK,00,00\r"); + got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + REQUIRE((listing[got - 30] | (listing[got - 29] << 8)) == free_before); +} + +// SI-033: a scratch that matches nothing is not an error. The answer is 01 with a +// count of zero, as HD B-1 and the 1541 give it. C64 OS sends S/TEMPORARY/:* on every +// boot, whether or not the directory holds anything. +static void s11_si033_scratch_nothing(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI033-ScratchNothing"; + s11_partition(fm, dr, "si033"); + expect_command_response(testname, dr, "S:NOSUCHFILE\r", "01, FILES SCRATCHED,00,00\r"); + expect_command_ok(testname, dr, "MD:TEMPORARY\r"); + expect_command_response(testname, dr, "S/TEMPORARY/:*\r", "01, FILES SCRATCHED,00,00\r"); + // The count still counts. + expect_iec_write_ok(testname, dr, 2, "/TEMPORARY/:GONE,S,W", "x"); + expect_command_response(testname, dr, "S/TEMPORARY/:*\r", "01, FILES SCRATCHED,01,00\r"); + // A directory that is not there is a path error, not a scratch of nothing. + expect_command_response(testname, dr, "S/NOSUCHDIR/:*\r", "71,DIRECTORY ERROR,40,00\r"); +} + +// SI-053: I initialises. There is no medium to read in, so it answers OK, and like +// sd2iec it closes the channels a program left open, flushing what was written to +// them. UI is a different command and still answers with the DOS version. +static void s11_si053_initialize(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI053-Initialize"; + s11_partition(fm, dr, "si053"); + expect_command_response(testname, dr, "I\r", "00, OK,00,00\r"); + expect_command_response(testname, dr, "I0:\r", "00, OK,00,00\r"); + expect_command_response(testname, dr, "UI\r", "73,U64HD ULTIMATE DOS V2.0,00,00\r"); + + // A file written and never closed: I closes it, so what was written is there. + open_file(dr, 3, "LEFTOPEN,S,W"); + get_status(dr); + expect_status_ok(testname, "LEFTOPEN,S,W"); + send_channel_data(dr, 3, (const uint8_t *)"FLUSHED", 7); + expect_command_response(testname, dr, "I\r", "00, OK,00,00\r"); + expect_iec_file(testname, dr, 2, "LEFTOPEN,S,R", "FLUSHED"); +} + +// SI-045 and SI-046: the partition directory is a header, one line per partition and +// the BASIC end marker, with no blocks free line (issue #890), and the number in front +// of the header name is the number of partitions. +static void s11_si045_partition_directory(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI045-PartitionDirectory"; + s11_partition(fm, dr, "si045"); + int partitions = 0; + for (int i = 1; i < MAX_PARTITIONS; i++) { + IecPartition *p = dr->get_file_system()->GetPartition(i); + if (p && (p->GetPartitionNumber() == i)) { + partitions++; + } + } + uint8_t listing[8192]; + int got = read_directory_stream(testname, dr, "$=P", listing, sizeof(listing)); + if (memmem(listing, got, "BLOCKS FREE", 11)) { + printf("%s: the partition directory has a blocks free line\n", testname); + dump_hex_relative(listing + got - 64, 64); + } + REQUIRE(memmem(listing, got, "BLOCKS FREE", 11) == NULL); + // A header and one 32 byte line per partition, then the two zero bytes that end a + // BASIC program. + if (got != (32 * (partitions + 1)) + 2) { + printf("%s: %d bytes for %d partitions, expected %d\n", testname, got, partitions, + (32 * (partitions + 1)) + 2); + } + REQUIRE(got == (32 * (partitions + 1)) + 2); + REQUIRE((listing[got - 2] == 0) && (listing[got - 1] == 0)); +} + +static void s11_si046_partition_count(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI046-PartitionCount"; + s11_partition(fm, dr, "si046"); + int partitions = 0; + for (int i = 1; i < MAX_PARTITIONS; i++) { + IecPartition *p = dr->get_file_system()->GetPartition(i); + if (p && (p->GetPartitionNumber() == i)) { + partitions++; + } + } + uint8_t listing[8192]; + read_directory_stream(testname, dr, "$=P", listing, sizeof(listing)); + // Bytes 4 and 5 of the header are the line number BASIC prints before the name. + int shown = listing[4] | (listing[5] << 8); + if (shown != partitions) { + printf("%s: header shows %d, there are %d partitions\n", testname, shown, partitions); + } + REQUIRE(partitions > 1); + REQUIRE(shown == partitions); +} + +// Reads what the command channel has to say, however long it is. last_status only +// holds a status line, and M-R can answer with 256 bytes. +static int read_command_channel(IecDrive *dr, uint8_t *out, int size) +{ + dr->push_ctrl(SLAVE_CMD_ATN); + dr->push_ctrl(0x6F); + dr->talk(); + int total = 0; + while (total < size) { + uint8_t *data; + int n = 0; + t_channel_retval ret = dr->prefetch_more(256, data, n); + if (n > size - total) { + n = size - total; + } + memcpy(out + total, data, n); + total += n; + dr->pop_more(n); + if ((ret != IEC_OK) || (n == 0)) { + break; + } + } + return total; +} + +// SI-100: U0>+CHR$(d) moves the drive to device number d for as long as it runs; the +// configured number is not written. +static void s11_si100_device_number(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI100-DeviceNumber"; + s11_partition(fm, dr, "si100"); + int configured = dr->get_address(); + const uint8_t u0_12[5] = { 'U', '0', '>', 12, 0x0D }; + expect_command_data_response(testname, dr, u0_12, sizeof(u0_12), "00, OK,00,00\r"); + printf("%s: device number now %d, configured %d\n", testname, dr->get_address(), configured); + REQUIRE(dr->get_address() == 12); + // The drive keeps answering on the command channel. + expect_command_response(testname, dr, "UI\r", "73,U64HD ULTIMATE DOS V2.0,00,00\r"); + // Outside 8 to 30 nothing changes. + const uint8_t u0_7[4] = { 'U', '0', '>', 7 }; + expect_command_data_response(testname, dr, u0_7, sizeof(u0_7), "30,SYNTAX ERROR,00,00\r"); + REQUIRE(dr->get_address() == 12); + const uint8_t u0_back[4] = { 'U', '0', '>', (uint8_t)configured }; + expect_command_data_response(testname, dr, u0_back, sizeof(u0_back), "00, OK,00,00\r"); + REQUIRE(dr->get_address() == configured); +} + +// SI-105 and SI-112: M-R answers the number of bytes asked for, all zero, and does not +// read past the end of the page; M-W and M-E are refused, because no drive code runs here. +static void s11_si105_memory_commands(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI105-MemoryCommands"; + s11_partition(fm, dr, "si105"); + uint8_t reply[512]; + + // The four probes C64 OS sends during its boot, two bytes each, as PRINT# sends them. + static const uint16_t probes[] = { 0xFEA4, 0xE5C5, 0xA6E8, 0x0002 }; + for (int i = 0; i < 4; i++) { + uint8_t cmd[7] = { 'M', '-', 'R', (uint8_t)(probes[i] & 0xFF), (uint8_t)(probes[i] >> 8), 2, 0x0D }; + send_command_data(dr, cmd, sizeof(cmd)); + memset(reply, 0xAA, sizeof(reply)); + int got = read_command_channel(dr, reply, sizeof(reply)); + printf("%s: M-R $%04X,2 answered %d bytes: %02X %02X\n", testname, probes[i], got, reply[0], reply[1]); + REQUIRE(got == 2); + REQUIRE((reply[0] == 0) && (reply[1] == 0)); + } + // After the bytes, the error channel says OK again. + get_status(dr); + expect_current_status(testname, "after M-R", "00, OK,00,00\r"); + + // No count reads one byte, a count of zero reads 256, and the page end stops it. + const uint8_t one[5] = { 'M', '-', 'R', 0x00, 0xFE }; + send_command_data(dr, one, sizeof(one)); + REQUIRE(read_command_channel(dr, reply, sizeof(reply)) == 1); + const uint8_t all[6] = { 'M', '-', 'R', 0x00, 0xFE, 0x00 }; + send_command_data(dr, all, sizeof(all)); + int got = read_command_channel(dr, reply, sizeof(reply)); + printf("%s: M-R $FE00,0 answered %d bytes\n", testname, got); + REQUIRE(got == 256); + for (int i = 0; i < 256; i++) { + REQUIRE(reply[i] == 0); + } + const uint8_t edge[6] = { 'M', '-', 'R', 0xF0, 0xFE, 0x20 }; + send_command_data(dr, edge, sizeof(edge)); + REQUIRE(read_command_channel(dr, reply, sizeof(reply)) == 16); + + const uint8_t mw[8] = { 'M', '-', 'W', 0x00, 0x05, 0x02, 0xEA, 0x60 }; + expect_command_data_response(testname, dr, mw, sizeof(mw), "30,SYNTAX ERROR,00,00\r"); + const uint8_t me[5] = { 'M', '-', 'E', 0x00, 0x05 }; + expect_command_data_response(testname, dr, me, sizeof(me), "30,SYNTAX ERROR,00,00\r"); +} + +// SI-021: a command, and the name of a file opened on a data channel, can be longer +// than 64 bytes. C64 OS paths reach 232 characters. +static void s11_si021_long_names(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI021-LongNames"; + s11_partition(fm, dr, "si021"); + expect_command_ok(testname, dr, "MD:DIRECTORYNAMENUMBERONEXYZ\r"); + expect_command_ok(testname, dr, "MD/DIRECTORYNAMENUMBERONEXYZ/:DIRECTORYNAMENUMBERTWOXYZ\r"); + const char *file = "/DIRECTORYNAMENUMBERONEXYZ/DIRECTORYNAMENUMBERTWOXYZ/:VICTIMFILE"; + char name[128]; + snprintf(name, sizeof(name), "%s,S,W", file); + REQUIRE(strlen(name) > 64); + expect_iec_write_ok(testname, dr, 2, name, "long"); + snprintf(name, sizeof(name), "%s,S,R", file); + expect_iec_file(testname, dr, 2, name, "long"); + char cmd[128]; + snprintf(cmd, sizeof(cmd), "S%s\r", file); + REQUIRE(strlen(cmd) > 64); + expect_command_response(testname, dr, cmd, "01, FILES SCRATCHED,01,00\r"); +} + +// SI-022: a command longer than the buffer answers 32 and is not executed. Cut short +// and executed, a scratch removes what its first bytes name. +static void s11_si022_too_long(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI022-TooLong"; + const char *path = s11_partition(fm, dr, "si022"); + expect_iec_write_ok(testname, dr, 2, "VICTIM,S,W", "keep me"); + char cmd[300]; + memset(cmd, 'A', sizeof(cmd)); + memcpy(cmd, "S:VICTIM,", 9); + cmd[255] = 0; + expect_command_response(testname, dr, cmd, "32,SYNTAX ERROR,00,00\r"); + expect_iec_file(testname, dr, 2, "VICTIM,S,R", "keep me"); + cmd[254] = 0; // a command that fills the buffer is refused as well + expect_command_response(testname, dr, cmd, "32,SYNTAX ERROR,00,00\r"); + expect_iec_file(testname, dr, 2, "VICTIM,S,R", "keep me"); + cmd[253] = 0; // one byte shorter fits + expect_command_response(testname, dr, cmd, "01, FILES SCRATCHED,01,00\r"); + + // A name that fills the buffer is refused the same way, not created under its first + // bytes. + char name[300]; + memset(name, 'B', sizeof(name)); + memcpy(name, "LONGNAME", 8); + name[260] = 0; + open_file(dr, 2, name); + get_status(dr); + expect_current_status(testname, "a 260 byte name", "32,SYNTAX ERROR,00,00\r"); + close_file(dr, 2); + uint8_t listing[4096]; + int got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + REQUIRE(memmem(listing, got, "LONGNAME", 8) == NULL); +} + +// SI-016: a command ending in a carriage return and a line feed, as PRINT# to a logical +// file number of 128 or more sends it, ends before them. +static void s11_si016_second_terminator(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI016-SecondTerminator"; + s11_partition(fm, dr, "si016"); + expect_command_ok(testname, dr, "MD:SUB\r"); + expect_command_ok(testname, dr, "CD:SUB\r\n"); + expect_command_response(testname, dr, "XPWD\r", "40:/SUB/"); +} + +// SI-018: the position command keeps a last byte of 13, because it is an offset and +// not a terminator. +static void s11_si018_position_exempt(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI018-PositionExempt"; + s11_partition(fm, dr, "si018"); + const uint8_t chan = 3; + const uint8_t record[16] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P' }; + expect_rel_open(testname, dr, chan, "RECORDS", sizeof(record)); + expect_rel_write(testname, dr, chan, record, sizeof(record)); + close_file(dr, chan); + expect_rel_open(testname, dr, chan, "RECORDS", sizeof(record)); + // P, the channel, record 1, offset 13, and no terminator: JiffyDOS's @ sends this. + const uint8_t p13[5] = { 'P', chan, 1, 0, 13 }; + expect_command_data_response(testname, dr, p13, sizeof(p13), "00, OK,00,00\r"); + expect_rel_read(testname, dr, chan, record + 12, 4); + // The same from BASIC, with the terminator behind it. + const uint8_t p13_basic[6] = { 'P', (uint8_t)(96 + chan), 1, 0, 13, 0x0D }; + expect_command_data_response(testname, dr, p13_basic, sizeof(p13_basic), "00, OK,00,00\r"); + expect_rel_read(testname, dr, chan, record + 12, 4); + close_file(dr, chan); +} + +// SI-014 and SI-015: the left arrow (0x5F) is the parent directory in the name +// position, directly after CD[n] or after a colon, and an ordinary character between +// slashes. This is the reproduction from #877. +static void s11_si014_left_arrow(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI014-LeftArrow"; + const char *path = s11_partition(fm, dr, "si014"); + char host[80]; + expect_command_ok(testname, dr, "MD:_\r"); + snprintf(host, sizeof(host), "%s/_", path); + expect_path_exists(testname, fm, host); + expect_directory_contains(testname, dr, "$", "\"_\""); + expect_command_ok(testname, dr, "CD/_\r"); + expect_command_response(testname, dr, "XPWD\r", "40:/_/"); + expect_command_ok(testname, dr, "CD:_\r"); + expect_command_response(testname, dr, "XPWD\r", "40:/"); + expect_command_ok(testname, dr, "CD/_\r"); + expect_command_ok(testname, dr, "CD_\r"); + expect_command_response(testname, dr, "XPWD\r", "40:/"); + expect_command_ok(testname, dr, "CD/_\r"); + expect_command_ok(testname, dr, "CD/:_\r"); // SI-015 + expect_command_response(testname, dr, "XPWD\r", "40:/"); + // A left arrow between slashes is a name; .. goes up and down again. + expect_command_ok(testname, dr, "MD/_/:OTHER\r"); + expect_command_ok(testname, dr, "CD//_/OTHER\r"); + expect_command_response(testname, dr, "XPWD\r", "40:/_/OTHER/"); + expect_command_ok(testname, dr, "CD/../OTHER\r"); + expect_command_response(testname, dr, "XPWD\r", "40:/_/OTHER/"); + expect_command_ok(testname, dr, "CD//_\r"); + expect_command_ok(testname, dr, "RD:OTHER\r"); + expect_command_ok(testname, dr, "CD:_\r"); + expect_command_ok(testname, dr, "RD:_\r"); + expect_path_absent(testname, fm, host); +} + +// SI-012: a path component may carry wildcards, and the first match is used. +static void s11_si012_wildcard_path(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI012-WildcardPath"; + s11_partition(fm, dr, "si012"); + expect_command_ok(testname, dr, "MD:SUBDIRECTORY\r"); + expect_command_ok(testname, dr, "MD/SUBDIRECTORY/:DEEP\r"); + expect_command_ok(testname, dr, "CD//SUB*/DEEP\r"); + expect_command_response(testname, dr, "XPWD\r", "40:/SUBDIRECTORY/DEEP/"); + expect_command_ok(testname, dr, "CD//SUBDIRECTOR?/\r"); + expect_command_response(testname, dr, "XPWD\r", "40:/SUBDIRECTORY/"); + expect_command_ok(testname, dr, "CD//\r"); + expect_iec_write_ok(testname, dr, 2, "/SUBDIRECTORY/DEEP/:INSIDE,S,W", "found"); + expect_iec_file(testname, dr, 2, "//S*/D*/:INSIDE,S,R", "found"); +} + +// SI-060: MD needs a colon, and a name that is a shifted space is no name. +static void s11_si060_md_colon(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI060-MdColon"; + s11_partition(fm, dr, "si060"); + expect_command_response(testname, dr, "MD NOCOLON\r", "34,SYNTAX ERROR,00,00\r"); + const uint8_t shifted_space[5] = { 'M', 'D', ':', 0xA0, 0x0D }; + expect_command_data_response(testname, dr, shifted_space, sizeof(shifted_space), "34,SYNTAX ERROR,00,00\r"); + expect_command_ok(testname, dr, "MD:WITHCOLON\r"); +} + +// SI-063: RD takes no path, so it cannot remove the parent of where the user stands. +static void s11_si063_rd_no_path(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI063-RdNoPath"; + const char *path = s11_partition(fm, dr, "si063"); + char host[80]; + expect_command_ok(testname, dr, "MD:PROBEDIR\r"); + expect_command_response(testname, dr, "RD/PROBEDIR\r", "34,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "RD//:PROBEDIR\r", "34,SYNTAX ERROR,00,00\r"); + snprintf(host, sizeof(host), "%s/PROBEDIR", path); + expect_path_exists(testname, fm, host); + expect_command_ok(testname, dr, "RD:PROBEDIR\r"); + expect_path_absent(testname, fm, host); +} + +// SI-150: a path deeper than sixteen components is followed to its end, not cut off. +static void s11_si150_deep_path(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI150-DeepPath"; + s11_partition(fm, dr, "si150"); + char path[128] = ""; + char cmd[160]; + for (int i = 0; i < 20; i++) { + snprintf(cmd, sizeof(cmd), "MD//%s:%c\r", path, 'A' + i); + expect_command_ok(testname, dr, cmd); + int len = strlen(path); + path[len] = 'A' + i; + path[len + 1] = '/'; + path[len + 2] = 0; + } + snprintf(cmd, sizeof(cmd), "CD//%s\r", path); + expect_command_ok(testname, dr, cmd); + char pwd[160]; + snprintf(pwd, sizeof(pwd), "40:/%s", path); + expect_command_response(testname, dr, "XPWD\r", pwd); +} + +// SI-130 and SI-131: a listing is a BASIC program loaded at $0401, so it starts with +// the load address 01 04 and a link 01 01; byte 4 is the partition number. +static void s11_si130_listing_header(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI130-ListingHeader"; + s11_partition(fm, dr, "si130"); + uint8_t listing[4096]; + read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + printf("%s: first bytes %02X %02X %02X %02X %02X\n", testname, + listing[0], listing[1], listing[2], listing[3], listing[4]); + REQUIRE((listing[0] == 0x01) && (listing[1] == 0x04)); + REQUIRE((listing[2] == 0x01) && (listing[3] == 0x01)); + REQUIRE(listing[4] == 40); +} + +// The line of a listing whose quoted name is `name`, or NULL. +static const uint8_t *s11_listing_line(const uint8_t *listing, int length, const char *name) +{ + char quoted[24]; + snprintf(quoted, sizeof(quoted), "\"%s\"", name); + for (int offset = 32; offset + 32 <= length; offset += 32) { + if (memmem(listing + offset, 32, quoted, strlen(quoted))) { + return listing + offset; + } + } + return NULL; +} + +// SI-133: the low byte of each line's link is (file size mod 254) + 2, so a program can +// work out a file's exact length from the listing. +static void s11_si133_size_remainder(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI133-SizeRemainder"; + const char *path = s11_partition(fm, dr, "si133"); uint32_t tr; - mstring status; + uint8_t data[600]; + memset(data, 'x', sizeof(data)); + REQUIRE(fm->save_file(true, path, "TEN.prg", data, 10, &tr) == FR_OK); + REQUIRE(fm->save_file(true, path, "EXACT.prg", data, 254, &tr) == FR_OK); + REQUIRE(fm->save_file(true, path, "LONGER.prg", data, 300, &tr) == FR_OK); + uint8_t listing[4096]; + int got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + static const struct { const char *name; uint8_t link; } cases[] = { + { "TEN", 12 }, { "EXACT", 2 }, { "LONGER", 48 }, + }; + for (int i = 0; i < 3; i++) { + const uint8_t *line = s11_listing_line(listing, got, cases[i].name); + REQUIRE(line != NULL); + printf("%s: %s link %02X %02X, expected %02X 01\n", testname, cases[i].name, line[0], line[1], cases[i].link); + REQUIRE((line[0] == cases[i].link) && (line[1] == 0x01)); + } +} - File *f; - FileManager *fm = FileManager :: getFileManager(); +// One GET#, as BASIC performs it: address the channel to talk, take a single byte, and +// release the bus again. The drive sees a fresh talk for every byte, which is what +// separates this from a load (SI-138, issue #917). +static t_channel_retval s11_get_byte(IecDrive *dr, uint8_t chan, uint8_t *out) +{ + dr->push_ctrl(SLAVE_CMD_ATN); + dr->push_ctrl(0x60 | chan); + dr->talk(); + uint8_t data = 0; + t_channel_retval ret = dr->prefetch_data(data); + if ((ret == IEC_OK) || (ret == IEC_LAST)) { + *out = data; + dr->pop_data(); + } + return ret; +} + +// SI-138: the last byte of a listing carries EOI, whatever the size of the reads that +// brought the listing in. Reported on issue #917: a BASIC program that reads a listing +// with GET# never saw a status of 64 and read zeroes for ever. The tail is read one byte +// per talk here, which is the case that failed; a whole-stream read never does. +static void s11_si138_listing_eof(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI138-ListingEof"; + const char *path = s11_partition(fm, dr, "si138"); + uint32_t tr; + uint8_t data[16]; + memset(data, 'e', sizeof(data)); + REQUIRE(fm->save_file(true, path, "ONE.prg", data, sizeof(data), &tr) == FR_OK); + REQUIRE(fm->save_file(true, path, "TWO.seq", data, sizeof(data), &tr) == FR_OK); + + static const char *listings[] = { "$", "$=T:*", "$=T:*=L", "$=P" }; + for (int i = 0; i < 4; i++) { + const char *name = listings[i]; + uint8_t listing[4096]; + int total = read_directory_stream(testname, dr, name, listing, sizeof(listing)); + REQUIRE(total > 4); + + // Everything but the last four bytes in one piece, then the tail one byte at a + // time. The fourth of those bytes is the last byte of the listing. + open_file(dr, 0, name); + get_status(dr); + expect_status_ok(testname, name); + REQUIRE(read_file_limited(dr, 0, NULL, total - 4) == (total - 4)); + + int reads = 0; + t_channel_retval ret = IEC_OK; + uint8_t byte = 0xFF; + while ((reads < 16) && (ret == IEC_OK)) { + ret = s11_get_byte(dr, 0, &byte); + reads++; + } + printf("%s: %s ends after %d single byte reads with %d\n", testname, name, reads, (int)ret); + REQUIRE(ret == IEC_LAST); + REQUIRE(reads == 4); + REQUIRE(byte == 0); + close_file(dr, 0); + expect_status_ok(testname, name); + } +} + +// The time stamp a line of `length` bytes carries, given the block count in front of it. +// The type field sits at a fixed printed column, so everything behind it moves with the +// number of digits BASIC prints for the line number. +static void s11_expect_stamped_line(const char *testname, const uint8_t *line, int length, + const char *type, int gap, int stamp_len) +{ + int blocks = line[2] | (line[3] << 8); + int chars = (blocks >= 1000) ? 4 : (blocks >= 100) ? 3 : (blocks >= 10) ? 2 : 1; + int type_at = 27 - chars; + int stamp_at = type_at + (int)strlen(type) + gap; + printf("%s: %d blocks, type at %d, stamp at %d: ", testname, blocks, type_at, stamp_at); + for (int i = 0; i < length; i++) { + printf("%02X ", line[i]); + } + printf("\n"); + REQUIRE(memcmp(line + type_at, type, strlen(type)) == 0); + for (int i = type_at + (int)strlen(type); i < stamp_at; i++) { + REQUIRE(line[i] == 32); + } + REQUIRE((line[stamp_at + 2] == '/') && (line[stamp_at + 5] == '/' || line[stamp_at + 5] == ' ')); + // The filler CMD DOS puts behind the stamp, and the zero that ends the BASIC line. + for (int i = stamp_at + stamp_len; i < length - 1; i++) { + REQUIRE(line[i] == 1); + } + REQUIRE(line[length - 1] == 0); +} + +// SI-139: a time stamped line is a fixed 64 bytes long, or 42 in the short format, and +// the bytes behind the stamp are 0x01. Reported on issue #917 against a CMD HD and an +// sd2iec: SoftIEC put the stamp two columns early in the long format and left the filler +// out of both, so a line was as long as its contents made it. +static void s11_si139_stamped_entries(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI139-StampedEntries"; + const char *path = s11_partition(fm, dr, "si139"); + uint32_t tr; + uint8_t data[3000]; + memset(data, 'x', sizeof(data)); + // One block, so BASIC prints one digit, and twelve blocks, so it prints two. The two + // digit case is the one the report names: one filler byte in the short format. + REQUIRE(fm->save_file(true, path, "SMALL.prg", data, 16, &tr) == FR_OK); + REQUIRE(fm->save_file(true, path, "BIGGER.prg", data, sizeof(data), &tr) == FR_OK); + + static const struct { const char *name; int line; const char *type; int gap; int stamp; } + cases[] = { + { "$=T:*=L", 64, "PRG", 3, 19 }, // MM/DD/YY HH.MM xM + { "$=T:*", 42, "P", 1, 13 }, // MM/DD HH.MM x + }; + for (int i = 0; i < 2; i++) { + uint8_t listing[4096]; + int got = read_directory_stream(testname, dr, cases[i].name, listing, sizeof(listing)); + // A header and a blocks free line of 32 bytes, and two lines in between. + printf("%s: %s is %d bytes\n", testname, cases[i].name, got); + REQUIRE(got == 64 + 2 * cases[i].line); + for (int entry = 0; entry < 2; entry++) { + s11_expect_stamped_line(testname, listing + 32 + entry * cases[i].line, + cases[i].line, cases[i].type, cases[i].gap, cases[i].stamp); + } + } +} + +// SI-149: a GEOS file in a mounted image is listed with the type its own directory entry +// carries, and a read over the bus delivers the file rather than the CVT container the +// file browser builds around it. Reported on issue #917, where a GEOS disk mapped as a +// partition listed every file as SEQ. The extension the image file system gives a GEOS +// entry is CVT, which the IEC name builder did not recognise, so the type fell back to +// SEQ; the open then took the branch that puts a header block in front of the data. +// +// The read half of this case is a regression guard. 3.14 and 3.14d passed +// FA_OPEN_FROM_CBM from the IEC open and received the file; commit 76d887bd rewrote that +// open and dropped the argument, so 3.15 received the CVT container. Anyone rewriting +// setup_file_access() again fails here rather than shipping the same loss twice. +static void s11_si149_geos_entries(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI149-GeosEntries"; + const char *path = s11_partition(fm, dr, "si149"); + create_iec_geos_fixture("output/iec_geos_cases.d64"); + char host[96]; + snprintf(host, sizeof(host), "%s/GEOS.D64", path); + REQUIRE(copy_to("output/iec_geos_cases.d64", host) == FR_OK); + expect_command_ok(testname, dr, "CD:GEOS.D64\r"); + + // The listed type, taken from each entry's own type bits. + static const struct { const char *name; const char *type; } listed[] = { + { "\"GEOSPRG\"", "PRG" }, + { "\"GEOSSEQ\"", "SEQ" }, + { "\"GEOSUSR\"", "USR" }, + { "\"PLAINPRG\"", "PRG" }, + }; + for (int i = 0; i < 4; i++) { + // Every entry is one block, so BASIC prints one digit and the type sits at a + // fixed column: the gap behind the name shortens as the name grows. + char expected[48]; + snprintf(expected, sizeof(expected), "%s%*s%s", listed[i].name, + (int)(19 - strlen(listed[i].name)), "", listed[i].type); + expect_directory_contains(testname, dr, "$", expected); + } + + // The bytes a read delivers. A CVT stream starts with the directory entry, so its + // first byte would be the type byte 0x82 and not the load address of the file. + expect_iec_file(testname, dr, 2, "GEOSPRG", "\x01\x08GEOS:PRG"); + expect_iec_file(testname, dr, 2, "GEOSSEQ", "GEOS:SEQ"); + expect_iec_file(testname, dr, 2, "PLAINPRG", "\x01\x08PLAIN:PRG"); + + // A VLIR file points at a record block, which a drive hands over as a whole sector. + // Before the change this read answered nothing and logged a channel fault. + uint8_t vlir[512]; + memset(vlir, 0, sizeof(vlir)); + open_file(dr, 2, "GEOSUSR"); + get_status(dr); + expect_status_ok(testname, "GEOSUSR"); + int got = read_file(dr, 2, vlir, sizeof(vlir)); + printf("%s: GEOSUSR read %d bytes, first four %02x %02x %02x %02x\n", + testname, got, vlir[0], vlir[1], vlir[2], vlir[3]); + REQUIRE(got == 254); + REQUIRE(vlir[0] == 17); + REQUIRE(vlir[1] == 11); + REQUIRE(memcmp(vlir + 2, "VLIR", 4) == 0); + close_file(dr, 2); + expect_status_ok(testname, "GEOSUSR"); +} + +// SI-134: $:*=H lists what $:* lists; H shows hidden files and filters nothing out. +static void s11_si134_hidden_flag(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI134-HiddenFlag"; + const char *path = s11_partition(fm, dr, "si134"); + uint32_t tr; + REQUIRE(fm->save_file(true, path, "VISIBLE.prg", (const uint8_t *)"V", 1, &tr) == FR_OK); + expect_command_ok(testname, dr, "MD:FOLDER\r"); + uint8_t all[4096], hidden[4096]; + int n_all = read_directory_stream(testname, dr, "$:*", all, sizeof(all)); + int n_hidden = read_directory_stream(testname, dr, "$:*=H", hidden, sizeof(hidden)); + printf("%s: $:* is %d bytes, $:*=H is %d bytes\n", testname, n_all, n_hidden); + REQUIRE(s11_listing_line(hidden, n_hidden, "VISIBLE") != NULL); + REQUIRE(s11_listing_line(hidden, n_hidden, "FOLDER") != NULL); + REQUIRE(n_all == n_hidden); +} + +// SI-065: the header of a listing carries the listed directory's own name, and the +// partition's name only at the root. +static void s11_si065_header_name(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI065-HeaderName"; + s11_partition(fm, dr, "si065"); + expect_command_ok(testname, dr, "MD:GAMES\r"); + expect_command_ok(testname, dr, "MD/GAMES/:ACTION\r"); + uint8_t listing[4096]; + char header[17]; + header[16] = 0; + read_directory_stream(testname, dr, "$/GAMES/", listing, sizeof(listing)); + memcpy(header, listing + 8, 16); + printf("%s: header of $/GAMES/ is '%s'\n", testname, header); + REQUIRE(memcmp(listing + 8, "GAMES ", 16) == 0); + expect_command_ok(testname, dr, "CD//GAMES/ACTION\r"); + read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + memcpy(header, listing + 8, 16); + printf("%s: header of $ in ACTION is '%s'\n", testname, header); + REQUIRE(memcmp(listing + 8, "ACTION ", 16) == 0); + read_directory_stream(testname, dr, "$//", listing, sizeof(listing)); + memcpy(header, listing + 8, 16); + printf("%s: header of $// is '%s'\n", testname, header); + REQUIRE(memcmp(listing + 8, "SUITE11 ", 16) == 0); +} + +// SI-032 and SI-148: opening a name for writing. A wildcard without @ is an illegal +// name (33). With @, the first match is replaced under its own name when its type is +// the one asked for, and anything else answers 64: another type, a relative file, or no +// match at all (1541 ROM $D8F5). A name that starts with a shifted space is refused the +// same way. +static void s11_si032_wildcard_write(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI032-WildcardWrite"; + const char *path = s11_partition(fm, dr, "si032"); + char host[80]; + expect_iec_write_ok(testname, dr, 1, "FOOBAR", "old"); + expect_iec_write_ok(testname, dr, 2, "FOOSEQ,S,W", "seq"); + + // @ and a pattern matching a PRG, from a SAVE: the PRG is replaced, name and all. + expect_iec_write_ok(testname, dr, 1, "@:FOOB*", "new"); + expect_iec_file(testname, dr, 0, "FOOBAR", "new"); + snprintf(host, sizeof(host), "%s/FOOB*.prg", path); + expect_path_absent(testname, fm, host); + // @ and a pattern whose first match is not the type asked for. + expect_iec_open_status_prefix(testname, dr, 1, "@:FOOS*", "64,FILE TYPE MISMATCH"); + close_file(dr, 1); + expect_iec_file(testname, dr, 2, "FOOSEQ,S,R", "seq"); + // @ and a pattern that matches nothing. + expect_iec_open_status_prefix(testname, dr, 1, "@:NOMATCH*", "64,FILE TYPE MISMATCH"); + close_file(dr, 1); + // @ and a pattern matching a relative file. + expect_rel_open(testname, dr, 3, "FOOREL", 16); + close_file(dr, 3); + expect_iec_open_status_prefix(testname, dr, 2, "@:FOOR*,S,W", "64,FILE TYPE MISMATCH"); + close_file(dr, 2); + // No @: a wildcard in a name to write is an illegal name. + expect_iec_open_status_prefix(testname, dr, 1, "FOO*", "33,SYNTAX ERROR"); + close_file(dr, 1); + expect_iec_open_status_prefix(testname, dr, 2, "FOO?AR,S,W", "33,SYNTAX ERROR"); + close_file(dr, 2); + // SI-148: a name that starts with a shifted space is no name to create. + expect_iec_open_status_prefix(testname, dr, 2, "@:\xA0NAME,S,W", "64,FILE TYPE MISMATCH"); + close_file(dr, 2); + expect_iec_open_status_prefix(testname, dr, 2, "\xA0NAME,S,W", "33,SYNTAX ERROR"); + close_file(dr, 2); +} + +// SI-041 and SI-042: G-P with 0 asks about the system partition, which this drive does +// not have; bytes 27 to 29 are the partition's size in 512 byte blocks; byte 1 is 0. +static void s11_si041_partition_size(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI041-PartitionSize"; + s11_partition(fm, dr, "si041"); + const uint8_t system[4] = { 'G', '-', 'P', 0 }; + send_command_data(dr, system, sizeof(system)); + get_status(dr); + printf("%s: G-P 0 answered %d bytes, type %d, partition %d\n", testname, last_status_size, + (uint8_t)last_status[0], (uint8_t)last_status[2]); + REQUIRE(last_status_size == 31); + REQUIRE((last_status[0] == 0) && (last_status[1] == 0) && (last_status[2] == 0)); + + // A D64 image is 174848 bytes, 342 blocks of 512 rounded up. + create_formatted_image(fm, "/Fat/s11_si041.d64", "SIZED", 683, e_image_d64); + dr->add_partition(44, "/Fat/s11_si041.d64", "SIZED"); + const uint8_t gp44[4] = { 'G', '-', 'P', 44 }; + send_command_data(dr, gp44, sizeof(gp44)); + get_status(dr); + int blocks = ((uint8_t)last_status[27] << 16) | ((uint8_t)last_status[28] << 8) | (uint8_t)last_status[29]; + printf("%s: G-P 44 type %d, byte 1 %d, size %d blocks\n", testname, (uint8_t)last_status[0], + (uint8_t)last_status[1], blocks); + REQUIRE(last_status_size == 31); + REQUIRE((last_status[0] == 2) && (last_status[1] == 0) && (last_status[2] == 44)); + REQUIRE(blocks == 342); + + // A directory partition reports its volume: the 16 MB FAT file this suite runs on, + // which is no more than 32768 blocks and no less than what is free on it. + const uint8_t gp40[4] = { 'G', '-', 'P', 40 }; + send_command_data(dr, gp40, sizeof(gp40)); + get_status(dr); + blocks = ((uint8_t)last_status[27] << 16) | ((uint8_t)last_status[28] << 8) | (uint8_t)last_status[29]; + Path fat_path("/Fat/"); + uint32_t free_clusters = 0, cluster_size = 0; + REQUIRE(fm->get_free(&fat_path, free_clusters, cluster_size) == FR_OK); + uint32_t free_blocks = (uint32_t)(((uint64_t)free_clusters * cluster_size) / 512); + printf("%s: G-P 40 size %d blocks, %u blocks free on the volume\n", testname, blocks, free_blocks); + REQUIRE((blocks <= 32768) && (blocks >= (int)free_blocks) && (blocks > 0)); +} + +// SI-072: a file named with a disk image or cartridge extension is stored under exactly +// that name, without a type extension, so a PC sees GAME.D81 and not GAME.D81.prg. +static void s11_si072_raw_names(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI072-RawNames"; + const char *path = s11_partition(fm, dr, "si072"); + static const char *names[] = { "X.D81", "Y.D64", "Z.DNP", "GAME.CRT", "GAME.TCRT" }; + char host[80]; + FileInfo info(16); + char open_name[40]; + for (int i = 0; i < 5; i++) { + snprintf(open_name, sizeof(open_name), "%s,P,W", names[i]); + expect_iec_write_ok(testname, dr, 2, open_name, "raw"); + snprintf(host, sizeof(host), "%s/%s", path, names[i]); + if (fm->fstat(host, info) != FR_OK) { + printf("%s: expected host file '%s'\n", testname, host); + } + REQUIRE(fm->fstat(host, info) == FR_OK); + snprintf(host, sizeof(host), "%s/%s.prg", path, names[i]); + if (fm->fstat(host, info) == FR_OK) { + printf("%s: host file '%s' should not exist\n", testname, host); + } + REQUIRE(fm->fstat(host, info) != FR_OK); + } + expect_iec_file(testname, dr, 0, "X.D81", "raw"); + // Any other extension still gets the type. + expect_iec_write_ok(testname, dr, 2, "NOTES.TXT,S,W", "typed"); + snprintf(host, sizeof(host), "%s/NOTES.TXT.seq", path); + REQUIRE(fm->fstat(host, info) == FR_OK); +} + +// SI-074: a rename refuses a name that exists with any type (63) and an empty name (34), +// and moves a file into another directory of the partition, as it did before. +// Whether a directory listing carries a run of bytes, for a case that has to assert +// that an entry is gone as well as that one is there. +static bool listing_holds(const uint8_t *listing, int got, const char *text) +{ + int len = strlen(text); + for (int i = 0; i <= got - len; i++) { + if (memcmp(listing + i, text, len) == 0) { + return true; + } + } + return false; +} + +static void s11_si074_rename_checks(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI074-RenameChecks"; + s11_partition(fm, dr, "si074"); + expect_command_ok(testname, dr, "MD:SUB\r"); + expect_iec_write_ok(testname, dr, 1, "OLD", "old"); + expect_iec_write_ok(testname, dr, 2, "NEW,S,W", "new"); + expect_command_ok(testname, dr, "R/SUB/:MOVED=OLD\r"); + expect_iec_file(testname, dr, 0, "/SUB/:MOVED", "old"); + expect_command_ok(testname, dr, "R:OLD=/SUB/:MOVED\r"); + expect_iec_file(testname, dr, 0, "OLD", "old"); + expect_command_response(testname, dr, "R:NEW=OLD\r", "63,FILE EXISTS,00,00\r"); + expect_iec_file(testname, dr, 0, "OLD", "old"); + expect_command_response(testname, dr, "R:=OLD\r", "34,SYNTAX ERROR,00,00\r"); + expect_command_ok(testname, dr, "R:FRESH=OLD\r"); + expect_iec_file(testname, dr, 0, "FRESH", "old"); + + // A subdirectory is renamed under its own name, as HD 9-26 "Renaming Files and + // Subdirectories" describes and as SD parse_rename() does: it matches an entry of + // any type, so a directory entry is found. + expect_command_ok(testname, dr, "MD:DIRA\r"); + expect_command_ok(testname, dr, "R:DIRB=DIRA\r"); + uint8_t listing[4096]; + int got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + REQUIRE(listing_holds(listing, got, "\"DIRB\"")); + REQUIRE(!listing_holds(listing, got, "\"DIRA\"")); + // The renamed directory is still a directory, and can be entered under its new name. + REQUIRE(listing_holds(listing, got, "DIR")); + expect_command_ok(testname, dr, "CD:DIRB\r"); + expect_command_ok(testname, dr, "CD//\r"); + // The name a directory already has is refused for a file and for another directory. + expect_command_response(testname, dr, "R:DIRB=FRESH\r", "63,FILE EXISTS,00,00\r"); + expect_command_ok(testname, dr, "MD:DIRC\r"); + expect_command_response(testname, dr, "R:DIRB=DIRC\r", "63,FILE EXISTS,00,00\r"); + // A name that belongs to nothing still answers 62. + expect_command_response(testname, dr, "R:DIRD=NOSUCHDIR\r", "62,FILE NOT FOUND,00,00\r"); +} + +// SI-083: P on a file opened for writing moves past the end, and the next write extends +// the file. This is JiffyDOS's MD81, as the reporter's #877 excerpt shows it: open +// FOO.D81,P,W, position to 819199, write one byte, close. +static void s11_si083_seek_write(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI083-SeekWrite"; + const char *path = s11_partition(fm, dr, "si083"); + const uint8_t chan = 2; + open_file(dr, chan, "FOO.D81,P,W"); + get_status(dr); + expect_status_ok(testname, "FOO.D81,P,W"); + const uint8_t md81[6] = { 'P', (uint8_t)(96 + chan), 0xFF, 0x7F, 0x0C, 0x00 }; + expect_command_data_response(testname, dr, md81, sizeof(md81), "00, OK,00,00\r"); + const uint8_t last = 0x42; + send_channel_data(dr, chan, &last, 1); + close_file(dr, chan); + expect_status_ok(testname, "close FOO.D81"); + char host[80]; + snprintf(host, sizeof(host), "%s/FOO.D81", path); + FileInfo info(16); + REQUIRE(fm->fstat(host, info) == FR_OK); + printf("%s: FOO.D81 is %u bytes\n", testname, (unsigned)info.size); + REQUIRE(info.size == 819200); + expect_command_response(testname, dr, "S:FOO.D81\r", "01, FILES SCRATCHED,01,00\r"); + + // What was written before the position is kept, and the write lands where P put it. + open_file(dr, chan, "HOLES,S,W"); + get_status(dr); + send_channel_data(dr, chan, (const uint8_t *)"HEAD", 4); + const uint8_t p1000[6] = { 'P', (uint8_t)(96 + chan), 0xE8, 0x03, 0x00, 0x00 }; + expect_command_data_response(testname, dr, p1000, sizeof(p1000), "00, OK,00,00\r"); + send_channel_data(dr, chan, (const uint8_t *)"TAIL", 4); + close_file(dr, chan); + uint8_t content[1100]; + open_file(dr, 3, "HOLES,S,R"); + get_status(dr); + int got = read_file(dr, 3, content, sizeof(content)); + close_file(dr, 3); + printf("%s: HOLES is %d bytes\n", testname, got); + REQUIRE(got == 1004); + REQUIRE(memcmp(content, "HEAD", 4) == 0); + REQUIRE(memcmp(content + 1000, "TAIL", 4) == 0); +} + +// SI-083 and SI-036: inside a disk image a file cannot be positioned past its end, and +// the answer is 72, which CBM DOS names, not the Ultimate's 69. +static void s11_si083_seek_write_image(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI083-SeekWriteImage"; + s11_partition(fm, dr, "si083i"); + create_formatted_image(fm, "/Fat/s11_si083.d81", "SEEK", 3200, e_image_d81); + dr->add_partition(45, "/Fat/s11_si083.d81", "SEEKIMAGE"); + const uint8_t chan = 2; + open_file(dr, chan, "45:FOO,P,W"); + get_status(dr); + expect_status_ok(testname, "45:FOO,P,W"); + const uint8_t md81[6] = { 'P', (uint8_t)(96 + chan), 0xFF, 0x7F, 0x0C, 0x00 }; + expect_command_data_response(testname, dr, md81, sizeof(md81), "72,DISK FULL,00,00\r"); + close_file(dr, chan); +} + +static uint32_t s11_host_size(FileManager *fm, const char *dir, const char *name) +{ + char host[96]; + snprintf(host, sizeof(host), "%s/%s", dir, name); + FileInfo info(16); + if (fm->fstat(host, info) != FR_OK) { + return 0; + } + return info.size; +} - execute_suite8(fm, dr); - run_suite9_block_matrix(fm, dr); - execute_suite3(fm, dr); - execute_suite4(fm, dr); - execute_suite5(fm, dr); - execute_suite6(fm, dr); - execute_suite7(fm, dr); - execute_suite10(fm, dr); - execute_suite12(fm); +// SI-071: N:name[,id] creates a disk image, or formats one, the way sd2iec does, because +// this drive has no medium of its own to format. The extension picks the format; no +// extension means .D64, and then an existing file is not overwritten. +static void s11_si071_format(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI071-Format"; + const char *path = s11_partition(fm, dr, "si071"); + static const struct { const char *cmd; const char *file; uint32_t size; } images[] = { + { "N:ONE.D64,AA\r", "ONE.D64", 174848 }, + { "N:TWO.D71,AB\r", "TWO.D71", 349696 }, + { "N:THREE.D81,AC\r", "THREE.D81", 819200 }, + }; + for (int i = 0; i < 3; i++) { + expect_command_ok(testname, dr, images[i].cmd); + uint32_t size = s11_host_size(fm, path, images[i].file); + printf("%s: %s is %u bytes, expected %u\n", testname, images[i].file, size, images[i].size); + REQUIRE(size == images[i].size); + } + // A created image mounts, lists with its label, and takes files. + expect_command_ok(testname, dr, "CD:ONE.D64\r"); + expect_directory_contains(testname, dr, "$", "\"ONE "); + expect_iec_write_ok(testname, dr, 2, "INSIDE,S,W", "in the image"); + expect_iec_file(testname, dr, 2, "INSIDE,S,R", "in the image"); + expect_command_ok(testname, dr, "CD:_\r"); + // Given explicitly, an existing image's extension means format it again. + expect_command_ok(testname, dr, "N:ONE.D64,ZZ\r"); + expect_command_ok(testname, dr, "CD:ONE.D64\r"); + expect_iec_file_missing(testname, dr, 2, "INSIDE,S,R"); + expect_command_ok(testname, dr, "CD:_\r"); + + // A DNP takes a three digit track count as its id and is created, not formatted. + expect_command_ok(testname, dr, "N:FOUR.DNP,002\r"); + REQUIRE(s11_host_size(fm, path, "FOUR.DNP") == 2 * 65536); + expect_command_response(testname, dr, "N:FOUR.DNP,002\r", "63,FILE EXISTS,00,00\r"); + + // No extension: .D64 is added, and an existing one is left alone. + expect_command_ok(testname, dr, "N:PLAIN,PL\r"); + REQUIRE(s11_host_size(fm, path, "PLAIN.D64") == 174848); + expect_command_response(testname, dr, "N:PLAIN,PL\r", "63,FILE EXISTS,00,00\r"); + + // A new image needs an id, of two or three characters; the name needs a colon. + expect_command_response(testname, dr, "N:NOID.D64\r", "30,SYNTAX ERROR,00,00\r"); + REQUIRE(s11_host_size(fm, path, "NOID.D64") == 0); + expect_command_response(testname, dr, "N:BADID.D64,A\r", "30,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "N:BADDNP.DNP,12\r", "30,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "NNOCOLON,AA\r", "34,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "N:,AA\r", "34,SYNTAX ERROR,00,00\r"); + // Room for the image is checked before anything is created. + expect_command_response(testname, dr, "N:HUGE.DNP,255\r", "72,DISK FULL,00,00\r"); + REQUIRE(s11_host_size(fm, path, "HUGE.DNP") == 0); + + // A full sixteen character label keeps its extension. + expect_command_ok(testname, dr, "N:ABCDEFGHIJKLMNOP.D81,AB\r"); + REQUIRE(s11_host_size(fm, path, "ABCDEFGHIJKLMNOP.D81") == 819200); + // Inside a disk image N is refused rather than creating an image in the image. + expect_command_ok(testname, dr, "CD:ONE.D64\r"); + expect_command_response(testname, dr, "N:WORK,01\r", "30,SYNTAX ERROR,00,00\r"); + expect_iec_file_missing(testname, dr, 2, "WORK.D64,S,R"); + expect_command_ok(testname, dr, "CD:_\r"); + + expect_command_response(testname, dr, "S:*\r", "01, FILES SCRATCHED,06,00\r"); +} + +// SI-147 and SI-148: a shifted space ($A0) is a legal byte inside a name and maps to +// {A0}; a trailing run is padding and is dropped; a file an older build named with the +// padding kept is still found by its CBM name; and a listing shows the name up to its +// terminator, not up to the first $A0. testdrive is also built with -funsigned-char +// (target/pc/linux/iecdrive_unsigned), because the rule depended on char signedness. +static void s11_si147_shifted_space(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI147-ShiftedSpace"; + const char *path = s11_partition(fm, dr, "si147"); + FileInfo info(16); + char host[80]; + + expect_iec_write_ok(testname, dr, 2, "AB\xA0,S,W", "padded"); + snprintf(host, sizeof(host), "%s/AB.seq", path); + if (fm->fstat(host, info) != FR_OK) { + printf("%s: expected host file '%s'\n", testname, host); + } + REQUIRE(fm->fstat(host, info) == FR_OK); + expect_iec_file(testname, dr, 2, "AB\xA0,S,R", "padded"); + expect_iec_file(testname, dr, 2, "AB,S,R", "padded"); + + expect_iec_write_ok(testname, dr, 2, "A\xA0" "B,S,W", "inside"); + snprintf(host, sizeof(host), "%s/A{A0}B.seq", path); + if (fm->fstat(host, info) != FR_OK) { + printf("%s: expected host file '%s'\n", testname, host); + } + REQUIRE(fm->fstat(host, info) == FR_OK); + expect_directory_contains(testname, dr, "$", "\"A\xA0" "B\""); + + // A host name an earlier build produced with the padding escaped. + uint32_t tr; + REQUIRE(fm->save_file(true, path, "LEGACY{A0}.prg", (const uint8_t *)"old name", 8, &tr) == FR_OK); + expect_iec_file(testname, dr, 0, "LEGACY\xA0", "old name"); +} + +// SI-142: a host name escapes * and ?, so a pattern is matched against the CBM names +// by the drive and never by the host file system: a scratch, an RD and an open by +// pattern still find what they name, on a host directory and inside an image. +static void s11_si142_escaped_wildcards(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI142-EscapedWildcards"; + s11_partition(fm, dr, "si142"); + expect_iec_write_ok(testname, dr, 2, "FILE1,S,W", "one"); + expect_iec_write_ok(testname, dr, 2, "FILE2,S,W", "two"); + expect_iec_write_ok(testname, dr, 2, "OTHER,S,W", "other"); + expect_iec_file(testname, dr, 2, "FIL*,S,R", "one"); + expect_command_response(testname, dr, "S:FIL*\r", "01, FILES SCRATCHED,02,00\r"); + expect_iec_file(testname, dr, 2, "OTHER,S,R", "other"); + expect_command_ok(testname, dr, "MD:ABCDIR\r"); + expect_command_ok(testname, dr, "RD:ABC*\r"); + expect_directory_contains(testname, dr, "$", "\"OTHER\""); + create_formatted_image(fm, "/Fat/s11_si142.d64", "PATTERNS", 683, e_image_d64); + expect_command_ok(testname, dr, "CD//\r"); + dr->add_partition(46, "/Fat/s11_si142.d64", "PATTERNS"); + expect_iec_write_ok(testname, dr, 2, "46:GAME1,P,W", "g1"); + expect_iec_write_ok(testname, dr, 2, "46:GAME2,P,W", "g2"); + expect_command_response(testname, dr, "S46:GAME?\r", "01, FILES SCRATCHED,02,00\r"); +} + +// The type field of the listing line for `name`, and the character behind it, which is +// the lock marker. +static void s11_listing_type(IecDrive *dr, const char *testname, const char *dir, const char *name, + char *type, bool *present) +{ + uint8_t listing[4096]; + int got = read_directory_stream(testname, dr, dir, listing, sizeof(listing)); + const uint8_t *line = s11_listing_line(listing, got, name); + *present = (line != NULL); + type[0] = 0; + if (line) { + int blocks = line[2] | (line[3] << 8); + int digits = (blocks >= 100) ? 3 : (blocks >= 10) ? 2 : 1; + memcpy(type, line + 27 - digits, 4); + type[4] = 0; + } +} + +// SI-076 and SI-132: L toggles the lock of a file or a directory. A locked file lists +// with < behind its type and is not scratched; a locked directory is not removed. +static void s11_si076_lock(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI076-Lock"; + s11_partition(fm, dr, "si076"); + char type[8]; + bool present; + expect_iec_write_ok(testname, dr, 1, "LOCKME", "keep"); + expect_command_ok(testname, dr, "L:LOCKME\r"); + s11_listing_type(dr, testname, "$", "LOCKME", type, &present); + printf("%s: locked file lists as '%s'\n", testname, type); + REQUIRE(present && !strcmp(type, "PRG<")); + expect_command_response(testname, dr, "S:LOCKME\r", "01, FILES SCRATCHED,00,00\r"); + expect_iec_file(testname, dr, 0, "LOCKME", "keep"); + expect_command_ok(testname, dr, "L:LOCKME\r"); + s11_listing_type(dr, testname, "$", "LOCKME", type, &present); + REQUIRE(present && !strcmp(type, "PRG ")); + expect_command_response(testname, dr, "S:LOCKME\r", "01, FILES SCRATCHED,01,00\r"); + + expect_command_ok(testname, dr, "MD:LOCKDIR\r"); + expect_command_ok(testname, dr, "L:LOCKDIR\r"); + expect_command_status_prefix(testname, dr, "RD:LOCKDIR\r", "63,"); + expect_command_ok(testname, dr, "L:LOCKDIR\r"); + expect_command_ok(testname, dr, "RD:LOCKDIR\r"); + expect_command_response(testname, dr, "L:NOSUCH\r", "62,FILE NOT FOUND,00,00\r"); + + // Inside a disk image the lock is the CBM lock bit. + create_formatted_image(fm, "/Fat/s11_si076.d64", "LOCKS", 683, e_image_d64); + dr->add_partition(47, "/Fat/s11_si076.d64", "LOCKS"); + expect_iec_write_ok(testname, dr, 1, "47:INIMAGE", "img"); + expect_command_ok(testname, dr, "L47:INIMAGE\r"); + s11_listing_type(dr, testname, "$47", "INIMAGE", type, &present); + printf("%s: locked file in a D64 lists as '%s'\n", testname, type); + REQUIRE(present && !strcmp(type, "PRG<")); + expect_command_response(testname, dr, "S47:INIMAGE\r", "01, FILES SCRATCHED,00,00\r"); +} + +// A 1541 image on partition `part`, selected, with a buffer channel open on `chan`. +static void s11_block_partition(FileManager *fm, IecDrive *dr, const char *testname, int part, + const char *image, uint8_t chan) +{ + char cmd[16]; + create_formatted_image(fm, image, "BLOCKS", 683, e_image_d64); + dr->add_partition(part, image, "BLOCKS"); + snprintf(cmd, sizeof(cmd), "CP%d\r", part); + expect_command_status_prefix(testname, dr, cmd, "02,PARTITION SELECTED"); + open_buffer_channel(testname, dr, chan); +} + +// SI-090: a standard buffer starts with its pointer at byte 1, so what is written right +// after the open lands from byte 1 on. +static void s11_si090_buffer_pointer(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI090-BufferPointer"; + s11_block_partition(fm, dr, testname, 49, "/Fat/s11_si090.d64", 2); + send_channel_data(dr, 2, (const uint8_t *)"ABC", 3); + expect_command_ok(testname, dr, "U2:2,0,1,0\r"); + expect_command_ok(testname, dr, "U1:2,0,1,0\r"); + uint8_t sector[256]; + read_buffer_channel(testname, dr, 2, sector, sizeof(sector)); + printf("%s: bytes 1 to 3 are %02X %02X %02X\n", testname, sector[1], sector[2], sector[3]); + REQUIRE(memcmp(sector + 1, "ABC", 3) == 0); + close_file(dr, 2); +} + +// SI-093 and SI-013: a direct access channel keeps the partition that was current when +// it was opened, and the partition number in a block command is ignored. +static void s11_si093_bound_partition(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI093-BoundPartition"; + s11_partition(fm, dr, "si093"); + s11_block_partition(fm, dr, testname, 50, "/Fat/s11_si093.d64", 2); + expect_command_response(testname, dr, "CP40\r", "02,PARTITION SELECTED,40,00\r"); + expect_command_ok(testname, dr, "U1:2,0,18,0\r"); + uint8_t bam[256]; + read_buffer_channel(testname, dr, 2, bam, sizeof(bam)); + printf("%s: the channel read %02X %02X %02X from 18/0\n", testname, bam[0], bam[1], bam[2]); + REQUIRE((bam[0] == 18) && (bam[1] == 1) && (bam[2] == 'A')); + expect_command_ok(testname, dr, "U1:2,40,18,0\r"); + read_buffer_channel(testname, dr, 2, bam, sizeof(bam)); + REQUIRE((bam[0] == 18) && (bam[1] == 1) && (bam[2] == 'A')); + close_file(dr, 2); +} + +// SI-094: B-R takes the number of bytes from the first byte of the block and starts at +// the second; B-W stores the buffer pointer minus one there. U1 and U2 do neither. +static void s11_si094_block_length(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI094-BlockLength"; + s11_block_partition(fm, dr, testname, 51, "/Fat/s11_si094.d64", 2); + uint8_t block[256]; + memset(block, 0, sizeof(block)); + block[0] = 5; + memcpy(block + 1, "HELLO", 5); + expect_command_ok(testname, dr, "B-P 2 0\r"); + send_channel_data(dr, 2, block, sizeof(block)); + expect_command_ok(testname, dr, "U2:2,0,1,1\r"); + expect_command_ok(testname, dr, "B-R:2,0,1,1\r"); + uint8_t got[256]; + int n = read_file(dr, 2, got, sizeof(got)); + printf("%s: B-R made %d bytes available\n", testname, n); + REQUIRE((n == 5) && (memcmp(got, "HELLO", 5) == 0)); + + expect_command_ok(testname, dr, "B-P 2 1\r"); + send_channel_data(dr, 2, (const uint8_t *)"ABC", 3); + expect_command_ok(testname, dr, "B-W:2,0,1,2\r"); + expect_command_ok(testname, dr, "U1:2,0,1,2\r"); + read_buffer_channel(testname, dr, 2, got, 256); + printf("%s: B-W stored %d in byte 0\n", testname, got[0]); + REQUIRE((got[0] == 3) && (memcmp(got + 1, "ABC", 3) == 0)); + close_file(dr, 2); +} + +extern int iec_interface_configure_calls; // counted by the interface stub + +// SI-103: UJ closes the data channels, keeping the partition and its directory, and +// U+shifted J also returns every partition to its root and selects partition 1. Both +// answer 73. Neither may reconfigure the IEC interface, which on the device holds the +// IEC processor in reset, so the command channel has to go on answering. +static void s11_si103_resets(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI103-Resets"; + s11_partition(fm, dr, "si103"); + expect_command_ok(testname, dr, "MD:SUB\r"); + expect_command_ok(testname, dr, "CD:SUB\r"); + open_file(dr, 1, "KEPT"); + get_status(dr); + expect_status_ok(testname, "KEPT"); + send_channel_data(dr, 1, (const uint8_t *)"abc", 3); + + int configured = iec_interface_configure_calls; + expect_command_status_prefix(testname, dr, "UJ\r", "73,"); + printf("%s: interface configured %d times by UJ\n", testname, iec_interface_configure_calls - configured); + REQUIRE(iec_interface_configure_calls == configured); + expect_command_response(testname, dr, "XPWD\r", "40:/SUB/"); + expect_iec_file(testname, dr, 0, "KEPT", "abc"); + + expect_command_status_prefix(testname, dr, "U\xCA\r", "73,"); + REQUIRE(iec_interface_configure_calls == configured); + expect_command_response(testname, dr, "XPWD\r", "1:/"); + expect_command_response(testname, dr, "CP40\r", "02,PARTITION SELECTED,40,00\r"); + expect_command_response(testname, dr, "XPWD\r", "40:/"); +} + +// A host file of `len` bytes: an x00 header naming `cbm_name` with `record_length` at +// offset 25 when `cbm_name` is given, then `data`. +static void s11_host_file(FileManager *fm, const char *dir, const char *host, const char *cbm_name, + uint8_t record_length, const uint8_t *data, int len) +{ + const char *testname = "Suite11"; + uint8_t content[600]; + int n = 0; + if (cbm_name) { + memset(content, 0, 26); + memcpy(content, "C64File", 7); + memcpy(content + 8, cbm_name, strlen(cbm_name)); + content[25] = record_length; + n = 26; + } + memcpy(content + n, data, len); + uint32_t tr; + REQUIRE(fm->save_file(true, dir, host, content, n + len, &tr) == FR_OK); +} + +// The whole of a host file, or -1 when it does not exist. +static int s11_read_host_file(FileManager *fm, const char *dir, const char *host, uint8_t *out, int size) +{ + uint32_t tr = 0; + if (fm->load_file(dir, host, out, size, &tr) != FR_OK) { + return -1; + } + return (int)tr; +} + +// SI-144: a P00, S00, U00 or R00 file that starts with "C64File" lists under the CBM name +// in its header, with the type of its extension and the size of what follows the 26 byte +// header, and opens by that name with the header skipped. A file with such an extension +// and no signature is an ordinary file. Scratch and rename work on the CBM name, and a +// rename rewrites the name in the header. +static void s11_si144_read_x00(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI144-ReadX00"; + const char *path = s11_partition(fm, dr, "si144"); + s11_host_file(fm, path, "GAME.P00", "MY GAME", 0, (const uint8_t *)"PAYLOAD", 7); + s11_host_file(fm, path, "TEXT.S00", "NOTES", 0, (const uint8_t *)"some text", 9); + s11_host_file(fm, path, "X.P00", NULL, 0, (const uint8_t *)"not wrapped", 11); + + char type[8]; + bool present; + s11_listing_type(dr, testname, "$", "MY GAME", type, &present); + printf("%s: MY GAME listed %d as '%s'\n", testname, present, type); + REQUIRE(present && !strcmp(type, "PRG ")); + s11_listing_type(dr, testname, "$", "NOTES", type, &present); + REQUIRE(present && !strcmp(type, "SEQ ")); + s11_listing_type(dr, testname, "$", "X.P00", type, &present); + printf("%s: X.P00 listed %d as '%s'\n", testname, present, type); + REQUIRE(present); + uint8_t listing[4096]; + int got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + const uint8_t *line = s11_listing_line(listing, got, "MY GAME"); + REQUIRE(line && (line[0] == (7 % 254) + 2)); + + expect_iec_file(testname, dr, 0, "MY GAME", "PAYLOAD"); + expect_iec_file(testname, dr, 2, "NOTES,S", "some text"); + expect_iec_file(testname, dr, 2, "X.P00,S", "not wrapped"); + + // An append lands after the data and P counts from the start of the data. + expect_iec_write_ok(testname, dr, 2, "NOTES,S,A", "!"); + expect_iec_file(testname, dr, 2, "NOTES,S", "some text!"); + open_file(dr, 3, "MY GAME,P"); + get_status(dr); + expect_status_ok(testname, "MY GAME,P"); + expect_rel_position_status(testname, dr, 3, 3, 0, "00, OK,00,00\r"); + uint8_t rest[16]; + int count = read_file(dr, 3, rest, sizeof(rest)); + rest[(count > 0) && (count < 16) ? count : 0] = 0; + printf("%s: after P 3 the file reads '%s'\n", testname, (char *)rest); + REQUIRE((count == 4) && (memcmp(rest, "LOAD", 4) == 0)); + close_file(dr, 3); + + expect_command_ok(testname, dr, "R:TUNES=NOTES\r"); + uint8_t host[64]; + got = s11_read_host_file(fm, path, "TEXT.S00", host, sizeof(host)); + printf("%s: after the rename TEXT.S00 is %d bytes, name '%s'\n", testname, got, (char *)host + 8); + REQUIRE((got == 36) && (memcmp(host + 8, "TUNES\0", 6) == 0)); + expect_iec_file(testname, dr, 2, "TUNES,S", "some text!"); + expect_command_response(testname, dr, "S:TUNES\r", "01, FILES SCRATCHED,01,00\r"); + REQUIRE(s11_read_host_file(fm, path, "TEXT.S00", host, sizeof(host)) < 0); + expect_command_response(testname, dr, "S:MY*\r", "01, FILES SCRATCHED,01,00\r"); + REQUIRE(s11_read_host_file(fm, path, "GAME.P00", host, sizeof(host)) < 0); +} + +// SI-084 and SI-146: a relative file is read in this firmware's two byte layout, sd2iec's +// one byte layout, or inside an R00 wrapper, which an open with a record length finds by +// its CBM name rather than creating the file again beside it. +static void s11_si084_rel_layouts(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI084-RelLayouts"; + const char *path = s11_partition(fm, dr, "si084"); + const int lengths[] = { 2, 3, 127, 254 }; + for (int i = 0; i < 4; i++) { + int r = lengths[i]; + for (int layout = 1; layout <= 2; layout++) { + // A zero second byte first: that is the file the old reader misread silently. + for (int zero_first = 1; zero_first >= 0; zero_first--) { + uint8_t data[600]; + memset(data, 0, sizeof(data)); + data[0] = (uint8_t)r; + int n = layout; + for (int rec = 0; rec < 2; rec++) { + for (int b = 0; b < r; b++) { + data[n + b] = (uint8_t)('A' + rec); + } + if (zero_first && (rec == 0)) { + data[n] = 0; // byte 1 of a one byte layout file is then zero too + } + n += r; + } + char host[24], name[16]; + snprintf(name, sizeof(name), "R%dL%dZ%d", r, layout, zero_first); + snprintf(host, sizeof(host), "%s.rel", name); + uint32_t tr; + REQUIRE(fm->save_file(true, path, host, data, n, &tr) == FR_OK); + expect_rel_open(testname, dr, 2, name, 0); + expect_rel_position_status(testname, dr, 2, 2, 1, "00, OK,00,00\r"); + uint8_t expected[256]; + memset(expected, 'B', r); + uint8_t got[256]; + memset(got, 0, sizeof(got)); + int count = read_file(dr, 2, got, sizeof(got)); + printf("%s: %s record 2 read %d bytes starting %02X\n", testname, name, count, got[0]); + REQUIRE((count == r) && (memcmp(got, expected, r) == 0)); + close_file(dr, 2); + } + } + } + + // A record length of 1 cannot be told apart by size; it is taken as the two byte layout. + uint32_t tr; + REQUIRE(fm->save_file(true, path, "ONEBYTE.rel", (const uint8_t *)"\x01\x00" "AB", 4, &tr) == FR_OK); + expect_rel_open(testname, dr, 2, "ONEBYTE", 0); + expect_rel_position_status(testname, dr, 2, 2, 1, "00, OK,00,00\r"); + uint8_t one[4]; + REQUIRE((read_file(dr, 2, one, sizeof(one)) == 1) && (one[0] == 'B')); + close_file(dr, 2); + + // R00: the record length is at offset 25 and the records follow the header. + s11_host_file(fm, path, "WRAP.R00", "WRAPREL", 3, (const uint8_t *)"aaabbb", 6); + expect_rel_open(testname, dr, 2, "WRAPREL", 0); + expect_rel_position_status(testname, dr, 2, 2, 1, "00, OK,00,00\r"); + uint8_t rec[8]; + int count = read_file(dr, 2, rec, sizeof(rec)); + rec[(count > 0) && (count < 8) ? count : 0] = 0; + printf("%s: WRAPREL record 2 read %d bytes '%s'\n", testname, count, (char *)rec); + REQUIRE((count == 3) && (memcmp(rec, "bbb", 3) == 0)); + close_file(dr, 2); + + expect_rel_open(testname, dr, 2, "WRAPREL", 3); + expect_rel_position_status(testname, dr, 2, 1, 1, "00, OK,00,00\r"); + count = read_file(dr, 2, rec, sizeof(rec)); + REQUIRE((count == 3) && (memcmp(rec, "aaa", 3) == 0)); + close_file(dr, 2); + uint8_t host[64]; + REQUIRE(s11_read_host_file(fm, path, "WRAPREL.rel", host, sizeof(host)) < 0); +} + +// SI-144 on the paths that do not find a file through its CBM name: an open without a +// type, for which ConstructPath() makes a pattern; the creation of a name an x00 file +// carries; a copy; a rename into another directory; and a host name longer than a +// listing entry used to hold. +static void s11_x00_paths(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI144-X00Paths"; + const char *path = s11_partition(fm, dr, "x00paths"); + uint8_t host[128]; + s11_host_file(fm, path, "DATA.S00", "DATA", 0, (const uint8_t *)"payload", 7); + expect_iec_file(testname, dr, 2, "DATA", "payload"); + // A copy takes the data and the type, not the header. + expect_command_ok(testname, dr, "C:COPY=DATA\r"); + int got = s11_read_host_file(fm, path, "COPY.seq", host, sizeof(host)); + printf("%s: COPY.seq is %d bytes\n", testname, got); + REQUIRE((got == 7) && (memcmp(host, "payload", 7) == 0)); + // The name is taken: 63 without @, and with @ the new file takes the x00 file's place. + open_file(dr, 2, "DATA,S,W"); + get_status(dr); + expect_current_status(testname, "DATA,S,W", "63,FILE EXISTS,00,00\r"); + close_file(dr, 2); + expect_iec_write_ok(testname, dr, 2, "@:DATA,S,W", "new"); + REQUIRE(s11_read_host_file(fm, path, "DATA.S00", host, sizeof(host)) < 0); + expect_iec_file(testname, dr, 2, "DATA,S", "new"); + // A rename into another directory moves an x00 file, under its host name. + s11_host_file(fm, path, "MOVE.P00", "MOVER", 0, (const uint8_t *)"m", 1); + expect_command_ok(testname, dr, "MD:SUB\r"); + expect_command_ok(testname, dr, "R/SUB/:MOVED=MOVER\r"); + expect_iec_file(testname, dr, 0, "/SUB/:MOVED", "m"); + // A host name longer than forty characters still lists under the CBM name. + s11_host_file(fm, path, "A HOST NAME THAT IS LONGER THAN FORTY CHARACTERS.P00", "LONGWRAP", 0, + (const uint8_t *)"l", 1); + expect_directory_contains(testname, dr, "$", "\"LONGWRAP\""); +} + +// SI-084 inside a disk image: the image presents the two byte layout, so a size that is +// not a whole number of records does not select the one byte layout. +static void s11_rel_in_image(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI084-RelInImage"; + create_formatted_image(fm, "/Fat/s11_relimg.d64", "RELIMG", 683, e_image_d64); + dr->add_partition(56, "/Fat/s11_relimg.d64", "RELIMG"); + expect_command_status_prefix(testname, dr, "CP56\r", "02,PARTITION SELECTED"); + expect_rel_open(testname, dr, 2, "RECS", 4); + expect_rel_position_status(testname, dr, 2, 2, 1, "50,RECORD NOT PRESENT,00,00\r"); + expect_rel_position_status(testname, dr, 2, 1, 1, "00, OK,00,00\r"); + expect_rel_write(testname, dr, 2, (const uint8_t *)"AAAA", 4); + expect_rel_write(testname, dr, 2, (const uint8_t *)"BBBB", 4); + close_file(dr, 2); + + // Shorten the last data sector of the file by one byte. + open_buffer_channel(testname, dr, 3); + expect_command_ok(testname, dr, "U1:3,0,18,1\r"); + uint8_t dir[256]; + read_buffer_channel(testname, dr, 3, dir, sizeof(dir)); + int entry = -1; + for (int e = 0; e < 8; e++) { + if (((dir[2 + 32 * e] & 7) == 4) && !memcmp(dir + 5 + 32 * e, "RECS\xA0", 5)) { + entry = e; + } + } + REQUIRE(entry >= 0); + int track = dir[3 + 32 * entry], sector = dir[4 + 32 * entry]; + uint8_t block[256]; + char cmd[32]; + for (int hops = 0; hops < 100; hops++) { + snprintf(cmd, sizeof(cmd), "U1:3,0,%d,%d\r", track, sector); + expect_command_ok(testname, dr, cmd); + read_buffer_channel(testname, dr, 3, block, sizeof(block)); + if (!block[0]) { + break; + } + track = block[0]; + sector = block[1]; + } + printf("%s: the last data sector %d/%d ends at byte %d\n", testname, track, sector, block[1]); + REQUIRE(block[0] == 0); + block[1]--; + expect_command_ok(testname, dr, "B-P 3 0\r"); + send_channel_data(dr, 3, block, sizeof(block)); + snprintf(cmd, sizeof(cmd), "U2:3,0,%d,%d\r", track, sector); + expect_command_ok(testname, dr, cmd); + close_file(dr, 3); + + expect_rel_open(testname, dr, 2, "RECS", 0); + expect_rel_position_status(testname, dr, 2, 1, 1, "00, OK,00,00\r"); + expect_rel_read(testname, dr, 2, (const uint8_t *)"AAAA", 4); + close_file(dr, 2); +} + +// CR-4: a listing that is abandoned releases its directory when the channel closes, so +// the heap is back where it was once the channel is closed. A full listing first puts +// everything the file manager caches for the directory in place. +static size_t s11_heap_in_use(void) +{ + struct mallinfo2 m = mallinfo2(); + return m.uordblks; +} + +static void s11_cr4_abandoned_listing(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-CR4-AbandonedListing"; + s11_partition(fm, dr, "cr4"); + expect_iec_write_ok(testname, dr, 1, "ONE", "1"); + uint8_t listing[4096]; + read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + size_t before = s11_heap_in_use(); + for (int i = 0; i < 2; i++) { + uint8_t part[8]; + open_file(dr, 0, "$"); + get_status(dr); + expect_status_ok(testname, "$"); + REQUIRE(read_file_limited(dr, 0, part, sizeof(part)) == sizeof(part)); + close_file(dr, 0); + } + size_t after = s11_heap_in_use(); + printf("%s: %d bytes in use before, %d after the channel closed\n", testname, (int)before, (int)after); + REQUIRE(after <= before); +} + +// CR-5: a directory open that fails after an abandoned listing must not leave the channel +// pointing at the directory it freed, which the next open would free again. +static void s11_cr5_failed_directory_open(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-CR5-FailedDirectoryOpen"; + s11_partition(fm, dr, "cr5"); + expect_iec_write_ok(testname, dr, 1, "ONE", "1"); + for (int i = 0; i < 3; i++) { + uint8_t part[8]; + open_file(dr, 0, "$"); + get_status(dr); + expect_status_ok(testname, "$"); + REQUIRE(read_file_limited(dr, 0, part, sizeof(part)) == sizeof(part)); + open_file(dr, 0, "$/NOSUCHDIR/"); + get_status(dr); + printf("%s: $/NOSUCHDIR/ answered %s", testname, last_status); + REQUIRE(strncmp(last_status, "00,", 3) != 0); + close_file(dr, 0); + } + // The UCI target opens without closing first, so there the directory open itself must + // leave nothing dangling. + IecChannel *channel = dr->get_data_channel(0); + for (int i = 0; i < 3; i++) { + REQUIRE(channel->ext_open_file("$") == 1); + REQUIRE(channel->ext_open_file("$/NOSUCHDIR/") == 0); + } + REQUIRE(channel->ext_open_file("$") == 1); + channel->ext_close_file(); + expect_directory_contains(testname, dr, "$", "\"ONE\""); + expect_command_response(testname, dr, "XPWD\r", "40:/"); +} + +// CR-6: the IEC task and the GUI task reach the same channels and partitions, so the +// drive holds its lock whenever one of its entry points reaches storage. The FAT file +// counts the block accesses made while a watched drive is inside an entry point without +// its lock. +int s11_lock_watch_unlocked = 0; +int s11_lock_watch_locked = 0; +IecDrive *s11_lock_watch = NULL; +extern int iec_drive_lock_depth(IecDrive *drive) __attribute__((weak)); + +static void s11_cr6_lock(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-CR6-Lock"; + s11_partition(fm, dr, "cr6"); + if (!iec_drive_lock_depth) { + printf("%s: the drive has no lock\n", testname); + } + REQUIRE(iec_drive_lock_depth); + s11_lock_watch_unlocked = 0; + s11_lock_watch_locked = 0; + s11_lock_watch = dr; + expect_iec_write_ok(testname, dr, 1, "LOCKED", "some data"); + expect_iec_file(testname, dr, 0, "LOCKED", "some data"); + expect_directory_contains(testname, dr, "$", "\"LOCKED\""); + expect_command_ok(testname, dr, "MD:SUB\r"); + open_file(dr, 1, "PENDING"); + get_status(dr); + uint8_t block[600]; + memset(block, 'p', sizeof(block)); + send_channel_data(dr, 1, block, sizeof(block)); + dr->reset(); // the GUI's Reset closes the file + s11_lock_watch = NULL; + printf("%s: %d block accesses inside the lock, %d outside it\n", testname, + s11_lock_watch_locked, s11_lock_watch_unlocked); + REQUIRE((s11_lock_watch_unlocked == 0) && (s11_lock_watch_locked > 0)); + REQUIRE(iec_drive_lock_depth(dr) == 0); + expect_command_response(testname, dr, "CP40\r", "02,PARTITION SELECTED,40,00\r"); + expect_directory_contains(testname, dr, "$", "\"PENDING\""); +} + +// CR-8: a scratch by name is driven by the directory, so it removes every unlocked entry of +// that name and stops, and never deletes a locked one. +static void s11_cr8_scratch_scan(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-CR8-ScratchScan"; + const char *image = "/Fat/s11_cr8.d64"; + create_formatted_image(fm, image, "TWINS", 683, e_image_d64); + dr->add_partition(54, image, "TWINS"); + expect_command_status_prefix(testname, dr, "CP54\r", "02,PARTITION SELECTED"); + expect_iec_write_ok(testname, dr, 1, "TWIN", "prg"); + expect_iec_write_ok(testname, dr, 2, "TWIN,S,W", "seq"); + expect_iec_write_ok(testname, dr, 2, "OTHER,S,W", "other"); + expect_command_ok(testname, dr, "L:TWIN\r"); // the first entry, the PRG + char type[8]; + bool present; + s11_listing_type(dr, testname, "$", "TWIN", type, &present); + REQUIRE(present && !strcmp(type, "PRG<")); + const char *response = send_command(dr, "S:TWIN\r"); + printf("%s: S:TWIN answered %s", testname, response); + REQUIRE(strcmp(response, "01, FILES SCRATCHED,01,00\r") == 0); + uint8_t listing[4096]; + int got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + int twins = 0; + for (int offset = 32; offset + 32 <= got; offset += 32) { + twins += (memmem(listing + offset, 32, "\"TWIN\"", 6) != NULL); + } + s11_listing_type(dr, testname, "$", "TWIN", type, &present); + printf("%s: %d TWIN entries left, the first typed '%s'\n", testname, twins, type); + REQUIRE((twins == 1) && present && !strcmp(type, "PRG<")); + s11_listing_type(dr, testname, "$", "OTHER", type, &present); + REQUIRE(present); + expect_command_ok(testname, dr, "L:TWIN\r"); + expect_command_response(testname, dr, "S:TWIN\r", "01, FILES SCRATCHED,01,00\r"); + + // Two entries of one name and type, the first locked, as a damaged image can have + // them. A delete by name removes the first, so the unlocked second is not scratched + // either, and the locked one stays. + expect_iec_write_ok(testname, dr, 1, "PAIR", "first"); + expect_iec_write_ok(testname, dr, 2, "PAIR,S,W", "second"); + expect_command_ok(testname, dr, "L:PAIR\r"); + open_buffer_channel(testname, dr, 3); + expect_command_ok(testname, dr, "U1:3,0,18,1\r"); + uint8_t dir[256]; + read_buffer_channel(testname, dr, 3, dir, sizeof(dir)); + int seq = -1; + for (int e = 0; e < 8; e++) { + if (((dir[2 + 32 * e] & 7) == 1) && !memcmp(dir + 5 + 32 * e, "PAIR\xA0", 5)) { + seq = e; + } + } + REQUIRE(seq >= 0); + dir[2 + 32 * seq] = (dir[2 + 32 * seq] & ~7) | 2; // the SEQ entry becomes a second PRG + expect_command_ok(testname, dr, "B-P 3 0\r"); + send_channel_data(dr, 3, dir, sizeof(dir)); + expect_command_ok(testname, dr, "U2:3,0,18,1\r"); + close_file(dr, 3); + response = send_command(dr, "S:PAIR\r"); + printf("%s: with a locked PAIR first, S:PAIR answered %s", testname, response); + s11_listing_type(dr, testname, "$", "PAIR", type, &present); + printf("%s: the first PAIR is now typed '%s'\n", testname, type); + REQUIRE(present && !strcmp(type, "PRG<")); +} + +/* ============================================================================= + * Software IEC failure log. + * + * The drive writes one line, starting with "SoftIEC: ", for a command that leaves an + * error, an open that fails and the first failure of a channel, and nothing for an + * operation that succeeds. This suite captures what the drive writes while it runs + * operations of both kinds. + * ============================================================================= */ + +static char log_capture[256 * 1024]; + +static void log_capture_begin(int &saved_fd, FILE *&sink) +{ + const char *testname = "Suite11-FailureLog"; + fflush(stdout); + saved_fd = dup(fileno(stdout)); + sink = fopen("log_capture.txt", "w+"); + REQUIRE(saved_fd >= 0); + REQUIRE(sink != NULL); + dup2(fileno(sink), fileno(stdout)); +} + +static void log_capture_end(int saved_fd, FILE *sink) +{ + const char *testname = "Suite11-FailureLog"; + fflush(stdout); + dup2(saved_fd, fileno(stdout)); + close(saved_fd); + fseek(sink, 0, SEEK_SET); + size_t got = fread(log_capture, 1, sizeof(log_capture) - 1, sink); + log_capture[got] = 0; + fclose(sink); + remove("log_capture.txt"); +} + +static void expect_log_line(const char *testname, const char *what, const char *needle) +{ + if (strstr(log_capture, needle) == NULL) { + printf("%s: %s: no log line containing '%s' in:\n%s\n", testname, what, needle, log_capture); + } + REQUIRE(strstr(log_capture, needle) != NULL); +} + +// Lines of the failure log, and of the diagnostics that came before it. +static int count_log_lines(void) +{ + int n = 0; + for (const char *p = log_capture; (p = strstr(p, "SoftIEC: ")) != NULL; p++) { + n++; + } + for (const char *p = log_capture; (p = strstr(p, "SOFTIEC-TRACE")) != NULL; p++) { + n++; + } + return n; +} + +static void s11_failure_log(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-FailureLog"; + + // A partition of its own, so the state the earlier suites left behind cannot + // change what this one sees. + save_fixture_file(fm, "/Temp", "LOGGED.seq", "LOG PAYLOAD"); + dr->add_partition(9, "/Temp", "LOGPART"); + expect_command_response(testname, dr, "CP9\r", "02,PARTITION SELECTED,09,00\r"); + + int saved_fd = -1; + FILE *sink = NULL; + + // Operations that succeed write nothing: a command with a reply, the binary Change + // Partition, UI, which answers 73, and an open, a read and a close. + log_capture_begin(saved_fd, sink); + send_command(dr, "G-P\r"); + static const uint8_t change_partition[] = { 'C', 0xD0, 0x09 }; + send_command_data(dr, change_partition, 3); + get_status(dr); + send_command(dr, "UI\r"); + uint8_t body[64]; + open_file(dr, 2, "9:LOGGED,S,R"); + get_status(dr); + int got = read_file(dr, 2, body, sizeof(body)); + close_file(dr, 2); + log_capture_end(saved_fd, sink); + REQUIRE(got == 11); + printf("%s: %d log lines for operations that succeeded\n", testname, count_log_lines()); + REQUIRE(count_log_lines() == 0); + + // A command that fails is logged with its bytes, the carriage return still told apart + // from a printable byte, and the answer. + log_capture_begin(saved_fd, sink); + send_command(dr, "ZZ\r"); + log_capture_end(saved_fd, sink); + expect_log_line(testname, "failed command", + "SoftIEC: command failed dev=11 chan=15 part=9 dir=\"/\" len=3 txt=\"ZZ\\r\" -> 31,SYNTAX ERROR,00,00"); + REQUIRE(count_log_lines() == 1); + + // An open that fails is logged with the name as the bus delivered it. + log_capture_begin(saved_fd, sink); + open_file(dr, 3, "9:NOSUCH,S,R"); + get_status(dr); + close_file(dr, 3); + log_capture_end(saved_fd, sink); + expect_log_line(testname, "failed open", + "SoftIEC: open failed dev=11 chan=3 part=9 dir=\"/\" len=12 txt=\"9:NOSUCH,S,R\" -> 62,FILE NOT FOUND,00,00"); + REQUIRE(count_log_lines() == 1); + + // SI-152: a command longer than the rendering reports its real length, and the + // rendering says where it was cut. + char long_cmd[201]; + memset(long_cmd, 0x01, 200); // four characters each in the rendering + memcpy(long_cmd, "ZZ", 2); + long_cmd[200] = 0; + log_capture_begin(saved_fd, sink); + send_command(dr, long_cmd); + log_capture_end(saved_fd, sink); + expect_log_line(testname, "long command length", "SoftIEC: command failed dev=11 chan=15 part=9 dir=\"/\" len=200 "); + expect_log_line(testname, "long command cut", "\\x01..\" -> 31"); + +} + +static ConfigStore *s11_softiec_settings(void) +{ + const char *testname = "Suite11"; + ConfigStore *cfg = ConfigManager::getConfigManager()->find_store((uint32_t)0x49454300); + REQUIRE(cfg); + return cfg; +} + +// With "Log Every Operation" on, every command, open and close writes a line with the +// current partition and directory, a command that answers with data adds its reply, an open +// adds the host file or the first bytes of a listing, and a listing logs its last line. +// With the setting off again, operations that succeed write nothing. +static void s11_operation_log(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-OperationLog"; + save_fixture_file(fm, "/Temp", "OPLOG.seq", "LOG PAYLOAD"); + dr->add_partition(9, "/Temp", "LOGPART"); + expect_command_response(testname, dr, "CP9\r", "02,PARTITION SELECTED,09,00\r"); + ConfigStore *cfg = s11_softiec_settings(); + cfg->set_value(0x55, 1); + REQUIRE(dr->log_every_operation()); + + int saved_fd = -1; + FILE *sink = NULL; + log_capture_begin(saved_fd, sink); + send_command(dr, "CD//\r"); + const uint8_t mr[6] = { 'M', '-', 'R', 0x00, 0x05, 0x02 }; + send_command_data(dr, mr, sizeof(mr)); + uint8_t reply[8]; + read_command_channel(dr, reply, sizeof(reply)); + uint8_t body[64]; + open_file(dr, 2, "9:OPLOG,S,R"); + get_status(dr); + read_file(dr, 2, body, sizeof(body)); + close_file(dr, 2); + uint8_t listing[4096]; + read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + log_capture_end(saved_fd, sink); + printf("%s: %d lines\n", testname, count_log_lines()); + expect_log_line(testname, "command", "SoftIEC: command dev=11 chan=15 part=9 dir=\"/\" len=5 txt=\"CD//\\r\" -> 00, OK,00,00"); + expect_log_line(testname, "reply", "txt=\"M-R\\0\\x05\\x02\" reply=\"\\0\\0\" -> 00, OK,00,00"); + expect_log_line(testname, "open", "SoftIEC: open dev=11 chan=2 part=9 dir=\"/\" len=11 txt=\"9:OPLOG,S,R\" host=\"/Temp/OPLOG.seq\""); + expect_log_line(testname, "close", "SoftIEC: close dev=11 chan=2 "); + expect_log_line(testname, "listing", "txt=\"$\" data=\"\\x01\\x04\\x01\\x01"); + expect_log_line(testname, "listing end", "SoftIEC: listing end dev=11 chan=0 part=9 dir=\"/\" len=32 txt=\""); + REQUIRE(count_log_lines() >= 7); + + // Every line ends in " #" and a sequence number one higher than the line before it, so + // a reader of the device log can tell a line lost or delivered twice from one the drive + // wrote twice. + int previous = -1; + int numbered = 0; + for (const char *p = log_capture; (p = strstr(p, "SoftIEC: ")) != NULL; p++) { + const char *end = strchr(p, '\n'); + const char *hash = NULL; + for (const char *q = p; q && *q && (!end || q < end); q++) { + if (*q == '#') { + hash = q; + } + } + REQUIRE(hash != NULL); + int sequence = atoi(hash + 1); + if (previous >= 0) { + REQUIRE(sequence == previous + 1); + } + previous = sequence; + numbered++; + } + printf("%s: %d lines numbered, the last %d\n", testname, numbered, previous); + REQUIRE(numbered == count_log_lines()); + + cfg->set_value(0x55, 0); + REQUIRE(!dr->log_every_operation()); + log_capture_begin(saved_fd, sink); + send_command(dr, "CD//\r"); + read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + log_capture_end(saved_fd, sink); + REQUIRE(count_log_lines() == 0); +} + +// Changing Log Every Operation must not reconfigure the IEC interface, which on the device +// holds the IEC processor in reset and so drops a transfer that is on the bus. A change of +// the device number or of the enable still does. +static void s11_operation_log_no_reconfigure(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-OperationLogNoReconfigure"; + ConfigStore *cfg = s11_softiec_settings(); + int configured = iec_interface_configure_calls; + cfg->set_value(0x55, 1); + dr->effectuate_settings(); + cfg->set_value(0x55, 0); + dr->effectuate_settings(); + printf("%s: interface configured %d times by two changes of the log setting\n", testname, + iec_interface_configure_calls - configured); + REQUIRE(iec_interface_configure_calls == configured); + + int bus_id = cfg->get_value(0x52); + cfg->set_value(0x52, bus_id + 1); + dr->effectuate_settings(); + REQUIRE(iec_interface_configure_calls == configured + 1); + REQUIRE(dr->get_address() == bus_id + 1); + cfg->set_value(0x52, bus_id); + dr->effectuate_settings(); + REQUIRE(iec_interface_configure_calls == configured + 2); + REQUIRE(dr->get_address() == bus_id); + expect_command_status_prefix(testname, dr, "UI\r", "73,"); +} + +// The operation log with the longest inputs it takes: a working directory near the length +// a command can name, a 253 byte command, names that fill the buffer, and replies of 256 +// bytes. Every line must stay within its buffers; the AddressSanitizer build of this suite +// fails on any byte written or read outside them. +static void s11_operation_log_bounds(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-OperationLogBounds"; + s11_partition(fm, dr, "logbounds"); + ConfigStore *cfg = s11_softiec_settings(); + cfg->set_value(0x55, 1); + // Directories of 40 characters, deeper than one rendering holds. + char name[48]; + char cmd[300]; + for (int depth = 0; depth < 7; depth++) { + memset(name, 'D' + depth, 40); + name[40] = 0; + snprintf(cmd, sizeof(cmd), "MD:%s\r", name); + send_command(dr, cmd); + snprintf(cmd, sizeof(cmd), "CD:%s\r", name); + send_command(dr, cmd); + } + open_file(dr, 2, "LONGFILE,S,W"); + get_status(dr); + send_channel_data(dr, 2, (const uint8_t *)"DATA", 4); + close_file(dr, 2); + int saved_fd = -1; + FILE *sink = NULL; + log_capture_begin(saved_fd, sink); + // The host path of this file is longer than one rendering holds. + open_file(dr, 2, "LONGFILE,S,R"); + get_status(dr); + close_file(dr, 2); + memset(cmd, 0xFF, 253); + cmd[0] = 'Z'; + cmd[253] = 0; + send_command(dr, cmd); + uint8_t mr[6] = { 'M', '-', 'R', 0x00, 0xFE, 0xFF }; + uint8_t reply[300]; + send_command_data(dr, mr, sizeof(mr)); + read_command_channel(dr, reply, sizeof(reply)); + mr[5] = 0x00; + send_command_data(dr, mr, sizeof(mr)); + read_command_channel(dr, reply, sizeof(reply)); + char open_name[300]; + memset(open_name, 0xA5, 253); + open_name[253] = 0; + open_file(dr, 2, open_name); + get_status(dr); + close_file(dr, 2); + open_name[260] = 0; + memset(open_name, 'N', 260); + open_file(dr, 3, open_name); + get_status(dr); + close_file(dr, 3); + uint8_t listing[4096]; + read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + log_capture_end(saved_fd, sink); + cfg->set_value(0x55, 0); + // No line is longer than the three renderings, the answer and the fixed text allow. + int longest = 0; + for (const char *p = log_capture; (p = strstr(p, "SoftIEC: ")) != NULL; p++) { + const char *end = strchr(p, '\n'); + int n = end ? (int)(end - p) : (int)strlen(p); + longest = (n > longest) ? n : longest; + } + printf("%s: %d lines, the longest %d characters\n", testname, count_log_lines(), longest); + REQUIRE(count_log_lines() >= 7); + REQUIRE(longest < 3 * SOFTIEC_LOG_TEXT_SIZE + 200); + expect_log_line(testname, "long directory cut", "DDDDDDDD/EEEE"); + expect_log_line(testname, "long host path cut", "host=\"/Fat/s11_logbounds/DDDD"); + expect_command_response(testname, dr, "UI\r", "73,U64HD ULTIMATE DOS V2.0,00,00\r"); +} + +// A file inside a disk image whose chain links to a track the disk does not have. Working +// out its size indexed the loop detection map with -1 (found by Suite11-Soak). The drive +// must answer, and in the AddressSanitizer build nothing may be written outside the map. +static void s11_crash_damaged_chain(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-Crash-DamagedChain"; + create_formatted_image(fm, "/Fat/s11_chain.d64", "CHAIN", 683, e_image_d64); + dr->add_partition(55, "/Fat/s11_chain.d64", "CHAIN"); + expect_command_status_prefix(testname, dr, "CP55\r", "02,PARTITION SELECTED"); + uint8_t data[600]; + memset(data, 'c', sizeof(data)); + open_file(dr, 2, "LINKED,S,W"); + get_status(dr); + send_channel_data(dr, 2, data, sizeof(data)); + close_file(dr, 2); + // The file's first sector is the first entry of the directory sector 18/1. + open_buffer_channel(testname, dr, 3); + expect_command_ok(testname, dr, "U1:3,0,18,1\r"); + uint8_t dir[256]; + read_buffer_channel(testname, dr, 3, dir, sizeof(dir)); + int track = dir[3], sector = dir[4]; + char cmd[32]; + snprintf(cmd, sizeof(cmd), "U1:3,0,%d,%d\r", track, sector); + expect_command_ok(testname, dr, cmd); + uint8_t block[256]; + read_buffer_channel(testname, dr, 3, block, sizeof(block)); + printf("%s: LINKED starts at %d/%d and links to %d/%d; now to 99/0\n", testname, track, sector, block[0], block[1]); + block[0] = 99; + block[1] = 0; + expect_command_ok(testname, dr, "B-P 3 0\r"); + send_channel_data(dr, 3, block, sizeof(block)); + snprintf(cmd, sizeof(cmd), "U2:3,0,%d,%d\r", track, sector); + expect_command_ok(testname, dr, cmd); + close_file(dr, 3); + // An append works out the size of the file first. + open_file(dr, 2, "LINKED,S,A"); + get_status(dr); + printf("%s: the append answered %s", testname, last_status); + close_file(dr, 2); + open_file(dr, 2, "LINKED,S,R"); + get_status(dr); + uint8_t back[1024]; + int got = read_file(dr, 2, back, sizeof(back)); + close_file(dr, 2); + printf("%s: reading the damaged file gave %d bytes\n", testname, got); + expect_command_response(testname, dr, "UI\r", "73,U64HD ULTIMATE DOS V2.0,00,00\r"); +} + +// A host file whose name is longer than the 40 bytes a listing keeps of it. The name was +// copied without a terminator, so every use of it read past the buffer (found by +// Suite11-Soak). +static void s11_crash_long_host_name(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-Crash-LongHostName"; + const char *path = s11_partition(fm, dr, "longname"); + uint32_t tr; + REQUIRE(fm->save_file(true, path, "A NAME THAT IS MUCH LONGER THAN FORTY BYTES ON THE HOST.prg", + (const uint8_t *)"x", 1, &tr) == FR_OK); + uint8_t listing[4096]; + int got = read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + printf("%s: the listing is %d bytes\n", testname, got); + REQUIRE(got > 64); + // The opens and commands that find the file by its CBM name and then work out its + // type copied the name into 48 bytes without a terminator. + open_file(dr, 2, "A NAME THAT*"); + get_status(dr); + printf("%s: a typeless open answered %s", testname, last_status); + close_file(dr, 2); + expect_command_ok(testname, dr, "C:COPY=A NAME THAT*\r"); + expect_iec_write_ok(testname, dr, 1, "@:A NAME THAT*", "y"); + expect_command_ok(testname, dr, "R:SHORT=A NAME THAT*\r"); + expect_iec_file(testname, dr, 0, "SHORT", "y"); + expect_command_response(testname, dr, "UI\r", "73,U64HD ULTIMATE DOS V2.0,00,00\r"); +} + +// P on a file inside a disk image to a position past its end. The last sector's count of +// bytes left went negative and was copied as a length (found by the crash review). +static void s11_crash_seek_past_end_image(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-Crash-SeekPastEndImage"; + create_formatted_image(fm, "/Fat/s11_seek.d64", "SEEK", 683, e_image_d64); + dr->add_partition(57, "/Fat/s11_seek.d64", "SEEK"); + expect_command_status_prefix(testname, dr, "CP57\r", "02,PARTITION SELECTED"); + char payload[101]; + memset(payload, 'A', 100); + payload[100] = 0; + expect_iec_write_ok(testname, dr, 2, "SMALL,S,W", payload); + open_file(dr, 2, "SMALL,S,R"); + get_status(dr); + const uint8_t p200[6] = { 'P', 2, 200, 0, 0, 0 }; + send_command_data(dr, p200, sizeof(p200)); + get_status(dr); + printf("%s: P to byte 200 of a 100 byte file answered %s", testname, last_status); + uint8_t back[512]; + int got = read_file(dr, 2, back, sizeof(back)); + printf("%s: reading on gave %d bytes\n", testname, got); + REQUIRE(got <= 1); + close_file(dr, 2); + expect_command_response(testname, dr, "UI\r", "73,U64HD ULTIMATE DOS V2.0,00,00\r"); +} + +// A listing of a disk image partition, part read, while other channels list more images +// than the file manager keeps mounted. The first image was released under its open +// directory (found by the crash review). +static void s11_crash_evict_open_listing(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-Crash-EvictOpenListing"; + char path[64], name[16], cmd[24]; + for (int i = 0; i < 10; i++) { + snprintf(path, sizeof(path), "/Fat/s11_evict%d.d64", i); + snprintf(name, sizeof(name), "EV%d", i); + create_formatted_image(fm, path, name, 683, e_image_d64); + dr->add_partition(70 + i, path, name); + snprintf(cmd, sizeof(cmd), "%d:FILE%d,S,W", 70 + i, i); + expect_iec_write_ok(testname, dr, 2, cmd, "X"); + } + open_file(dr, 0, "$70"); + get_status(dr); + uint8_t part[40]; + REQUIRE(read_file_limited(dr, 0, part, sizeof(part)) == sizeof(part)); + uint8_t listing[4096]; + for (int i = 1; i < 10; i++) { + snprintf(cmd, sizeof(cmd), "$%d", 70 + i); + open_file(dr, 2, cmd); + get_status(dr); + read_file(dr, 2, listing, sizeof(listing)); + close_file(dr, 2); + } + memset(listing, 0, sizeof(listing)); + int got = read_file(dr, 0, listing, sizeof(listing)); + printf("%s: the first listing went on for %d more bytes\n", testname, got); + close_file(dr, 0); + REQUIRE(memmem(listing, got, "BLOCKS FREE.", 12) != NULL); +} + +// A copy that names a source in a partition that does not exist left the target open and +// its 32 KB copy buffer allocated, every time. +static void s11_crash_copy_missing_partition(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-Crash-CopyMissingPartition"; + s11_partition(fm, dr, "copyleak"); + expect_iec_write_ok(testname, dr, 2, "SRC,S,W", "source"); + expect_command_status_prefix(testname, dr, "C:WARM=SRC,200:X\r", "77,"); + size_t before = s11_heap_in_use(); + char cmd[32]; + for (int i = 0; i < 20; i++) { + snprintf(cmd, sizeof(cmd), "C:N%d=SRC,200:X\r", i); + expect_command_status_prefix(testname, dr, cmd, "77,"); + } + size_t after = s11_heap_in_use(); + printf("%s: %d bytes in use before 20 copies, %d after\n", testname, (int)before, (int)after); + REQUIRE(after < before + 32768); +} + +// An open through the UCI target on a channel that is already open, without a close in +// between, as a client that sends LOAD_SU twice does. The first file stayed open. +static void s11_crash_uci_reopen(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-Crash-UciReopen"; + s11_partition(fm, dr, "ucireopen"); + expect_iec_write_ok(testname, dr, 1, "PROG", "program"); + IecChannel *channel = dr->get_data_channel(0); + channel->ext_open_file("PROG"); // one file open, as there is after every open + size_t before = s11_heap_in_use(); + for (int i = 0; i < 20; i++) { + channel->ext_open_file("PROG"); + } + size_t after = s11_heap_in_use(); + channel->ext_close_file(); + printf("%s: %d bytes in use with one open, %d after 20 more\n", testname, (int)before, (int)after); + REQUIRE(after < before + 1024); +} + +// A record positioned past its last byte: the channel offered a negative number of +// bytes, which the UCI target passes on as a length to copy (found by Suite11-Soak). +static void s11_crash_record_past_end(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-Crash-RecordPastEnd"; + s11_partition(fm, dr, "recordend"); + expect_rel_open(testname, dr, 2, "RECORDS", 50); + expect_rel_position_status(testname, dr, 2, 1, 1, "50,RECORD NOT PRESENT,00,00\r"); + expect_rel_write(testname, dr, 2, (const uint8_t *)"AB", 2); + expect_rel_position_status(testname, dr, 2, 1, 40, "00, OK,00,00\r"); + negative_fetches = 0; + uint8_t out[64]; + int got = read_file_limited(dr, 2, out, sizeof(out)); + printf("%s: reading from byte 40 of a record that ends at byte 2 gave %d bytes, %d negative offers\n", + testname, got, negative_fetches); + REQUIRE(negative_fetches == 0); + close_file(dr, 2); +} + +// Every command of one and two bytes, and of each letter followed by the terminator, +// answers something: a parser that takes a substring past the end of a short command +// writes outside the heap (found by Suite11-Soak with "E"). +static void s11_short_commands(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-ShortCommands"; + s11_partition(fm, dr, "short"); + for (int a = 0; a < 256; a++) { + const uint8_t one[1] = { (uint8_t)a }; + send_command_data(dr, one, 1); + get_status(dr); + REQUIRE(isdigit((uint8_t)last_status[0]) && isdigit((uint8_t)last_status[1])); + const uint8_t with_cr[2] = { (uint8_t)a, 0x0D }; + send_command_data(dr, with_cr, 2); + get_status(dr); + REQUIRE(isdigit((uint8_t)last_status[0]) && isdigit((uint8_t)last_status[1])); + for (int b = 0; b < 256; b += (a >= 'A' && a <= 'Z') ? 1 : 51) { + const uint8_t two[2] = { (uint8_t)a, (uint8_t)b }; + send_command_data(dr, two, 2); + get_status(dr); + REQUIRE(isdigit((uint8_t)last_status[0]) && isdigit((uint8_t)last_status[1])); + } + } + expect_command_response(testname, dr, "E\r", "30,SYNTAX ERROR,00,00\r"); +} + +// --------------------------------------------------------------------------- +// Suite11-Soak: randomised use of the drive. Every iteration either follows the +// pattern C64 OS follows at boot (binary Change Partition, CD to absolute paths, M-R +// probes, UI, a scratch with a path, a listing abandoned after five bytes, several +// channels open at once, a file header read and then the whole file again), or runs +// one of the other command families, or sends hostile input: random command bytes, +// random names, channels abandoned half way, the menu's Reset and partition changes +// in between. Individual answers are not checked, only that there is one. What is +// checked is that the drive survives (run it in the AddressSanitizer build), that it +// still answers UI with 73 at the end, and that it gives back the memory it took. +// IECSOAK_ITERATIONS sets the length (default 400), IECSOAK_SEED the sequence, and +// IECSOAK_VERBOSE=1 prints each step so a failing seed can be followed. +// --------------------------------------------------------------------------- +static uint32_t soak_state = 1; +static bool soak_verbose = false; + +static uint32_t soak_rand(void) +{ + soak_state ^= soak_state << 13; + soak_state ^= soak_state >> 17; + soak_state ^= soak_state << 5; + return soak_state; +} + +static int soak_pick(int n) +{ + return (int)(soak_rand() % (uint32_t)n); +} + +static void soak_step(int iteration, const char *what, const char *detail) +{ + if (soak_verbose) { + fprintf(stderr, "soak %d: %s %s\n", iteration, what, detail ? detail : ""); + } +} + +static const char *soak_names[] = { + "ONE", "TWO", "GAME", "CONFIG.T", "LIB.O", "A\xA0" "B", "_", "..", "X*", "Y?", + "SIXTEENCHARSNAME", "SEVENTEENCHARNAME", "REL", "MY GAME", "IMG.D64", "", +}; +#define SOAK_NAMES (int)(sizeof(soak_names) / sizeof(soak_names[0])) + +static void soak_send_bytes(IecDrive *dr, uint8_t chan_cmd, const uint8_t *data, int len) +{ + dr->push_ctrl(SLAVE_CMD_ATN); + dr->push_ctrl(chan_cmd); + for (int i = 0; i < len; i++) { + dr->push_data(data[i]); + } + dr->push_ctrl(SLAVE_CMD_EOI); +} + +static void soak_command(IecDrive *dr, const char *cmd) +{ + send_command(dr, cmd); +} + +static void soak_read(IecDrive *dr, uint8_t chan, int len) +{ + static uint8_t sink[4096]; + if (len > (int)sizeof(sink)) { + len = sizeof(sink); + } + read_file_limited(dr, chan, sink, len); +} + +static void soak_fixture(FileManager *fm) +{ + const char *testname = "Suite11-Soak"; + static const char *dirs[] = { "/Fat/soak", "/Fat/soak/OS", "/Fat/soak/OS/SETTINGS", "/Fat/soak/OS/LIBRARY", + "/Fat/soak/OS/TEMPORARY", "/Fat/soak/OS/DRIVERS", "/Fat/soak/WORK" }; + for (int i = 0; i < 7; i++) { + FRESULT fres = fm->create_dir(dirs[i]); + REQUIRE((fres == FR_OK) || (fres == FR_EXIST)); + } + uint8_t data[3000]; + for (int i = 0; i < (int)sizeof(data); i++) { + data[i] = (uint8_t)(i * 13 + 7); + } + uint32_t tr; + REQUIRE(fm->save_file(true, "/Fat/soak/OS/SETTINGS", "CONFIG.T.seq", data, 13, &tr) == FR_OK); + REQUIRE(fm->save_file(true, "/Fat/soak/OS/SETTINGS", "SYSTEM.T.seq", data, 400, &tr) == FR_OK); + REQUIRE(fm->save_file(true, "/Fat/soak/OS/LIBRARY", "LIB.O.prg", data, 2957, &tr) == FR_OK); + REQUIRE(fm->save_file(true, "/Fat/soak/OS/LIBRARY", "SMALL.O.prg", data, 2, &tr) == FR_OK); + REQUIRE(fm->save_file(true, "/Fat/soak/OS/DRIVERS", "KBD.C64.prg", data, 567, &tr) == FR_OK); + s11_host_file(fm, "/Fat/soak/OS/LIBRARY", "GAME.P00", "MY GAME", 0, data, 300); + create_formatted_image(fm, "/Fat/soak/OS/IMG.D64", "SOAK", 683, e_image_d64); +} + +static void soak_partitions(FileManager *fm, IecDrive *dr) +{ + dr->add_partition(60, "/Fat/soak", "SOAK"); + create_formatted_image(fm, "/Fat/soak_61.d64", "SOAK41", 683, e_image_d64); + create_formatted_image(fm, "/Fat/soak_62.d81", "SOAK81", 3200, e_image_d81); + create_formatted_image(fm, "/Fat/soak_63.dnp", "SOAKNAT", 4 * 256, e_image_dnp); + dr->add_partition(61, "/Fat/soak_61.d64", "SOAK41"); + dr->add_partition(62, "/Fat/soak_62.d81", "SOAK81"); + dr->add_partition(63, "/Fat/soak_63.dnp", "SOAKNAT"); +} + +// What C64 OS does at boot, from the trace attached to #877. +static void soak_boot(IecDrive *dr, int iteration) +{ + soak_step(iteration, "boot", NULL); + const uint8_t cp[3] = { 'C', 0xD0, 60 }; + soak_send_bytes(dr, 0x6F, cp, 3); + get_status(dr); + soak_command(dr, "CD//OS\r"); + static const uint8_t probes[4][2] = { { 0xA4, 0xFE }, { 0xC5, 0xE5 }, { 0xE8, 0xA6 }, { 0x02, 0x00 } }; + for (int i = 0; i < 4; i++) { + const uint8_t mr[6] = { 'M', '-', 'R', probes[i][0], probes[i][1], 2 }; + soak_send_bytes(dr, 0xFF, mr, 6); + get_status(dr); + close_file(dr, 15); + } + soak_command(dr, "UI"); + soak_command(dr, "S/TEMPORARY/:*"); + open_file(dr, 0, "$"); + get_status(dr); + soak_read(dr, 0, 5); + close_file(dr, 0); + open_file(dr, 2, "/SETTINGS/:SYSTEM.T"); + get_status(dr); + soak_read(dr, 2, 1 + soak_pick(40)); + open_file(dr, 3, "/LIBRARY/:LIB.O"); + get_status(dr); + soak_read(dr, 3, 2); + close_file(dr, 3); + open_file(dr, 0, "/LIBRARY/:LIB.O"); + get_status(dr); + soak_read(dr, 0, 4096); + close_file(dr, 0); + open_file(dr, 3, "/TEMPORARY/:UPDATER"); + get_status(dr); + soak_read(dr, 3, 10); + close_file(dr, 3); + open_file(dr, 14, "/SETTINGS/:CONFIG.T"); + get_status(dr); + soak_read(dr, 14, 16); + close_file(dr, 14); + soak_command(dr, "CD//OS/DRIVERS/"); + open_file(dr, 0, "KBD.C64"); + get_status(dr); + soak_read(dr, 0, 4096); + close_file(dr, 0); + soak_command(dr, "CD//OS"); + open_file(dr, 0, "$:SYS*"); + get_status(dr); + soak_read(dr, 0, 4096); + close_file(dr, 0); + soak_read(dr, 2, 4096); + close_file(dr, 2); +} + +static void soak_listing(IecDrive *dr, int iteration) +{ + static const char *names[] = { "$", "$:*", "$=P", "$=T:*=L", "$//OS/", "$0", "$/NOSUCH/", "$61", "$62:*=S", + "$63", "$=P:*=N", "$//OS/IMG.D64/", "$:*=H" }; + const char *name = names[soak_pick(13)]; + uint8_t chan = (uint8_t)soak_pick(15); + soak_step(iteration, "listing", name); + open_file(dr, chan, name); + get_status(dr); + soak_read(dr, chan, soak_pick(2) ? 4096 : soak_pick(200)); + if (soak_pick(4)) { + close_file(dr, chan); + } +} + +static void soak_work_dir(IecDrive *dr) +{ + const uint8_t cp[3] = { 'C', 0xD0, (uint8_t)(60 + soak_pick(4)) }; + soak_send_bytes(dr, 0x6F, cp, 3); + get_status(dr); + if (cp[2] == 60) { + soak_command(dr, "CD//WORK/"); + } else { + soak_command(dr, "CD//"); + } +} + +static void soak_write(IecDrive *dr, int iteration) +{ + char name[48]; + static const char *modes[] = { ",S,W", ",P,W", ",U,W", ",S,A", "" }; + const char *base = soak_names[soak_pick(SOAK_NAMES)]; + snprintf(name, sizeof(name), "%s%s%s", soak_pick(3) ? "" : "@:", base, modes[soak_pick(5)]); + uint8_t chan = (uint8_t)(1 + soak_pick(14)); + soak_step(iteration, "write", name); + soak_work_dir(dr); + open_file(dr, chan, name); + get_status(dr); + uint8_t data[1600]; + int len = soak_pick(sizeof(data)); + for (int i = 0; i < len; i++) { + data[i] = (uint8_t)soak_rand(); + } + soak_send_bytes(dr, 0x60 | chan, data, len); + if (soak_pick(6)) { + close_file(dr, chan); + } + open_file(dr, chan, base); + get_status(dr); + soak_read(dr, chan, 4096); + close_file(dr, chan); +} + +static void soak_files(IecDrive *dr, int iteration) +{ + char cmd[80]; + const char *a = soak_names[soak_pick(SOAK_NAMES)]; + const char *b = soak_names[soak_pick(SOAK_NAMES)]; + switch (soak_pick(9)) { + case 0: snprintf(cmd, sizeof(cmd), "S:%s", a); break; + case 1: snprintf(cmd, sizeof(cmd), "R:%s=%s", a, b); break; + case 2: snprintf(cmd, sizeof(cmd), "C:%s=%s", a, b); break; + case 3: snprintf(cmd, sizeof(cmd), "MD:%s", a); break; + case 4: snprintf(cmd, sizeof(cmd), "CD:%s", a); break; + case 5: snprintf(cmd, sizeof(cmd), "RD:%s", a); break; + case 6: snprintf(cmd, sizeof(cmd), "L:%s", a); break; + case 7: snprintf(cmd, sizeof(cmd), "S:*"); break; + default: snprintf(cmd, sizeof(cmd), "CD_"); break; + } + soak_step(iteration, "files", cmd); + soak_work_dir(dr); + soak_command(dr, cmd); +} + +static void soak_relative(IecDrive *dr, int iteration) +{ + soak_step(iteration, "relative", NULL); + soak_work_dir(dr); + char name[16]; + int n = snprintf(name, sizeof(name), "REL,L,"); + name[n++] = (char)(1 + soak_pick(254)); + name[n] = 0; + uint8_t chan = (uint8_t)(2 + soak_pick(12)); + open_file(dr, chan, soak_pick(3) ? name : "REL,L"); + get_status(dr); + for (int i = soak_pick(5); i >= 0; i--) { + int record = 1 + soak_pick(soak_pick(4) ? 20 : 2000); + const uint8_t p[5] = { 'P', (uint8_t)(0x60 | chan), (uint8_t)record, (uint8_t)(record >> 8), (uint8_t)soak_pick(256) }; + soak_send_bytes(dr, 0x6F, p, 5); + get_status(dr); + if (soak_pick(2)) { + uint8_t data[300]; + int len = soak_pick(sizeof(data)); + for (int k = 0; k < len; k++) { + data[k] = (uint8_t)soak_rand(); + } + soak_send_bytes(dr, 0x60 | chan, data, len); + } else { + soak_read(dr, chan, soak_pick(300)); + } + } + close_file(dr, chan); +} + +static void soak_direct(IecDrive *dr, int iteration) +{ + soak_step(iteration, "direct", NULL); + soak_work_dir(dr); + uint8_t chan = (uint8_t)(2 + soak_pick(12)); + char name[4] = { '#', '#', (char)('0' + soak_pick(11)), 0 }; + open_file(dr, chan, soak_pick(2) ? "#" : name); + get_status(dr); + static const char *forms[] = { "U1:%d,0,%d,%d", "U2:%d,0,%d,%d", "B-R:%d,0,%d,%d", "B-W:%d,0,%d,%d", + "B-P:%d,%d,%d", "B-A:0,%d,%d%.0d", "B-F:0,%d,%d%.0d" }; + for (int i = soak_pick(6); i >= 0; i--) { + char cmd[48]; + int f = soak_pick(7); + if (f >= 5) { + snprintf(cmd, sizeof(cmd), forms[f], soak_pick(90), soak_pick(260), 0); + } else { + snprintf(cmd, sizeof(cmd), forms[f], soak_pick(3) ? chan : soak_pick(16), soak_pick(90), soak_pick(260)); + } + soak_command(dr, cmd); + if (soak_pick(2)) { + uint8_t data[600]; + int len = soak_pick(sizeof(data)); + for (int k = 0; k < len; k++) { + data[k] = (uint8_t)soak_rand(); + } + soak_send_bytes(dr, 0x60 | chan, data, len); + } else { + soak_read(dr, chan, soak_pick(2400)); + } + } + close_file(dr, chan); +} + +static void soak_hostile(IecDrive *dr, int iteration) +{ + uint8_t data[300]; + int len = soak_pick(sizeof(data)); + for (int i = 0; i < len; i++) { + data[i] = soak_pick(3) ? (uint8_t)(' ' + soak_pick(64)) : (uint8_t)soak_rand(); + } + if (soak_pick(2)) { + soak_step(iteration, "hostile command", NULL); + soak_send_bytes(dr, 0x6F, data, len); + get_status(dr); + } else { + uint8_t chan = (uint8_t)soak_pick(16); + soak_step(iteration, "hostile open", NULL); + soak_send_bytes(dr, 0xF0 | chan, data, len); + get_status(dr); + soak_read(dr, chan, soak_pick(600)); + if (soak_pick(2)) { + soak_send_bytes(dr, 0x60 | chan, data, soak_pick(len + 1)); + } + if (soak_pick(3)) { + close_file(dr, chan); + } + } +} + +static void soak_misc(IecDrive *dr, int iteration) +{ + static const char *cmds[] = { "G-P", "G-P\x01", "T-RI", "T-RA", "T-WI2026-09-13T01:02:03", "I", "UJ", + "U\xCA", "L:ONE", "XPWD", "M-R\x00\x05\xFF", "M-W\x00\x05\x01\x01", "N:TMP.D64,AB", + "S:TMP.D64", "CP61", "CP99", "CD//OS/IMG.D64", "CD_", "U0>\x0B" }; + const char *cmd = cmds[soak_pick(sizeof(cmds) / sizeof(cmds[0]))]; + soak_step(iteration, "misc", cmd); + if (strncmp(cmd, "N:", 2) == 0) { + soak_work_dir(dr); + } + if (strncmp(cmd, "M-", 2) == 0) { + soak_send_bytes(dr, 0x6F, (const uint8_t *)cmd, (cmd[2] == 'R') ? 6 : 8); + get_status(dr); + } else { + soak_command(dr, cmd); + } +} + +static void soak_gui(FileManager *fm, IecDrive *dr, int iteration) +{ + switch (soak_pick(4)) { + case 0: + soak_step(iteration, "gui", "reset"); + dr->reset(); + break; + case 1: { + soak_step(iteration, "gui", "partition moves"); + dr->add_partition(60, soak_pick(2) ? "/Fat/soak" : "/Fat/soak/OS", "SOAK"); + break; + } + case 2: { + soak_step(iteration, "gui", "info"); + static char text[4096]; + StreamTextLog log(sizeof(text), text); + dr->info(log); + break; + } + default: + soak_step(iteration, "gui", "close channels"); + for (int c = 0; c < 16; c++) { + close_file(dr, (uint8_t)c); + } + break; + } +} + +static void s11_soak(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-Soak"; + const char *env = getenv("IECSOAK_ITERATIONS"); + int iterations = env ? atoi(env) : 400; + env = getenv("IECSOAK_SEED"); + soak_state = env ? (uint32_t)strtoul(env, NULL, 0) : 0x1541; + if (!soak_state) { + soak_state = 1; + } + soak_verbose = getenv("IECSOAK_VERBOSE") != NULL; + // With IECSOAK_LOG set, the drive also writes its "Log Every Operation" lines. + s11_softiec_settings()->set_value(0x55, getenv("IECSOAK_LOG") ? 1 : 0); + printf("%s: %d iterations, seed 0x%x\n", testname, iterations, soak_state); + soak_fixture(fm); + soak_partitions(fm, dr); + + size_t heap_after_warmup = 0; + int warmup = iterations / 5; + for (int i = 0; i < iterations; i++) { + switch (soak_pick(16)) { + case 0: case 1: case 2: case 3: soak_boot(dr, i); break; + case 4: case 5: soak_listing(dr, i); break; + case 6: case 7: soak_write(dr, i); break; + case 8: soak_files(dr, i); break; + case 9: soak_relative(dr, i); break; + case 10: soak_direct(dr, i); break; + case 11: case 12: soak_hostile(dr, i); break; + case 13: soak_misc(dr, i); break; + default: soak_gui(fm, dr, i); break; + } + if (i == warmup) { + for (int c = 0; c < 16; c++) { + close_file(dr, (uint8_t)c); + } + heap_after_warmup = s11_heap_in_use(); + } + } + for (int c = 0; c < 16; c++) { + close_file(dr, (uint8_t)c); + } + size_t heap_at_end = s11_heap_in_use(); + const char *ui = send_command(dr, "UI"); + printf("%s: after %d iterations UI answered %s", testname, iterations, ui); + printf("%s: heap in use %d bytes after warmup, %d at the end\n", testname, + (int)heap_after_warmup, (int)heap_at_end); + printf("%s: %d reads were offered a negative number of bytes\n", testname, negative_fetches); + REQUIRE(strncmp(ui, "73,", 3) == 0); + REQUIRE(negative_fetches == 0); + REQUIRE(heap_at_end <= heap_after_warmup + 64 * 1024); +} + + +struct Suite11Case { + const char *name; + void (*run)(FileManager *fm, IecDrive *dr); +}; + +static const Suite11Case suite11_cases[] = { + { "Suite11-SI031-Unrecognised", s11_si031_unrecognised }, + { "Suite11-SI030-UnknownSubcommand", s11_si030_unknown_subcommand }, + { "Suite11-SI030-MissingName", s11_si030_missing_name }, + { "Suite11-SI030-WildcardTarget", s11_si030_wildcard_target }, + { "Suite11-SI036-BlockRange", s11_si036_block_range }, + { "Suite11-SI033-ScratchNothing", s11_si033_scratch_nothing }, + { "Suite11-SI053-Initialize", s11_si053_initialize }, + { "Suite11-SI045-PartitionDirectory", s11_si045_partition_directory }, + { "Suite11-SI046-PartitionCount", s11_si046_partition_count }, + { "Suite11-SI100-DeviceNumber", s11_si100_device_number }, + { "Suite11-SI105-MemoryCommands", s11_si105_memory_commands }, + { "Suite11-SI021-LongNames", s11_si021_long_names }, + { "Suite11-SI022-TooLong", s11_si022_too_long }, + { "Suite11-SI016-SecondTerminator", s11_si016_second_terminator }, + { "Suite11-SI018-PositionExempt", s11_si018_position_exempt }, + { "Suite11-SI014-LeftArrow", s11_si014_left_arrow }, + { "Suite11-SI012-WildcardPath", s11_si012_wildcard_path }, + { "Suite11-SI060-MdColon", s11_si060_md_colon }, + { "Suite11-SI063-RdNoPath", s11_si063_rd_no_path }, + { "Suite11-SI150-DeepPath", s11_si150_deep_path }, + { "Suite11-SI130-ListingHeader", s11_si130_listing_header }, + { "Suite11-SI133-SizeRemainder", s11_si133_size_remainder }, + { "Suite11-SI138-ListingEof", s11_si138_listing_eof }, + { "Suite11-SI139-StampedEntries", s11_si139_stamped_entries }, + { "Suite11-SI149-GeosEntries", s11_si149_geos_entries }, + { "Suite11-SI134-HiddenFlag", s11_si134_hidden_flag }, + { "Suite11-SI065-HeaderName", s11_si065_header_name }, + { "Suite11-SI032-WildcardWrite", s11_si032_wildcard_write }, + { "Suite11-SI041-PartitionSize", s11_si041_partition_size }, + { "Suite11-SI072-RawNames", s11_si072_raw_names }, + { "Suite11-SI074-RenameChecks", s11_si074_rename_checks }, + { "Suite11-SI083-SeekWrite", s11_si083_seek_write }, + { "Suite11-SI083-SeekWriteImage", s11_si083_seek_write_image }, + { "Suite11-SI071-Format", s11_si071_format }, + { "Suite11-SI147-ShiftedSpace", s11_si147_shifted_space }, + { "Suite11-SI142-EscapedWildcards", s11_si142_escaped_wildcards }, + { "Suite11-SI076-Lock", s11_si076_lock }, + { "Suite11-SI090-BufferPointer", s11_si090_buffer_pointer }, + { "Suite11-SI093-BoundPartition", s11_si093_bound_partition }, + { "Suite11-SI094-BlockLength", s11_si094_block_length }, + { "Suite11-SI103-Resets", s11_si103_resets }, + { "Suite11-SI144-ReadX00", s11_si144_read_x00 }, + { "Suite11-SI084-RelLayouts", s11_si084_rel_layouts }, + { "Suite11-SI144-X00Paths", s11_x00_paths }, + { "Suite11-SI084-RelInImage", s11_rel_in_image }, + { "Suite11-CR4-AbandonedListing", s11_cr4_abandoned_listing }, + { "Suite11-CR5-FailedDirectoryOpen", s11_cr5_failed_directory_open }, + { "Suite11-CR6-Lock", s11_cr6_lock }, + { "Suite11-CR8-ScratchScan", s11_cr8_scratch_scan }, + { "Suite11-FailureLog", s11_failure_log }, + { "Suite11-OperationLog", s11_operation_log }, + { "Suite11-OperationLogBounds", s11_operation_log_bounds }, + { "Suite11-OperationLogNoReconfigure", s11_operation_log_no_reconfigure }, + { "Suite11-BlockAllocateAnswers", s11_block_allocate_answers }, + { "Suite11-Crash-DamagedChain", s11_crash_damaged_chain }, + { "Suite11-Crash-LongHostName", s11_crash_long_host_name }, + { "Suite11-Crash-RecordPastEnd", s11_crash_record_past_end }, + { "Suite11-Crash-SeekPastEndImage", s11_crash_seek_past_end_image }, + { "Suite11-Crash-EvictOpenListing", s11_crash_evict_open_listing }, + { "Suite11-Crash-CopyMissingPartition", s11_crash_copy_missing_partition }, + { "Suite11-Crash-UciReopen", s11_crash_uci_reopen }, + { "Suite11-ShortCommands", s11_short_commands }, + { "Suite11-Soak", s11_soak }, +}; + +// Runs every case, or only those whose name contains `only`. +void execute_suite11(FileManager *fm, IecDrive *dr, const char *only) +{ + const char *testname = "Suite11"; + int ran = 0; + print_scenario("Suite11", "Software IEC compatibility specification"); + for (size_t i = 0; i < sizeof(suite11_cases) / sizeof(suite11_cases[0]); i++) { + if (only && !strstr(suite11_cases[i].name, only)) { + continue; + } + printf(" %s\n", suite11_cases[i].name); + suite11_cases[i].run(fm, dr); + ran++; + } + if (only) { + printf("Suite11 ran %d case(s) matching '%s'\n", ran, only); + REQUIRE(ran > 0); + return; + } + printf("Suite11 completed successfully!\n"); +} + + +int main(int argc, const char **argv) +{ + UserInterface *ui = new UserInterface("Test Drive"); + + init_ram_disk(); + init_flash_disk(); + init_fat_file(); + + IecDrive *dr = new IecDrive(); + t_channel_retval ret; + uint32_t tr; + mstring status; + + File *f; + FileManager *fm = FileManager :: getFileManager(); + + // With an argument, only the Suite11 cases whose name contains it run. + const char *only = (argc > 1) ? argv[1] : NULL; + if (!only) { + execute_suite8(fm, dr); + run_suite9_block_matrix(fm, dr); + execute_suite3(fm, dr); + execute_suite4(fm, dr); + execute_suite5(fm, dr); + execute_suite6(fm, dr); + execute_suite7(fm, dr); + execute_suite10(fm, dr); + execute_suite12(fm); + } + execute_suite11(fm, dr, only); delete dr; delete ui; diff --git a/software/test/stubs/http_codes.h b/software/test/stubs/http_codes.h new file mode 100644 index 000000000..a8921d20e --- /dev/null +++ b/software/test/stubs/http_codes.h @@ -0,0 +1,18 @@ +#ifndef HTTP_CODES_H_ +#define HTTP_CODES_H_ + +#define HTTP_OK 200 +#define HTTP_BAD_REQUEST 400 +#define HTTP_FORBIDDEN 403 +#define HTTP_NOT_FOUND 404 +#define HTTP_METHOD_NOT_ALLOWED 405 +#define HTTP_PRECONDITION_FAILED 412 +#define HTTP_UNSUPPORTED_MEDIA_TYPE 415 +#define HTTP_LOCKED 423 +#define HTTP_FAILED_DEPENDENCY 424 +#define HTTP_INTERNAL_SERVER_ERROR 500 +#define HTTP_NOT_IMPLEMENTED 501 +#define HTTP_SERVICE_UNAVAILABLE 503 +#define HTTP_INSUFFICIENT_STORAGE 507 + +#endif diff --git a/software/test/stubs/iec_interface.cc b/software/test/stubs/iec_interface.cc index 8bca96773..0a04c1b3f 100644 --- a/software/test/stubs/iec_interface.cc +++ b/software/test/stubs/iec_interface.cc @@ -28,11 +28,18 @@ IecInterface :: ~IecInterface() { } +int iec_interface_configure_calls = 0; // lets a test show a command did not reconfigure + void IecInterface :: configure(void) { + iec_interface_configure_calls++; // printf("IEC Interface configure.\n"); } +void IecInterface :: readdress(int slot) +{ +} + int IecInterface :: register_slave(IecSlave *slave) { for(int i=0; i < available_slots; i++) { diff --git a/target/pc/linux/iecdrive_asan/Makefile b/target/pc/linux/iecdrive_asan/Makefile new file mode 100644 index 000000000..d15f948e9 --- /dev/null +++ b/target/pc/linux/iecdrive_asan/Makefile @@ -0,0 +1,7 @@ +# The drive suite of ../iecdrive under AddressSanitizer, which turns a use after free or a +# double free in the drive into an immediate report. Run it from this directory with +# ASAN_OPTIONS=detect_leaks=0, because the suite does not free what it set up at exit. +include ../iecdrive/Makefile + +OPTIONS := $(OPTIONS) -fsanitize=address -fno-omit-frame-pointer +LIBS := $(LIBS) -fsanitize=address diff --git a/target/pc/linux/iecdrive_unsigned/Makefile b/target/pc/linux/iecdrive_unsigned/Makefile new file mode 100644 index 000000000..c0dc5d6dc --- /dev/null +++ b/target/pc/linux/iecdrive_unsigned/Makefile @@ -0,0 +1,6 @@ +# The drive suite of ../iecdrive, built with -funsigned-char, as the RISC-V targets +# (Ultimate 64 II, Ultimate II+L) compile it; see ../parse_unsigned. Run it from this +# directory, because it creates its FAT image file in the working directory. +include ../iecdrive/Makefile + +OPTIONS := $(filter-out -fsigned-char,$(OPTIONS)) -funsigned-char diff --git a/target/pc/linux/parse_unsigned/Makefile b/target/pc/linux/parse_unsigned/Makefile new file mode 100644 index 000000000..6fae5bd63 --- /dev/null +++ b/target/pc/linux/parse_unsigned/Makefile @@ -0,0 +1,7 @@ +# The parser suite of ../parse, built with -funsigned-char, as the RISC-V targets +# (Ultimate 64 II, Ultimate II+L) compile it. The host and Nios II builds have a signed +# char, so a defect that depends on the signedness of char, like the shifted space rule +# of SI-147, can only fail here. +include ../parse/Makefile + +OPTIONS := $(filter-out -fsigned-char,$(OPTIONS)) -funsigned-char diff --git a/tests/e2e/io/command_interface/uci_targets_test.py b/tests/e2e/io/command_interface/uci_targets_test.py index 52f99c3e3..fa0485022 100755 --- a/tests/e2e/io/command_interface/uci_targets_test.py +++ b/tests/e2e/io/command_interface/uci_targets_test.py @@ -120,6 +120,7 @@ SOFTIEC_CMD_IDENTIFY = 0x01 SOFTIEC_CMD_LOAD_SU = 0x10 SOFTIEC_CMD_GET_FATNAME = 0x22 +SOFTIEC_CMD_GET_IECNAME = 0x23 # No target implements $7F, so it reaches the unknown-command path. CMD_UNIMPLEMENTED = 0x7F @@ -174,6 +175,17 @@ # secondary address, verify flag, load address and end address from bytes 2 to 7 # and starts the name at byte 8, so all six have to be present before the name. LOAD_SU_MISSING = bytes(6) + b"NOSUCHFILE" +# GET_IECNAME answers a type byte and the CBM name of a host file. An x00 file carries +# its CBM name in a 26 byte header that starts "C64File" and a zero (SI-144). Both files +# go to the RAM disk for the run: one with the header, and one named the same way +# without it. +X00_WRAPPED = "/Temp/UCIGAME.P00" +X00_PLAIN = "/Temp/UCIPLAIN.P00" +X00_CBM_NAME = b"MY GAME" +X00_HEADER = b"C64File\0" + X00_CBM_NAME.ljust(16, b"\0") + b"\0\0" +# The first reply byte is the drive's file type: 0 for a name without a CBM type, 1 PRG. +IEC_TYPE_ANY = 0 +IEC_TYPE_PRG = 1 BUSY_TIMEOUT_SECONDS = 15.0 BUSY_POLL_SECONDS = 0.05 @@ -196,6 +208,7 @@ "load-reu-disabled", "save-reu-disabled", "softiec-single-part-reply", + "softiec-x00-name", "interface-usable-after", ] @@ -858,6 +871,31 @@ def run_softiec_single_part_reply(uci: Uci) -> bool: return True +def run_softiec_x00_name(ftp: "FtpFixture", uci: Uci) -> bool: + """GET_IECNAME names an x00 file by the CBM name in its header (SI-144). + + Given a full path, the target reads the header of a file whose extension is P, S, U + or R and two digits, so a program that lists a directory through the target sees + the names the drive lists on the bus. Given a name without a directory there is no + file to read, and the answer comes from the host name. A file that has such an + extension but no signature is an ordinary file. + """ + scenario = "softiec-x00-name" + with check(f"{scenario}: put a P00 file, and a file named like one, on the RAM disk"): + ftp.upload(X00_WRAPPED, X00_HEADER + b"PAYLOAD") + ftp.upload(X00_PLAIN, b"not wrapped") + expect(uci, f"{scenario}: a full path to a P00 file answers the name in its header and PRG", + bytes([TARGET_SOFTIEC, SOFTIEC_CMD_GET_IECNAME]) + X00_WRAPPED.encode("ascii"), + SOFTIEC_OK, reply=bytes([IEC_TYPE_PRG]) + X00_CBM_NAME) + expect(uci, f"{scenario}: the same file without its directory answers the host name", + bytes([TARGET_SOFTIEC, SOFTIEC_CMD_GET_IECNAME]) + b"UCIGAME.P00", + SOFTIEC_OK, reply=bytes([IEC_TYPE_ANY]) + b"UCIGAME.P00") + expect(uci, f"{scenario}: a file without the signature answers its host name", + bytes([TARGET_SOFTIEC, SOFTIEC_CMD_GET_IECNAME]) + X00_PLAIN.encode("ascii"), + SOFTIEC_OK, reply=bytes([IEC_TYPE_ANY]) + b"UCIPLAIN.P00") + return True + + def run_interface_usable_after(uci: Uci) -> bool: expect(uci, "interface-usable-after: the control target still answers IDENTIFY", bytes([TARGET_CONTROL, CTRL_CMD_IDENTIFY]), STATUS_OK, reply_prefix=b"CONTROL TARGET") @@ -988,6 +1026,7 @@ def run(name: str, fn, *fn_args) -> None: run("load-reu-disabled", run_reu_disabled, session, uci, CTRL_CMD_LOAD_REU, "load-reu-disabled") run("save-reu-disabled", run_reu_disabled, session, uci, CTRL_CMD_SAVE_REU, "save-reu-disabled") run("softiec-single-part-reply", run_softiec_single_part_reply, uci) + run("softiec-x00-name", run_softiec_x00_name, ftp, uci) run("interface-usable-after", run_interface_usable_after, uci) except Failure as exc: diff --git a/tests/e2e/io/iec/README.md b/tests/e2e/io/iec/README.md index bfa68e24e..2f12394f9 100644 --- a/tests/e2e/io/iec/README.md +++ b/tests/e2e/io/iec/README.md @@ -24,7 +24,13 @@ catch them: it built its command strings by hand. colon, so the colon became the channel number and every value moved one place. The track number arrived as the partition number. * The partition directory showed the path a partition is rooted at instead of its - name, and typed every partition `DIR`. + name, and typed every partition `DIR`. `G-P`, which answers the same question to a + program rather than to a listing, had the same two defects and reported its type in + the reserved byte. +* A command whose last parameter is a byte can carry a 13, which is the terminator + byte. `C` followed by a shifted P selects a partition that way, so it keeps its + parameter; the commands whose last parameter is optional behave as CMD DOS + documents, which is that the terminator has to be sent as well. Two of its checks exist only here, because they cannot fail on a host build. The device uses the firmware's own `sscanf` in `software/system/small_printf.cc`, which diff --git a/tests/e2e/io/iec/dos_command_test.py b/tests/e2e/io/iec/dos_command_test.py index 9a3bb77a9..e7cd1b86d 100644 --- a/tests/e2e/io/iec/dos_command_test.py +++ b/tests/e2e/io/iec/dos_command_test.py @@ -17,6 +17,11 @@ its name, and typed every partition DIR instead of NAT or the drive model of the image at its root (#877). + * The partition commands that carry their number as a byte rather than as text + were reported against the first version of this fix. CMD DOS spells Change + Partition either "CPn" or "C" followed by a shifted P and the number, and that + number can be 13, which is the same byte PRINT# appends as a terminator. + Two more checks are here rather than on the host because they cannot fail there. The device uses the firmware's own sscanf, which has no %c and counts a conversion it did not make, while a host build links the C library's: a directory filtered by @@ -46,7 +51,7 @@ import ftp # noqa: E402 from api import UltimateApi # noqa: E402 from config_snapshot import Snapshot # noqa: E402 -from iec_agent import STATUS_BYTES, Agent # noqa: E402 +from iec_agent import CLOSE, MAILBOX_CAPACITY, OPEN, READ_COUNT, STATUS_BYTES, Agent # noqa: E402 from report import Failure, check, detail, section, suite_fail, suite_ok, teardown_step # noqa: E402 SUITE = "iec_dos_command_test" @@ -98,7 +103,8 @@ def check_command_channel(agent, api, password, folder, root): with check("CD into the created directory, back out, and remove it"): agent.command(f"CD//{here}/MADEDIR\r") agent.command("CD_\r") - agent.command(f"RD//{here}/:MADEDIR\r") + # RD takes no path; the working directory is the parent again after CD_. + agent.command("RD:MADEDIR\r") with ftp.session(api.host, password) as client: entries = ftp.names(client, f"{root.rstrip('/')}/{folder}") if "MADEDIR" in [name.upper() for name in entries]: @@ -154,7 +160,8 @@ def check_timestamp_filter(agent, api, password, folder, root): client.storbinary(f"STOR {root.rstrip('/')}/{folder}/stamped.prg", io.BytesIO(b"stamped")) listing = listing_of(agent, f"$//{here}:*=L") - stamped = re.search(rb'"STAMPED\s*"\s+PRG\s+(\d\d)/(\d\d)/(\d\d) (\d\d)\.(\d\d) ([AP])M', listing) + # The long format puts three spaces between the date and the time (SI-139). + stamped = re.search(rb'"STAMPED\s*"\s+PRG\s+(\d\d)/(\d\d)/(\d\d)\s+(\d\d)\.(\d\d) ([AP])M', listing) if not stamped: raise Failure(f"the long listing carries no stamp for the file just written: {listing!r}") month, day, year, hour12, minute, half = (f.decode() for f in stamped.groups()) @@ -184,6 +191,301 @@ def check_timestamp_filter(agent, api, password, folder, root): raise Failure(f"the file is reported newer than {date} {clock} PM") +def stamped_lines(listing, length, what): + """The entry lines of a time stamped listing, which all have the same length.""" + body = listing[LINE:len(listing) - LINE] + if not body or len(body) % length: + raise Failure(f"{what} has {len(listing)} bytes, which is not a header, " + f"a blocks free line and whole lines of {length} bytes") + return [body[i:i + length] for i in range(0, len(body), length)] + + +def check_stamped_line(line, what, type_name, gap, stamp_len): + """SI-139: where the stamp sits in a line, and the filler behind it.""" + digits = len(str(line[2] | (line[3] << 8))) + type_at = 27 - digits + stamp_at = type_at + len(type_name) + gap + if line[type_at:type_at + len(type_name)] != type_name: + raise Failure(f"{what}: the type is not {type_name!r} at offset {type_at}: {line!r}") + if line[type_at + len(type_name):stamp_at] != b" " * gap: + raise Failure(f"{what}: the {gap} characters between the type and the stamp are " + f"{line[type_at + len(type_name):stamp_at]!r}: {line!r}") + if not re.match(rb"\d\d/\d\d", line[stamp_at:stamp_at + 5]): + raise Failure(f"{what}: no stamp at offset {stamp_at}: {line!r}") + filler = line[stamp_at + stamp_len:len(line) - 1] + if filler != b"\x01" * len(filler) or line[-1] != 0: + raise Failure(f"{what}: the line ends {line[stamp_at + stamp_len:]!r}, expected " + f"{len(filler)} filler bytes of 01 and a zero: {line!r}") + + +def check_listing_layout(agent, folder): + """#917, SI-139: a time stamped line is a fixed 64 bytes, or 42 in the short format. + + The stamp starts four characters behind a three character type and two behind the + single letter of the short format, and CMD DOS fills what is left of the line with + 0x01. This drive wrote the long stamp two columns early and ended every line where + its contents happened to end. + """ + here = folder.upper() + for name, length, type_name, gap, stamp_len in ( + (f"$//{here}:*=P,L", 64, b"PRG", 3, 19), + (f"$=T//{here}:*=P", 42, b"P", 1, 13)): + with check(f"SI-139: {name} lines are {length} bytes with 0x01 filler"): + listing = listing_of(agent, name) + lines = stamped_lines(listing, length, name) + detail(f"{name}: {len(lines)} lines of {length} bytes, first {lines[0]!r}") + for line in lines: + check_stamped_line(line, name, type_name, gap, stamp_len) + + +def check_listing_eof(agent, folder): + """#917, SI-138: the last byte of a listing carries EOI. + + The tail is read one byte per transaction, which is what BASIC's GET# does: the + KERNAL addresses the drive to talk, takes one byte and untalks again. Reading the + listing in larger pieces cannot fail for this, because the drive then runs ahead + within one talk and reaches the last byte on its own. + """ + here = folder.upper() + name = f"$//{here}:*" + with check("SI-138: a listing read one byte at a time ends with status 64"): + total = len(listing_of(agent, name)) + agent.call(OPEN, channel=3, data=name.encode("ascii"), secondary=0) + try: + agent.status() + remaining = total - 4 + while remaining: + step = min(remaining, MAILBOX_CAPACITY) + agent.read_exact(step, channel=3) + remaining -= step + tail = b"" + for _ in range(8): + tail += agent.call(READ_COUNT, channel=3, count=1) + if agent.last_status & 64: + break + else: + raise Failure(f"{len(tail)} single byte reads at the end of a {total} byte " + f"listing all answered status 0: {tail!r}") + finally: + agent.call(CLOSE, channel=3) + detail(f"the last {len(tail)} bytes of a {total} byte listing read one at a time: {tail!r}") + if len(tail) != 4 or tail[-1] != 0: + raise Failure(f"end of file arrived after {len(tail)} of the last 4 bytes: {tail!r}") + + +def check_compatibility(agent, api, password, folder, root): + """doc/softiec_compatibility_spec.md, in the bytes a Commodore sends. + + The host suites check each requirement against the same code; these are the ones + whose answer depends on something only the device has: the IEC processor's device + number slots (U0>), the CPU the firmware runs on, whose char is signed on + the Nios II of an Ultimate 64 and unsigned on the RISC-V of an Ultimate 64 II and an + Ultimate II+L (the shifted space rule, SI-147), and the real bus timing of a command + that fills the 254 byte buffer. + """ + here = folder.upper().encode("ascii") + directory = f"{root.rstrip('/')}/{folder}" + + def unrecognised_command(): + response = agent.command(bytes([0]), allowed=(31,)) + detail(response) + + def scratch_nothing(): + response = agent.command(b"S//" + here + b"/:NOSUCHFILE\r", allowed=(1,)) + if not response.startswith("01, FILES SCRATCHED,00"): + raise Failure(f"answered {response!r}") + + def initialize(): + agent.command(b"I\r", allowed=(0,)) + agent.command(b"UI\r", allowed=(73,)) + + def memory_read(): + probe = agent.command_reply(b"M-R" + bytes([0xA4, 0xFE, 2]) + b"\r", 2) + detail(f"M-R $FEA4,2 answered {probe.hex()}") + if probe != bytes(2): + raise Failure(f"M-R answered {probe!r}") + agent.status((0,)) + + def partition_directory(): + listing = listing_of(agent, "$=P") + detail(f"{len(listing)} bytes, header {listing[:6].hex()}, last line {listing[-32:]!r}") + # Every problem is reported, so #890's footer shows even when the header is wrong too. + problems = [] + if b"BLOCKS FREE" in listing or listing[-2:] != bytes(2): + problems.append("the partition directory ends with a blocks free line (#890)") + if listing[4] != 1: + problems.append(f"the header counts {listing[4]} partitions, expected 1") + if listing[:4] != bytes([1, 4, 1, 1]): + problems.append(f"the listing starts {listing[:4].hex()}, expected 01040101") + if problems: + raise Failure("; ".join(problems)) + + def device_number(): + moved = agent.move_drive(12) + detail(f"after U0>+CHR$(12) the drive list reports device {moved}") + if moved != 12: + agent.status((0,)) + raise Failure(f"the drive stayed at device {moved}") + try: + reply = agent.call(3, 15, device=12, expect=STATUS_BYTES).decode("ascii").strip() + detail(f"device 12 answered {reply!r}") + if not reply.startswith("00,"): + raise Failure(f"device 12 answered {reply!r}") + finally: + # Back to device 11 whatever happened, so the checks after this one still + # have their drive. + agent.move_drive(11) + agent.status((0,)) + + def left_arrow(): + agent.command(b"CD//" + here + b"\r") + agent.command(b"MD:_\r") + agent.command(b"CD/_\r") + agent.command(b"CD:_\r") + agent.command(b"RD:_\r") + agent.command(b"CD//\r") + + def rename_directory(): + # HD 9-26 heads its section "Renaming Files and Subdirectories", and sd2iec + # matches an entry of any type, so R renames a subdirectory as well as a file. + agent.command(b"CD//" + here + b"\r") + agent.command(b"MD:DIRA\r") + agent.command(b"R:DIRB=DIRA\r", allowed=(0,)) + agent.command(b"CD:DIRB\r") + agent.command(b"CD//" + here + b"\r") + response = agent.command(b"R:DIRC=DIRA\r", allowed=(62,)) + detail(f"a name that belongs to nothing answers {response!r}") + agent.command(b"RD:DIRB\r") + agent.command(b"CD//\r") + + def shifted_space(): + for name, host in ((b"PAD\xa0", "PAD.seq"), (b"IN\xa0SIDE", "IN{A0}SIDE.seq")): + agent.call(1, channel=3, data=b"//" + here + b"/:" + name + b",S,W") + try: + agent.status((0,)) + agent.call(2, channel=3, data=b"X") + finally: + agent.call(4, channel=3) + with ftp.session(api.host, password) as client: + entries = ftp.names(client, directory) + detail(f"{name!r} is stored as one of {sorted(entries)}") + if host not in entries: + raise Failure(f"{name!r} was not stored as {host}: {entries}") + + def command_length(): + pad = 253 - len(b"S//" + here + b"/:") + agent.command(b"S//" + here + b"/:" + b"N" * pad, allowed=(1,)) + response = agent.command(b"S//" + here + b"/:" + b"N" * (pad + 1), allowed=(32,)) + detail(response) + + def format_image(): + agent.command(b"N//" + here + b"/:MADE.D64,AB\r") + with ftp.session(api.host, password) as client: + image = ftp.retrieve(client, f"{directory}/MADE.D64") + detail(f"MADE.D64 is {len(image)} bytes, label {image[BAM_OFFSET + 144:BAM_OFFSET + 148]!r}") + if len(image) != 174848 or image[BAM_OFFSET + 144:BAM_OFFSET + 148] != b"MADE": + raise Failure("N did not create a formatted 1541 image") + + def resets(): + agent.call(1, channel=4, data=b"//" + here + b"/:KEPT,S,W") + try: + agent.status() + agent.call(2, channel=4, data=b"abc") + response = agent.command(b"UJ\r", allowed=(73,)) + detail(f"UJ answered {response!r} with a file open for writing") + finally: + agent.call(4, channel=4) + agent.call(1, channel=3, data=b"//" + here + b"/:KEPT,S,R") + try: + agent.status() + kept = agent.read_stream(channel=3) + finally: + agent.call(4, channel=3) + if kept != b"abc": + raise Failure(f"the file UJ closed holds {kept!r}") + agent.command(b"CD//" + here + b"\r") + response = agent.command(bytes([ord("U"), 0xCA]) + b"\r", allowed=(73,)) + where = agent.command_reply(b"XPWD\r", 32).decode("ascii").strip() + detail(f"U+shifted J answered {response!r}, then XPWD {where!r}") + if where != "1:/": + raise Failure(f"after U+shifted J the working directory is {where!r}") + + def x00_header(name, record_length=0): + return b"C64File\0" + name.ljust(16, b"\0") + b"\0" + bytes([record_length]) + + def x00_read(): + with ftp.session(api.host, password) as client: + ftp.store(client, f"{directory}/GAME.P00", x00_header(b"MY GAME") + b"PAYLOAD") + listing = listing_of(agent, f"$//{folder.upper()}/:MY*") + lines = [parse_directory_line(listing[i:i + LINE]) for i in range(LINE, len(listing) - LINE, LINE)] + detail(f"$:MY* lists {lines}") + if (1, "MY GAME", "PRG") not in lines: + raise Failure(f"GAME.P00 is not listed as MY GAME PRG: {lines}") + agent.call(1, channel=3, data=b"//" + here + b"/:MY GAME,P,R") + try: + agent.status() + data = agent.read_stream(channel=3) + finally: + agent.call(4, channel=3) + detail(f"MY GAME reads {data!r}") + if data != b"PAYLOAD": + raise Failure(f"MY GAME reads {data!r}") + agent.command(b"R//" + here + b"/:TUNE=//" + here + b"/:MY GAME\r") + with ftp.session(api.host, password) as client: + renamed = ftp.retrieve(client, f"{directory}/GAME.P00") + detail(f"after R:TUNE=MY GAME the header names {renamed[8:24]!r}") + if renamed[:26] != x00_header(b"TUNE"): + raise Failure(f"the rename left the header as {renamed[:26]!r}") + response = agent.command(b"S//" + here + b"/:TUNE\r", allowed=(1,)) + with ftp.session(api.host, password) as client: + left = ftp.names(client, directory) + detail(f"S:TUNE answered {response!r}") + if not response.startswith("01, FILES SCRATCHED,01") or "GAME.P00" in left: + raise Failure(f"S:TUNE answered {response!r} and left {sorted(left)}") + + def rel_layouts(): + # sd2iec's layout: the record length in one byte, then records of three bytes. + with ftp.session(api.host, password) as client: + ftp.store(client, f"{directory}/SDREL.rel", bytes([3]) + b"\0aabbb") + agent.call(1, channel=3, data=b"//" + here + b"/:SDREL,L") + try: + agent.status() + agent.command(bytes([ord("P"), 96 + 3, 2, 0, 1])) + record = agent.read_stream(channel=3) + finally: + agent.call(4, channel=3) + detail(f"record 2 of SDREL reads {record!r}") + if record != b"bbb": + raise Failure(f"record 2 of a one byte layout file reads {record!r}") + + # Each check reports on its own, so a firmware that fails one still shows the rest. + failed = [] + for label, action in ( + ("SI-031: a command that is not a command letter answers 31", unrecognised_command), + ("SI-033: a scratch that matches nothing answers 01", scratch_nothing), + ("SI-053: I answers OK, UI the DOS version", initialize), + ("SI-105: M-R answers the two bytes C64 OS asks for, all zero", memory_read), + ("SI-045, SI-046, SI-130: the partition directory", partition_directory), + ("SI-100: U0> moves the drive to device 12 on the bus, and U0> moves it back", device_number), + ("SI-014: a left arrow between slashes is a directory name", left_arrow), + ("SI-147, SI-148: a shifted space in a name, on this CPU", shifted_space), + ("SI-021, SI-022: a 253 byte command runs, a 254 byte one is refused", command_length), + ("SI-071: N creates a D64 image", format_image), + ("SI-103: UJ closes the channels and U+shifted J returns to the root, and the drive still answers", resets), + ("SI-074: R renames a subdirectory", rename_directory), + ("SI-144: a P00 file lists, loads, renames and scratches under the name in its header", x00_read), + ("SI-084: a relative file in sd2iec's one byte layout reads its records", rel_layouts), + ): + try: + with check(label): + action() + except Failure as exc: + failed.append(str(exc)) + agent.call(4, channel=3) + if failed: + raise Failure(f"{len(failed)} compatibility checks failed") + + def listing_of(agent, name): """The whole of one directory stream, read in mailbox sized pieces.""" agent.call(1, channel=3, data=name.encode("ascii"), secondary=0) @@ -213,6 +515,37 @@ def check_partition_directory(agent, api): raise Failure(f"A partition rooted at a directory is typed {kind!r}, expected 'NAT'") +def check_partition_commands(agent): + """#877 in its programmatic form, and the partition commands that carry a byte.""" + # CMD DOS has two spellings of Change Partition: "CPn" with the number in ASCII, + # and "C" followed by a shifted P and the number as a byte. The byte can be 13, + # which is the same carriage return BASIC appends, so a drive that drops the + # terminator without looking at the command loses the parameter. + with check("C reads a partition number of 13 as a number"): + response = agent.command(bytes([ord("C"), 0xD0, 13]), allowed=(77,)) + detail(response) + if not response.startswith("77,SELECTED PARTITION ILLEGAL,13"): + raise Failure(f"Selecting partition 13 answered {response!r}") + response = agent.command(bytes([ord("C"), 0xD0, 1]), allowed=(2,)) + if not response.startswith("02,PARTITION SELECTED,01"): + raise Failure(f"Selecting partition 1 answered {response!r}") + + # G-P answers with thirty bytes and a carriage return: the type, a reserved byte, + # the partition number and the name the partition directory shows. + with check("G-P reports the type, the number and the name of the partition"): + info = agent.command_reply(b"G-P" + bytes([1]), 40) + detail(f"{len(info)} bytes, type {info[0]}, partition {info[2]}, name {info[3:19]!r}") + if len(info) != 31 or info[30] != 13: + raise Failure(f"G-P answered {len(info)} bytes ending {info[-1:]!r}, expected 31 ending in a carriage return") + if info[0] != 1 or info[1] != 0: + raise Failure(f"G-P reports type {info[0]} in byte 0 and {info[1]} in the reserved byte 1, expected 1 and 0") + if info[2] != 1: + raise Failure(f"G-P reports partition {info[2]}, expected 1") + name = info[3:19].rstrip(b"\0").decode("ascii", "replace") + if name.startswith("/"): + raise Failure(f"G-P names the partition by its path, {name!r}") + + def run(args): api = UltimateApi(args.host, args.password, args.timeout) agent = Agent(api) @@ -238,7 +571,9 @@ def run(args): agent.start() started = True agent.call(1, channel=15) - agent.status((0, 73)) + # The error channel still holds whatever the last program left there, which after + # an aborted run on a firmware without these fixes can be any error. + agent.status(tuple(range(100))) agent.command("CD//") root = partition_path(api) if not original_path.casefold().startswith(root.casefold()): @@ -258,7 +593,11 @@ def run(args): ("command channel", lambda: check_command_channel(agent, api, args.password, folder, root)), ("block commands", lambda: check_block_commands(agent, api, args.password, folder, image)), ("time stamp filter", lambda: check_timestamp_filter(agent, api, args.password, folder, root)), - ("partition directory", lambda: check_partition_directory(agent, api))): + ("listing layout", lambda: check_listing_layout(agent, folder)), + ("listing end of file", lambda: check_listing_eof(agent, folder)), + ("partition directory", lambda: check_partition_directory(agent, api)), + ("partition commands", lambda: check_partition_commands(agent)), + ("compatibility specification", lambda: check_compatibility(agent, api, args.password, folder, root))): section(label) try: agent.command("CD//") diff --git a/tests/e2e/io/iec/iec_agent.py b/tests/e2e/io/iec/iec_agent.py index a94cf2fd8..cf3c3944c 100644 --- a/tests/e2e/io/iec/iec_agent.py +++ b/tests/e2e/io/iec/iec_agent.py @@ -51,6 +51,14 @@ GRACE_SECONDS = 2.0 +def iec_drive(api): + """The Software IEC drive's entry in the drive list.""" + for entry in api.rest.json("/v1/drives")["drives"]: + if "IEC Drive" in entry: + return entry["IEC Drive"] + raise Failure("The drive list has no IEC Drive") + + def transfer_seconds(op, carried): """How long to leave the C64 alone for one mailbox operation.""" return FIXED_SECONDS[op] + (carried * SECONDS_PER_BYTE) @@ -68,6 +76,10 @@ def __init__(self, api, softiec_device=11): self.overruns = 0 # The KERNAL status of the last transaction. Bit 6 is end of file. self.last_status = 0 + # Read the mailbox back after writing it, before the agent is told to act. A REST + # upload that could not be stored (a full RAM disk) has been seen to answer success and + # leave the old bytes in place, which the agent would then put on the bus. + self.verify_writes = False def start(self): self.api.machine.close_menu_from_anywhere() @@ -99,6 +111,9 @@ def call(self, op, channel=5, data=b"", device=11, count=None, secondary=None, e raise ValueError("READ_COUNT needs at least one byte") if data: self.api.machine.writemem(0xc100, data) + if self.verify_writes and (self.api.machine.readmem(0xc100, len(data)) != bytes(data)): + raise Failure(f"the agent's mailbox does not hold the {len(data)} bytes just " + f"written to it over REST") # The KERNAL refuses logical file number zero, so a directory, which needs # secondary address zero, is opened on a different logical file number. self.api.machine.writemem(0xc002, bytes( @@ -168,4 +183,32 @@ def status(self, allowed=(0,)): def command(self, command, allowed=(0,)): self.call(WRITE, 15, command if isinstance(command, bytes) else command.encode("ascii")) - self.status(allowed) + return self.status(allowed) + + def command_reply(self, command, size): + """A command whose answer is data rather than a status line, such as G-P.""" + self.call(WRITE, 15, command) + return self.call(READ_TO_EOI, 15, expect=size) + + def move_drive(self, device): + """Moves the Software IEC drive to `device` with U0>, and returns the device number + the drive list reports afterwards. + + The drive list says where the drive went without addressing a device that may not + be there: a KERNAL open of an absent device leaves the agent busy past its budget. + When the drive moved, the command channel is closed on the old number and opened on + the new one, and later calls address the new number. + """ + old = self.softiec_device + self.call(WRITE, 15, b"U0>" + bytes([device]) + b"\r", device=old) + moved = iec_drive(self.api)["bus_id"] + if (moved == device) and (device != old): + try: + # Closing addresses the device the file was opened on, which is not present + # any more; the KERNAL says so in ST and closes the file all the same. + self.call(CLOSE, channel=15, device=old) + except Failure: + pass + self.softiec_device = device + self.call(OPEN, channel=15, device=device) + return moved diff --git a/tests/soak/README.md b/tests/soak/README.md index d6351d4c9..113198a57 100644 --- a/tests/soak/README.md +++ b/tests/soak/README.md @@ -18,6 +18,7 @@ and run only when `--soak` or `--all` asks for them. | `filemanager/prg_context_menu_leak_test.py` | The browser's PRG context-menu load actions, which go through a different code path from the REST launcher | | `filemanager/browser_refresh_leak_test.py` | The filesystem-refresh matrix, which needs a browser open on a directory while its contents change | | `filemanager/mount_cache_leak_test.py` | Entering one disk image after another, which mounts each one and holds the image file open | +| `io/iec/softiec_soak_test.py` | The Software IEC drive driven from the C64 over the real bus while REST and FTP load the device (#877). `--mode` selects a realistic C64 OS soak, a hostile stress that edge-tests the command channel, OPEN names, x00 files, channels, transfers, direct access, the disk image types, the UCI target and the PC lanes racing the bus, or `both` in turn. `--log` runs each phase with logging off, on, both in turn, or toggled during the phase, and correlates the device's syslog against every command, open and close the suite made; `--syslog-spool` names a file an external collector writes, and without it the suite binds the UDP port the device's syslog setting names when it points at this host. Fails if the firmware stops answering, if fixture data read back differs, if the heap does not come back, or if the log contradicts what the suite did; `--profile stress` runs the stress mode for ten minutes and `--profile soak` runs the soak mode for four hours, both with logging off. The log rendering and correlation live in the sibling module `softiec_log.py` | The heap suites all read `GET /v1/machine:heap`. Firmware predating that endpoint answers 404 and their checks skip, so they are safe to run against any @@ -27,7 +28,8 @@ rather than a single before-and-after reading; the reason is in `network/`'s `*_probe.py` modules, `stream_monitor.py` and `connection_runtime.py` are protocol drivers and shared runtime for -`connection_test.py`. +`connection_test.py`. `io/iec/softiec_log.py` is the device-log rendering and +correlation module `io/iec/softiec_soak_test.py` imports. ## Running diff --git a/tests/soak/io/iec/softiec_log.py b/tests/soak/io/iec/softiec_log.py new file mode 100644 index 000000000..4e47b0f9d --- /dev/null +++ b/tests/soak/io/iec/softiec_log.py @@ -0,0 +1,907 @@ +"""The device-log side of the Software IEC soak and stress suite. + +The Software IEC drive writes one syslog line for a command that leaves an error, for an +open that fails and for the first failure of a channel, and, with the setting "Log Every +Operation" on, one more for every other command, open and data-channel close, with the +reply of a command that answers data and the host file an open reached. The format is +built by IecChannel::log_line in software/io/iec/iec_channel.cc and the text of each field +is rendered by softiec_log_text in software/io/iec/iec_log.h. + +This module reproduces that rendering in Python, parses the lines back into fields, and +correlates a phase's lines with what the C64 lane (and the UCI target) actually did. It is +kept separate from the suite so it can be exercised on its own with synthetic lines, which +the suite's dry run does before any device is touched. + +What is designed around, from the firmware: + + * A command is executed when the bus write to channel 15 ends. It always logs + "command failed" when the drive failed (error code >= 20 and not 73, the check in + IecChannel::drive_failed), and otherwise logs "command" only when logging is on. So the + two-digit status the C64 reads next decides which line to expect and whether it appears + with logging off. + * An open on a data secondary logs "open" or "open failed" the same way, with chan the + secondary address and txt the name bytes. A data-channel close logs "close" only with + logging on. Reads and data writes log nothing. Closing channel 15 logs nothing. + * "listing end" is logged when a listing is read to its end, and "channel fault" once + after a channel fails. Both are treated as optional here, never as required. + * The line's "-> status" is the error channel at the time of logging, which is what the + C64 reads next for a command or an open, so the two-digit code is comparable. A command + that answers data carries the first bytes of the reply behind a "reply" label. + +Losses this correlation accounts for rather than hides: + + * printf is character by character and not atomic across tasks, so another task's message + can split a "SoftIEC:" line; the part after the split arrives in a later datagram. A + fragment that carries the prefix but does not parse is counted as a split, and a missing + expected line is only a failure when the number missing exceeds the splits seen. + * The syslog task throttles to about 200 lines a second and drops on a 16 KB overflow, and + UDP can lose a datagram. These show as missing lines, bounded by the same rule. +""" + +from __future__ import annotations + +import re +import socket +import threading +import time +from dataclasses import dataclass, field + +# The prefix every line carries (SOFTIEC_LOG_PREFIX in iec_log.h). Grep key in a device log. +LOG_PREFIX = "SoftIEC: " + +# Room the firmware gives softiec_log_text for a rendered field: SOFTIEC_LOG_TEXT_SIZE, +# which is 4 * SOFTIEC_LOG_MAX_BYTES + 4. The renderer fills up to this many characters and +# then cuts with "..", so a long payload is cut by character count, not by byte count. +LOG_TEXT_SIZE = 4 * 64 + 4 + +# The line one external collector writes, one datagram per line: the source address, the +# time it arrived as HH:MM:SS, and the line text with its own spaces kept. The suite's +# --syslog-spool option reads exactly this, so the format is a documented constant the +# collector and the suite share. +SPOOL_FORMAT = " " + +# The largest step between the sequence numbers of two lines in a row that still counts as +# lines lost between them; a longer step is a number made unreadable by another task's text. +MAX_SEQUENCE_STEP = 500 + +# The fewest characters another task's message puts into a field. The shortest seen is a +# socket number and address, over thirty; renderings of different bytes differ by far less. +MIN_INTERLEAVED = 8 + +# The sequence number a line ends with, also found at the end of the second half of a split line. +_SEQUENCE_TAIL = re.compile(r" #(\d+)$") + +# How far from the diagonal the alignment of events and lines looks, on top of the difference +# in their counts. Wide enough for the lines a phase loses in a burst, bounded so the table +# stays linear in the length of the phase. +ALIGN_BAND = 400 + +_HEX = "0123456789ABCDEF" + +# The head of a well-formed line, up to the first rendered field. "what" carries spaces +# ("command failed", "open failed"), so it is captured lazily up to " dev=". +_HEAD = re.compile(r"^(?P.+?) dev=(?P-?\d+) chan=(?P-?\d+) " + r"part=(?P-?\d+) dir=") + + +def render_text(data: bytes, out_size: int = LOG_TEXT_SIZE) -> str: + """Render bytes the way softiec_log_text does: a printable ASCII byte stands for itself, + a zero, line feed, carriage return, quote and backslash get short escapes, every other + byte becomes \\xNN with uppercase hex, and a rendering that fills the buffer ends in + "..". Reproduced character for character so a rendered field matches the device's.""" + out: list[str] = [] + written = 0 + if out_size < 1: + return "" + for b in data: + if b == 0x00: + esc = "\\0" + elif b == 0x0A: + esc = "\\n" + elif b == 0x0D: + esc = "\\r" + elif b == 0x22: + esc = "\\\"" + elif b == 0x5C: + esc = "\\\\" + elif 0x20 <= b < 0x7F: + esc = chr(b) + else: + esc = "\\x" + _HEX[(b >> 4) & 15] + _HEX[b & 15] + n = len(esc) + if (written + n) >= (out_size - 2): + if (written + 2) < out_size: + out.append("..") + break + out.append(esc) + written += n + return "".join(out) + + +# --------------------------------------------------------------------------- +# Expected events, recorded by the suite as it drives the bus +# --------------------------------------------------------------------------- + +# What the C64 lane did, in the order it did it. `status` is the two-digit code the C64 read +# from the error channel next, which is also the line's "-> status", and it decides the +# expected line: a failure (code >= 20 and not 73) always logs, anything else logs only with +# logging on. `reply` is the bytes a command that answers data returned, compared against the +# line's "reply" field when logging is on. +_FAILURE_MIN = 20 +_NOT_FAILURE = 73 # ERR_DOS, the answer to UI and the resets, is not a failure + + +@dataclass +class Event: + op: str # "command", "open", "close" or "marker" + chan: int # the channel the line carries: 15 for a command, the + # secondary address for an open or a close + txt: bytes # the command or name bytes as the C64 sent them + status: int | None = None # the two-digit code the C64 read next, or None if unread + reply: bytes | None = None # a command's data reply, or None + dev: int | None = 11 # the drive's bus id, or None to skip comparing it + # When the bus operation started and finished, on the suite's own clock. Used only in + # toggle mode, to decide which log setting was in force while it ran. + t0: float | None = None + t1: float | None = None + # A line that may or may not appear: a recovery close of a channel that may not have been + # open, or a UCI operation whose channel state is not tracked. Never required, but a line + # that does appear is still verified. + optional: bool = False + + @property + def failure(self) -> bool: + """Whether the drive failed, so the line is written whatever the log setting is.""" + return (self.status is not None) and (self.status >= _FAILURE_MIN) \ + and (self.status != _NOT_FAILURE) + + @property + def what(self) -> str: + """The `what` field this event should produce.""" + if self.op == "close": + return "close" + if self.op == "open": + return "open failed" if self.failure else "open" + return "command failed" if self.failure else "command" + + def always_logged(self) -> bool: + """A failed command or open logs whatever the setting is; a marker is a failed + command; a close and a successful command or open log only with logging on.""" + return self.op != "close" and self.failure + + @property + def cls(self) -> str: + return "close" if self.op == "close" else ("open" if self.op == "open" else "cmd") + + @property + def key(self) -> tuple[str, int, str]: + # The channel is part of the key: the closes that I and UJ log for channels 0 to 14 + # carry no text, and without it one lost close would pair every later one with its + # neighbour's line. + return (self.cls, self.chan, render_text(self.txt)) + + +@dataclass +class Flip: + """One change of the "Log Every Operation" setting made while the bus was busy: when it + was requested, when a read-back confirmed the new value, and the value it set.""" + requested: float + confirmed: float + on: bool + + +def steady_state_at(flips: list[Flip], initial_on: bool, t0: float, t1: float) -> str: + """Whether the log setting was steady, and to what, for the whole span [t0, t1]. + + Returns "on" or "off" when the span lies inside one steady window, and "overlap" when a + flip's request-to-confirm window touches it, so a line for it can honestly go either way. + """ + on = initial_on + for flip in flips: + # The setting is unsettled from the request until the read-back confirmed it. + if (t0 <= flip.confirmed) and (t1 >= flip.requested): + return "overlap" + if t0 >= flip.confirmed: + on = flip.on + return "on" if on else "off" + + +# --------------------------------------------------------------------------- +# Parsed lines +# --------------------------------------------------------------------------- + + +@dataclass +class LogLine: + what: str + dev: int + chan: int + part: int + dir: str + length: int + txt: str + label: str | None + label_text: str | None + status_code: int | None + error: str + raw: str + # The sequence number the drive ends every line with (" #N"), or None for a firmware that + # does not write one. + seq: int | None = None + + @property + def cls(self) -> str: + if self.what.startswith("command"): + return "cmd" + if self.what.startswith("open"): + return "open" + if self.what == "close": + return "close" + if self.what == "listing end": + return "listing" + if self.what.startswith("channel fault"): + return "fault" + return "other" + + @property + def optional(self) -> bool: + # A marker line that pairs with no operation is one of the unrecorded outer markers. + return (self.cls in ("listing", "fault", "other")) or self.txt.startswith(MARKER_PREFIX_TEXT) + + @property + def success(self) -> bool: + """A line whose `what` names an operation that succeeded, so it is not written with + logging off; seeing one there is a defect in the setting, not a lost line.""" + return self.what in ("command", "open", "close") + + @property + def key(self) -> tuple[str, int, str]: + return (self.cls, self.chan, self.txt) + + +def _field(text: str, start: int) -> tuple[str | None, int]: + """The rendered field that starts at the opening quote at `start`, and the index after + its closing quote. A rendered field never carries an unescaped quote, so the first one + not preceded by a backslash closes it. Returns (None, len) when it is not terminated, + which marks the line as a split fragment.""" + if start >= len(text) or text[start] != '"': + return None, start + i = start + 1 + out: list[str] = [] + while i < len(text): + c = text[i] + if c == "\\" and (i + 1) < len(text): + out.append(c) + out.append(text[i + 1]) + i += 2 + continue + if c == '"': + return "".join(out), i + 1 + out.append(c) + i += 1 + return None, i + + +def parse_line(text: str) -> LogLine | None: + """One SoftIEC line to a LogLine, or None when the text carries the prefix but does not + parse (a split fragment) or does not carry the prefix at all (a foreign line). A caller + tells the two apart with `carries_prefix`.""" + at = text.find(LOG_PREFIX) + if at < 0: + return None + body = text[at + len(LOG_PREFIX):] + head = _HEAD.match(body) + if not head: + return None + rest = body[head.end():] + dir_text, i = _field(rest, 0) + if dir_text is None: + return None + m = re.match(r" len=(\d+) txt=", rest[i:]) + if not m: + return None + i += m.end() + txt, i = _field(rest, i) + if txt is None: + return None + label = None + label_text = None + tail = rest[i:] + lab = re.match(r" (\w+)=", tail) + if lab: + label = lab.group(1) + label_text, j = _field(rest, i + lab.end()) + if label_text is None: + return None + tail = rest[j:] + if not tail.startswith(" -> "): + return None + error = tail[4:] + seq = None + numbered = re.search(r" #(\d+)$", error) + if numbered: + seq = int(numbered.group(1)) + error = error[:numbered.start()] + code = None + if len(error) >= 2 and error[:2].isdigit(): + code = int(error[:2]) + return LogLine(what=head.group("what"), dev=int(head.group("dev")), + chan=int(head.group("chan")), part=int(head.group("part")), + dir=dir_text, length=int(m.group(1)), txt=txt, label=label, + label_text=label_text, status_code=code, error=error, raw=text, seq=seq) + + +def carries_prefix(text: str) -> bool: + return LOG_PREFIX in text + + +# --------------------------------------------------------------------------- +# Correlation +# --------------------------------------------------------------------------- + + +@dataclass +class Correlation: + label: str + matched: int = 0 + optional: int = 0 + splits: int = 0 + missing: list[str] = field(default_factory=list) + missing_failures: int = 0 + unexpected: list[str] = field(default_factory=list) + # A well-formed non-optional line that matched no operation. A printf split leaves a + # fragment that does not parse, so a line that parses and still matches nothing is a real + # line the drive should not have written: a fault, not a lost line. Kept apart from the + # split allowance, which forgives missing lines only. + unexpected_bad: list[str] = field(default_factory=list) + contradictions: list[str] = field(default_factory=list) + logging_off_success: list[str] = field(default_factory=list) + parsed: int = 0 + # From the sequence numbers: lines delivered twice (the same number and text, dropped + # before aligning), and numbers missing between the first and the last line of the window, + # each a line lost on the way or split so it did not parse. + duplicates: int = 0 + gaps: int = 0 + unreadable_numbers: int = 0 + # Numbers seen only at the end of a split line: the line arrived but did not parse. + split_numbers: int = 0 + # Lines another task's message was printed into, paired with their operation by kind, + # channel and byte count. + interleaved: int = 0 + numbered: bool = False + # In toggle mode: how many events were checked strictly in each state, and how many fell + # in a flip window and so had their success line treated as optional. + strict_on: int = 0 + strict_off: int = 0 + overlap: int = 0 + + @property + def allowance(self) -> int: + """How many expected lines may be missing: with sequence numbers, the numbers absent from + the window and the numbers whose line arrived split; without them, the split fragments + seen.""" + # A line whose number could not be read did arrive, and it spans one of the numbers + # counted as missing, so each one lowers the allowance by one. + return max(0, self.gaps + self.split_numbers - self.unreadable_numbers) \ + if self.numbered else self.splits + + @property + def unexplained_missing(self) -> int: + """Missing expected lines the lost or split lines cannot account for.""" + return max(0, len(self.missing) - self.allowance) + + def problems(self) -> list[str]: + out: list[str] = [] + out += self.contradictions + out += self.logging_off_success + out += self.unexpected_bad + if self.unexplained_missing > 0: + out.append(f"{len(self.missing)} expected line(s) missing with only " + f"{self.allowance} lost or split line(s) to account for them; first: " + + "; ".join(self.missing[:5])) + return out + + def ok(self) -> bool: + return not self.problems() + + def summary(self) -> str: + toggle = "" + if self.strict_on or self.strict_off or self.overlap: + toggle = (f", strict on {self.strict_on}, strict off {self.strict_off}, " + f"in a flip window {self.overlap}") + return (f"{self.label}: {self.parsed} lines parsed, {self.matched} matched, " + f"{len(self.missing)} missing ({self.missing_failures} of them failure " + f"lines), {len(self.unexpected)} unexpected ({len(self.unexpected_bad)} " + f"well-formed), {self.optional} optional, {self.splits} split, " + f"{self.duplicates} delivered twice, {self.gaps} sequence gaps, " + f"{self.unreadable_numbers} unreadable numbers, {self.split_numbers} numbers only in split lines, " + f"{self.interleaved} interleaved{toggle}") + + +def _contradictions(ev: Event, ln: LogLine) -> list[str]: + out = [] + if ev.chan != ln.chan: + out.append(f"chan {ln.chan}, expected {ev.chan}") + if (ev.dev is not None) and (ev.dev != ln.dev): + out.append(f"dev {ln.dev}, expected {ev.dev}") + # The line carries the real byte count in its len field even when the rendering is cut, + # so two payloads with the same rendered prefix but a different length are told apart. + if ln.length != len(ev.txt): + out.append(f"len {ln.length}, expected {len(ev.txt)}") + if ev.op == "close" and ln.txt != "": + out.append(f"close carried txt {ln.txt!r}, expected none") + if (ev.status is not None) and (ln.status_code is not None) and (ev.status != ln.status_code): + out.append(f"status {ln.status_code}, expected {ev.status}") + if (ev.reply is not None) and (ln.label == "reply"): + want = render_text(ev.reply) + if want != ln.label_text: + out.append(f"reply {ln.label_text!r}, expected {want!r}") + return out + + +def _quote(ev: Event | None = None, ln: LogLine | None = None) -> str: + parts = [] + if ev is not None: + parts.append(f"expected {ev.what} chan={ev.chan} txt={render_text(ev.txt)!r}" + + (f" status={ev.status}" if ev.status is not None else "")) + if ln is not None: + parts.append(f"line {ln.raw!r}") + return " | ".join(parts) + + +def correlate(events: list[Event], texts: list[str], logging_on: bool, + label: str | None = None) -> Correlation: + """A phase whose log setting was steady the whole time. `state_of` says every event was + in "on" or "off"; the unaligned-success-line rule applies, because with the setting off + no success line should appear at all.""" + state = "on" if logging_on else "off" + return _correlate(events, texts, lambda _ev: state, + label=label or f"logging {state}", steady_state=state) + + +def correlate_toggle(events: list[Event], texts: list[str], flips: list[Flip], + initial_on: bool, label: str | None = None) -> Correlation: + """A phase whose log setting was flipped while the bus ran. Each event is checked against + the state in force for the whole time it ran; an event that overlapped a flip window has + its success line treated as optional, but a line that is present still has to match. So a + flip that silently does not take effect shows up as a strict-state mismatch rather than + being absorbed.""" + def state_of(ev: Event) -> str: + if ev.t0 is None or ev.t1 is None: + return "overlap" + return steady_state_at(flips, initial_on, ev.t0, ev.t1) + return _correlate(events, texts, state_of, label=label or "logging toggled") + + +def _deduplicate(lines: list[LogLine], result: Correlation, + arrivals: list[tuple[int, bool]]) -> list[LogLine]: + """Drops a line delivered twice, counts the sequence numbers missing from the window and + the numbers seen only at the end of a split line, and reports two different lines that + carry the same number. Lines without a number (an older firmware) are passed through and + the split count stays the allowance.""" + numbers = [ln.seq for ln in lines if ln.seq is not None] + if not numbers: + return lines + result.numbered = True + kept: list[LogLine] = [] + seen: dict[int, LogLine] = {} + for ln in lines: + if ln.seq is None: + kept.append(ln) + continue + first = seen.get(ln.seq) + if first is None: + seen[ln.seq] = ln + kept.append(ln) + elif _body(first.raw) == _body(ln.raw): + result.duplicates += 1 + else: + result.contradictions.append( + f"two different lines carry sequence number {ln.seq}: {first.raw!r} and {ln.raw!r}") + # Gaps are counted between numbers that step forward in the order the lines arrived. A + # number another task's message was printed into can be far off (#4415 read as #44152), + # so a step backwards or of more than MAX_SEQUENCE_STEP is not a gap: that number is + # counted as unreadable and skipped. + parsed_numbers = set(seen) + counted: set[int] = set() + previous = None + for seq, _parsed in arrivals: + if seq in counted: + continue # the same number again: a line delivered twice + if previous is None: + previous = seq + elif previous < seq <= previous + MAX_SEQUENCE_STEP: + result.gaps += seq - previous - 1 + previous = seq + else: + result.unreadable_numbers += 1 + continue + counted.add(seq) + if seq not in parsed_numbers: + result.split_numbers += 1 + return kept + + +def _align(events: list[Event], lines: list[LogLine], pairs) -> list[tuple[str, Event | None, LogLine | None]]: + """The events and the lines in one order-keeping alignment with the most pairs, as a + list of ("pair", event, line), ("event", event, None) and ("line", None, line). + + A longest common subsequence rather than a greedy walk: the same command, open or close + recurs every few iterations, and with many lines lost a greedy walk can pair a line with a + later copy of its operation and throw every pair after it out. The table is computed in a + band around the diagonal, ALIGN_BAND cells to each side, which the losses of a phase stay + well within, so its cost is linear in the length of the phase.""" + n, m = len(events), len(lines) + if n == 0 or m == 0: + return [("event", ev, None) for ev in events] + [("line", None, ln) for ln in lines] + band = ALIGN_BAND + abs(n - m) + width = m + 1 + # The exact pairing by key is checked first; the slower interleaving test runs only for a + # line of the same kind and channel whose text is longer than the event's rendering. + event_keys = [ev.key for ev in events] + line_keys = [ln.key for ln in lines] + score = [0] * ((n + 1) * width) + move = bytearray((n + 1) * width) # 1 pair, 2 skip an event, 3 skip a line + for j in range(1, m + 1): + move[j] = 3 + for i in range(1, n + 1): + ev = events[i - 1] + centre = (i * m) // n + low = max(1, centre - band) + high = min(m, centre + band) + row = i * width + above = row - width + score[row + low - 1] = score[above + low - 1] if low > 1 else 0 + move[row] = 2 + if low > 1: + move[row + low - 1] = 2 + for j in range(low, high + 1): + best = score[above + j] + step = 2 + if score[row + j - 1] > best: + best = score[row + j - 1] + step = 3 + if (score[above + j - 1] + 1 > best) and ( + event_keys[i - 1] == line_keys[j - 1] + or ((event_keys[i - 1][:2] == line_keys[j - 1][:2]) + and (len(line_keys[j - 1][2]) >= len(event_keys[i - 1][2]) + MIN_INTERLEAVED) + and pairs(ev, lines[j - 1]))): + best = score[above + j - 1] + 1 + step = 1 + score[row + j] = best + move[row + j] = step + for j in range(high + 1, m + 1): + score[row + j] = score[row + j - 1] + move[row + j] = 3 + out: list[tuple[str, Event | None, LogLine | None]] = [] + i, j = n, m + while i > 0 or j > 0: + step = move[i * width + j] if (i > 0 and j > 0) else (2 if i > 0 else 3) + if step == 1: + out.append(("pair", events[i - 1], lines[j - 1])) + i -= 1 + j -= 1 + elif step == 2: + out.append(("event", events[i - 1], None)) + i -= 1 + else: + out.append(("line", None, lines[j - 1])) + j -= 1 + out.reverse() + return out + + +def _interleaved(want: str, got: str) -> bool: + """Whether `got` is `want` with another task's text, at least MIN_INTERLEAVED characters, + inserted at one place.""" + if len(got) < len(want) + MIN_INTERLEAVED: + return False + prefix = 0 + while (prefix < len(want)) and (want[prefix] == got[prefix]): + prefix += 1 + suffix = 0 + while (suffix < len(want) - prefix) and (want[len(want) - 1 - suffix] == got[len(got) - 1 - suffix]): + suffix += 1 + return prefix + suffix == len(want) + + +def _body(text: str) -> str: + """A line from its prefix on, so the same line in two datagrams compares equal.""" + at = text.find(LOG_PREFIX) + return text[at:] if at >= 0 else text + + +def _correlate(events, texts, state_of, label, steady_state=None): + """The shared engine. `state_of(ev)` returns "on", "off" or "overlap" for one event, and + decides whether its line is required, forbidden or optional. An aligned pair is verified + field by field whatever the state, so a wrong chan, dev, status or reply always fails.""" + result = Correlation(label=label) + lines: list[LogLine] = [] + arrivals: list[tuple[int, bool]] = [] # (sequence number, whether its line parsed) + for text in texts: + parsed = parse_line(text) + if parsed is not None: + lines.append(parsed) + if parsed.seq is not None: + arrivals.append((parsed.seq, True)) + continue + if carries_prefix(text): + result.splits += 1 + # The end of a split line arrives on its own and still ends in its sequence number. + tail = _SEQUENCE_TAIL.search(text) + if tail: + arrivals.append((int(tail.group(1)), False)) + lines = _deduplicate(lines, result, arrivals) + result.parsed = len(lines) + + def expected(ev: Event) -> bool: + """Whether a line is required for this event: always for a failure, for every event + in an on window, and never for an optional event or in an off or a flip window for a + success.""" + if ev.optional: + return False + return ev.always_logged() or (state_of(ev) == "on") + + def count_state(ev: Event) -> None: + state = state_of(ev) + if state == "on": + result.strict_on += 1 + elif state == "off": + result.strict_off += 1 + else: + result.overlap += 1 + + def record_missing(ev: Event) -> None: + if not expected(ev): + return # a silent success in an off or a flip window is correct, not missing + result.missing.append(_quote(ev=ev)) + if ev.always_logged(): + result.missing_failures += 1 + + def record_unexpected(ln: LogLine) -> None: + result.unexpected.append(_quote(ln=ln)) + if (steady_state == "off") and ln.success: + result.logging_off_success.append( + f"a success line appeared with logging off: {ln.raw!r}") + if not ln.optional: + # A well-formed command, open or close line that matched no operation is a fault + # whatever the log setting; a split fragment does not parse and never reaches here. + result.unexpected_bad.append( + f"a well-formed {ln.what} line matched no operation: {ln.raw!r}") + + # An event that cannot write a line in its state, a success while logging is strictly + # off, is left out of the alignment: with logging off, hundreds of silent successes can + # stand between two failure lines, more than the lookahead spans. A success line that does + # appear with logging off then matches no event, which fails as an unexpected line. + silent = [ev for ev in events + if (not ev.optional) and (not ev.always_logged()) and (state_of(ev) == "off")] + for ev in silent: + count_state(ev) + events = [ev for ev in events + if ev.optional or ev.always_logged() or (state_of(ev) != "off")] + + def judge(ev: Event, ln: LogLine) -> None: + count_state(ev) + state = state_of(ev) + if (not ev.optional) and (state == "off") and ln.success and not ev.always_logged(): + # A success line matched an event whose window was strictly off: the setting did + # not take effect. In a flip window this would be allowed, which is why the + # window classification is by the event's own run time, not the line's. + result.logging_off_success.append( + f"a success line appeared while logging was off: {ln.raw!r}") + return + problems = _contradictions(ev, ln) + if problems: + result.contradictions.append(_quote(ev=ev, ln=ln) + " -> " + "; ".join(problems)) + else: + result.matched += 1 + + def pairs(ev: Event, ln: LogLine) -> bool: + """Whether a line is this event's line: the same kind, channel and text, or the same + kind, channel and byte count with another task's message printed into the middle of + the text (printf is not atomic, and a message without its newline in the right place + leaves the line well-formed).""" + if ev.key == ln.key: + return True + # Another task's message is a whole line of text, so a short difference is not one: the + # renderings of two different binary parameters (\xA0 against \0) differ by as little + # as two characters. The status has to agree as well. + status_agrees = (ev.status is None) or (ln.status_code is None) or (ev.status == ln.status_code) + return (ev.cls == ln.cls) and (ev.chan == ln.chan) and (ln.length == len(ev.txt)) \ + and status_agrees and _interleaved(render_text(ev.txt), ln.txt) + + for kind, ev, ln in _align(events, lines, pairs): + if kind == "pair": + if ev.key != ln.key: + result.interleaved += 1 + judge(ev, ln) + elif kind == "event": + record_missing(ev) + elif ln.optional: + result.optional += 1 + else: + record_unexpected(ln) + return result + + +# --------------------------------------------------------------------------- +# The device log, read from a spool file or off the wire +# --------------------------------------------------------------------------- + + +def parse_spool_line(line: str) -> tuple[str, str] | None: + """One SPOOL_FORMAT line to (source ip, text), or None when it is not that shape.""" + stripped = line.rstrip("\r\n") + parts = stripped.split(" ", 2) + if len(parts) < 3: + return None + ip, when, text = parts + if not re.match(r"^\d{1,3}(\.\d{1,3}){3}$", ip): + return None + if not re.match(r"^\d\d:\d\d:\d\d$", when): + return None + return ip, text + + +def read_spool(path: str, offset: int = 0) -> list[tuple[str, str]]: + """Every (source ip, text) the collector has written from byte `offset` on. A missing file + is empty. A spool shared by long runs grows to tens of megabytes, so a phase reads only + what was written since it started.""" + try: + with open(path, "rb") as raw: + raw.seek(offset) + data = raw.read() + except OSError: + return [] + out: list[tuple[str, str]] = [] + for line in data.decode("utf-8", errors="replace").splitlines(): + entry = parse_spool_line(line) + if entry is not None: + out.append(entry) + return out + + +MARKER_PREFIX = b"XSOAKLOG" +MARKER_PREFIX_TEXT = MARKER_PREFIX.decode("ascii") + + +def marker_text(nonce: str) -> bytes: + """The bytes of a marker command. X is a command letter, so X followed by anything but + PWD answers 30 and always logs a "command failed" line, whatever the log setting, which + is what makes a marker visible with logging off. The nonce is printable, so it renders as + itself in the log.""" + return MARKER_PREFIX + nonce.encode("ascii") + + +def select_window(entries: list[tuple[str, str]], start_nonce: str, end_nonce: str, + pre_nonce: str | None = None, + post_nonce: str | None = None) -> tuple[str | None, list[str]]: + """The device address the markers came from, and its lines in the phase's window. + + The inner markers (start and end) are recorded operations; the outer ones (pre and post), + when given, are not. The window runs from the pre marker, or from the start marker, to the + post marker, or to the end marker, or to the last line seen. The outer markers stay in the + window so that their sequence numbers bound it, and a split inner marker shows as a gap + between two numbered lines; an unpaired marker line is optional (LogLine.optional). The + address is read from the first marker found, so a spool holding several devices is + filtered to this one. Returns (None, []) if no marker was found, which a caller reports + rather than guessing.""" + wanted = {nonce: render_text(marker_text(nonce)) + for nonce in (pre_nonce, start_nonce, end_nonce, post_nonce) if nonce} + + def is_marker(text: str, nonce: str | None) -> bool: + # Found by its text anywhere in a datagram, so a marker line another task's message + # split still bounds the window. + return bool(nonce) and (f'txt="{wanted[nonce]}"' in text or wanted[nonce] + '"' in text) + + device_ip = None + for ip, text in entries: + if any(is_marker(text, nonce) for nonce in wanted): + device_ip = ip + break + if device_ip is None: + return None, [] + device_texts = [text for ip, text in entries if ip == device_ip] + + def index_of(nonce: str | None, begin: int = 0) -> int | None: + for i in range(begin, len(device_texts)): + if is_marker(device_texts[i], nonce): + return i + return None + + pre = index_of(pre_nonce) + start = index_of(start_nonce) + if pre is not None: + begin = pre + elif start is not None: + begin = start + else: + return None, [] + post = index_of(post_nonce, begin) + end = index_of(end_nonce, begin) + if post is not None: + finish = post + 1 + elif end is not None: + finish = end + 1 + else: + finish = len(device_texts) + return device_ip, device_texts[begin:finish] + + +class UdpLogSource: + """A UDP sink bound to one address and port, for a run that owns the syslog port. It + keeps (source ip, text) in arrival order, the same shape read_spool returns, so a phase + correlates the same way whether the lines came from a file or from the wire. + + Only for a single-suite run: two suites on one host cannot both bind one port, which is + why the spool file is the path a shared bench uses. + """ + + def __init__(self, bind_ip: str, port: int) -> None: + self.bind_ip = bind_ip + self.port = port + self._entries: list[tuple[str, str]] = [] + self._lock = threading.Lock() + self._sock: socket.socket | None = None + self._running = False + self._thread: threading.Thread | None = None + + def start(self) -> None: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1 << 20) + sock.bind((self.bind_ip, self.port)) + sock.settimeout(0.25) + self._sock = sock + self._running = True + self._thread = threading.Thread(target=self._receive, daemon=True) + self._thread.start() + + def _receive(self) -> None: + while self._running and self._sock is not None: + try: + data, (address, _port) = self._sock.recvfrom(4096) + except (TimeoutError, OSError): + continue + when = time.strftime("%H:%M:%S") + for text in data.decode("utf-8", "replace").rstrip("\r\n").split("\n"): + with self._lock: + self._entries.append((address, f"{when} {text}")) + + def entries(self) -> list[tuple[str, str]]: + # The stored text keeps the time in front, so it reads like a spool line without the + # address, which select_window does not need past the address it already has. + with self._lock: + return [(ip, text.split(" ", 1)[-1]) for ip, text in list(self._entries)] + + def stop(self) -> None: + self._running = False + if self._thread is not None: + self._thread.join(timeout=2) + if self._sock is not None: + self._sock.close() + self._sock = None + + +def parse_syslog_server(value: str) -> tuple[str, int] | None: + """The "Log to Syslog Server" setting as (ip, port), or None when it is empty or not an + address. The firmware defaults the port to 514 (software/network/syslog.cc).""" + value = (value or "").strip() + if not value: + return None + ip, sep, port = value.partition(":") + if not re.match(r"^\d{1,3}(\.\d{1,3}){3}$", ip): + return None + if sep and port.isdigit() and 0 < int(port) <= 0xFFFF: + return ip, int(port) + return ip, 514 + + +def local_addresses() -> set[str]: + """This host's IPv4 addresses, so the suite can tell whether the device logs here.""" + found = {"127.0.0.1", "0.0.0.0"} + try: + for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET): + found.add(info[4][0]) + except OSError: + pass + return found diff --git a/tests/soak/io/iec/softiec_soak_test.py b/tests/soak/io/iec/softiec_soak_test.py new file mode 100644 index 000000000..5ce927792 --- /dev/null +++ b/tests/soak/io/iec/softiec_soak_test.py @@ -0,0 +1,2129 @@ +#!/usr/bin/env python3 +"""Soak and stress for the Software IEC drive, driven from a real C64 over the bus. + +GideonZ/1541ultimate#877 reports the whole firmware becoming unresponsive while C64 +OS starts from a Software IEC partition, at a different point each time. This suite +drives the drive from a real C64 through the IEC agent, so every byte on the bus is +one the KERNAL puts there, while a REST lane and one or more FTP lanes load the device +from the PC side. None of the lanes touches C64 memory, which would disturb a transfer. + +It offers two kinds of run, chosen with --mode, and a way to run both one after the +other: + + * soak: the pattern of use a C64 OS session and a person put the drive through. A + session boots once from the #877 trace and then mostly browses directories, loads + applications and documents and reads them to the end, saves small settings files + with @, creates and scratches temporary files, polls the status channel, reads the + clock, and changes partition or directory now and then, with a few seconds of think + time between actions. It fails if the firmware stops answering, if data read back + differs from what was stored, or if the heap keeps shrinking. + + * stress: the same interface pushed as hard as the agent allows, with no think time. + It fuzzes the command channel and OPEN names, opens as many channels as the KERNAL + table holds, abandons transfers part way, saves and reads back large files, edits a + relative file at a high record number, drives direct access at the edges of a D64 + and past them, scratches with wide patterns in a full directory, nests directories + deep, changes the device number and back, and sends the resets and I with channels + open. The PC lanes race the bus: FTP fights over files in a shared directory the C64 + also uses, and REST reads the drive list without pauses and resets the drive. The stress run + fails only on death, on corruption of the read-only fixture files the lanes never + touch, on the drive ceasing to answer the C64 while REST still answers, or on heap + that does not come back after an idle settle. Fuzzed answers are only required to be + two-digit statuses; the exact codes are recorded and reported, not asserted, because + a hostile command has no single right answer. + + * both: the soak phase then the stress phase, each its own section and check with its + own heap verdict. The fixture is built once. Defaults are 1800 s of soak and 600 s + of stress. + +Both modes cover the whole Software IEC surface a normal session and a hostile one reach: +LOAD and SAVE on secondaries 0 and 1, append, USR, x00 wrapped files, D71, D81 and DNP +images and DNP subdirectories, rename, copy, lock, the clock, XPWD, partition info with a +byte, listings with type and date filters and a many-entry directory, and, between bus +steps, the UCI SoftIEC target (software/io/command_interface/softiec_target.cc) reached +over the cartridge registers as tests/e2e/io/command_interface/uci_targets_test.py reaches +it. The stress mode adds the hostile forms: buffer exhaustion, records at the edges, locked +files, copy with many sources, N of every image type and inside an image, many images to +push the mount cache, FTP writing into the image the C64 uses, and a REST softiec reset +during traffic. + +The device's own log is checked as well. --log chooses off, on, both (off then on, the +default), or toggle. In an off or on phase the setting "Log Every Operation" is fixed for +the phase; in a toggle phase a lane flips it every 10 to 20 seconds while the bus runs, so +a transfer overlaps a flip, which is the case Suite11-OperationLogNoReconfigure guards on +the host. The suite records every command, open and close it makes and correlates +the device's syslog lines against them: with logging off only the failure lines are +expected, with logging on every operation, and in a toggle phase each event is judged +against the setting in force while it ran. The syslog is read from a file an external +collector writes, one line per datagram as " ", named with +--syslog-spool; without it the suite binds the UDP port the device's "Log to Syslog Server" +setting names when that address is one of this host's, and otherwise reports why it could +not correlate rather than failing the run. A unique marker command at the start and end of +each phase gives the device's source address in a shared spool and bounds the window. Every +line carries the drive's sequence number, so a line delivered twice is dropped, and only as +many expected lines may be missing as numbers are absent from the window. + +--mode selects the run; --duration overrides the seconds of a single soak or stress +run; --soak-duration and --stress-duration set the two phases of a both run. --profile +is kept for run-tests: stress runs the stress mode for ten minutes and soak runs the +soak mode for four hours, and --profile overrides --mode; --log defaults to off under +--profile so an unattended gate needs no collector. --seed and --no-lanes work in +every mode; --no-lanes leaves out the REST and FTP lanes so the drive's heap use can be +told from theirs. + +The caches fill during the first part of a session: in a 30 minute soak the free heap fell +by about 30 KB over the first 60 to 70 iterations, on an Ultimate 64 Elite and on a U2+L, +and then stayed flat. The soak judges its heap over the second half of the samples for +that reason, so a run shorter than about 20 minutes says little about a leak. + +The suite needs a C64 with a standard KERNAL, REST and FTP, and one Software IEC +partition numbered 1. It uses device 11, and restores the settings, the partition's +working directory, and removes its own directory. +""" +import argparse +import contextlib +import os +import random +import sys +import threading +import time +import traceback +import uuid +from pathlib import Path + +sys.path.insert(0, str(next(p for p in Path(__file__).resolve().parents + if (p / "tests" / "lib").is_dir()) / "tests" / "lib")) +import bootstrap # noqa: E402,F401 +import cli # noqa: E402 +import ftp # noqa: E402 +from api import UltimateApi # noqa: E402 +from config_snapshot import Snapshot # noqa: E402 +from report import Failure, check, detail, section, suite_fail, suite_ok, teardown_step # noqa: E402 + +sys.path.insert(0, bootstrap.directory("e2e", "io", "iec")) +from iec_agent import CLOSE, OPEN, READ_COUNT, READ_TO_EOI, STATUS_BYTES, WRITE, Agent, iec_drive # noqa: E402 + +import softiec_log # noqa: E402 + +SUITE = "softiec_soak_test" + +# The default seconds for each mode, and the two phases of a both run. +SOAK_DEFAULT_SECONDS = 30 * 60 +STRESS_DEFAULT_SECONDS = 10 * 60 +# What --profile maps to, so run-tests keeps working: the stress profile is a ten +# minute stress run and the soak profile is a four hour soak run. +PROFILE_STRESS_SECONDS = 10 * 60 +PROFILE_SOAK_SECONDS = 4 * 60 * 60 + +# The heap may move while caches fill; what is not allowed is a steady loss. The soak +# measurement starts after the warm-up iterations and allows this much per iteration. +WARMUP_ITERATIONS = 5 +LEAK_TOLERANCE_BYTES_PER_ITERATION = 256 +# The stress heap is judged before and after, measured after an idle settle rather than +# by a per-iteration slope, because a stress run allocates and frees hard and unevenly. +# The bound is loose on purpose: a first session after power-up can lose about 25 KB to +# caches that never come back (see the module docstring), and the value that matters for +# review is the reported before and after, so only a gross leak fails the run. Judge a +# tighter loss by comparing the reported numbers across runs on a warm device. +STRESS_HEAP_LOSS_TOLERANCE_BYTES = 65536 +# How long to leave the drive idle after the lanes stop before the final heap reading, +# so buffers a transfer held are given back. +IDLE_SETTLE_SECONDS = 8.0 +# The stress lanes can fill the network stack until it refuses or resets a single REST +# request, and the C64 lane reaches its agent over REST too. Before the firmware is called +# dead, or the drive called deaf to the C64, the lanes are paused and REST is asked this many +# times, this far apart. +LIVENESS_ATTEMPTS = 6 +# How long a phase waits for its end marker to reach the syslog before correlating. +LOG_FLUSH_SECONDS = 30.0 +LIVENESS_RETRY_SECONDS = 2.0 +# How long a pause of the lanes waits for their requests already on the way. +LANE_PAUSE_SECONDS = 1.0 + +REST_LANE_SECONDS = 1.5 +FTP_LANE_SECONDS = 4.0 +# How many operations the failure report names. +HISTORY = 25 +# How many recorded anomalies a phase's report quotes in full, besides counting them all. +ANOMALY_EXAMPLES = 10 + +# The Software IEC log setting, in the store it lives in (software/io/iec/iec_drive.cc). +LOG_CATEGORY = "SoftIEC Drive Settings" +LOG_ITEM = "Log Every Operation" +# The Command Interface setting, needed for the UCI target (software/io/c64/c64.cc). +CMD_IF_CATEGORY = "C64 and Cartridge Settings" +CMD_IF_ITEM = "Command Interface" +# The network setting that names the syslog destination (software/network/network_config.cc). +SYSLOG_CATEGORY = "Network Settings" +SYSLOG_ITEM = "Log to Syslog Server" + +# A toggle phase flips the log setting no more often than this, so the flash writes stay +# bounded, and no less often, so the phase spends time in each state. +LOG_FLIP_MIN_SECONDS = 10.0 +LOG_FLIP_MAX_SECONDS = 20.0 +# How long to wait for a read-back to confirm a flip before giving up on it. +LOG_CONFIRM_SECONDS = 6.0 + +# The x00 wrapped files the fixture lays down over FTP, by host name and CBM name. A P00, +# S00, U00 or R00 file carries "C64File" and a zero, its CBM name in the 16 bytes at offset +# 8, and a relative file's record length at offset 25 (SI-144). +FIXTURE_X00 = {"WRAPPED.P00": ("MY GAME", 0, 40), "TEXT.S00": ("NOTES", 0, 60), + "TOOL.U00": ("UTILITY", 0, 48), "DATA.R00": ("RECORDS", 32, 320)} +# The disk images the fixture creates in the run's directory, by name and REST creator. +FIXTURE_IMAGES = {"DISK.D64": "create_d64", "DISK.D71": "create_d71", + "DISK.D81": "create_d81", "DISK.DNP": "create_dnp"} +# How many small files the fixture writes into MANY, to read a directory to its end. +MANY_ENTRIES = 40 + + +def pattern(name, size): + """The content of a fixture file: deterministic, different for each file.""" + seed = sum(name.encode("ascii")) + return bytes(((i * 31 + seed) & 0xFF) for i in range(size)) + + +# The files C64 OS reads at boot, by the paths it uses, with their sizes from the trace. +FIXTURE = { + "OS/SETTINGS/SYSTEM.T.seq": 400, + "OS/SETTINGS/CONFIG.T.seq": 13, + "OS/SETTINGS/COMPONENTS.T.seq": 683, + "OS/LIBRARY/REDIRECT.O.prg": 18, + "OS/LIBRARY/WORKSPACE.O.prg": 373, + "OS/LIBRARY/IEC.LIB.R.prg": 624, + "OS/KERNAL/MENU.O.prg": 2209, + "OS/KERNAL/FILE.O.prg": 1338, + "OS/DRIVERS/KBD.C64.prg": 567, + "OS/TK/TKVIEW.O.prg": 1694, +} +# The applications and documents the soak loads and reads to the end, as host names. +FIXTURE_DOCUMENTS = ("OS/KERNAL/MENU.O.prg", "OS/KERNAL/FILE.O.prg", "OS/TK/TKVIEW.O.prg", + "OS/DRIVERS/KBD.C64.prg", "OS/LIBRARY/WORKSPACE.O.prg") +# WORK is the soak's scratch area, OS/TEMPORARY its throwaway files, RACE the directory +# the stress FTP lanes and the C64 fight over, PCLANE the soak FTP lane's own file, X00 the +# x00 wrapped files, MANY a directory of dozens of files read to the end, IMAGES the disk +# images of every type. +FIXTURE_DIRS = ("OS", "OS/SETTINGS", "OS/LIBRARY", "OS/KERNAL", "OS/DRIVERS", "OS/TK", + "OS/TEMPORARY", "WORK", "PCLANE", "RACE", "X00", "MANY", "IMAGES") + + +def x00_wrapper(cbm_name, record_length, body): + """A P00/S00/U00/R00 file's bytes: the 26 byte header that names it, then the data.""" + header = b"C64File\0" + cbm_name.encode("ascii").ljust(16, b"\0") + b"\0" \ + + bytes([record_length]) + return header + body + + +class Dead(Failure): + """The firmware stopped answering.""" + + +class Corruption(Failure): + """Data read back from the drive differed from what was written or stored. + + A subclass of Failure so that a soak reports it like any other failure, and a + stress run, which tolerates most failures, still fails on this one. + """ + + +class RecordingAgent: + """A wrapper around the IEC agent that turns bus operations into the log events the phase + correlates against, at the one boundary every operation crosses. Wrapping the agent + catches the operations the Session helpers do not funnel: recover(), move_drive() (which + calls self.call, so it routes through here too), the direct writes to channel 15, and an + operation cut short by a Failure. + + What the bus sees, from tests/e2e/io/iec/iec_agent.asm and the KERNAL: + + * WRITE to channel 15 (CHKOUT $FFC9, CHROUT, UNLISTEN) sends a command; the drive runs + and logs it when the write ends. The command's status is what the C64 reads next, so + a WRITE to 15 opens a pending command finished by the next READ_TO_EOI on 15: the + answer is a status line for most commands and the reply bytes for one that answers + data (M-R, G-P, T-R*), told apart by whether the bytes parse as a two-digit status. + If another operation comes first, the command is finished with status unknown. + * OPEN (SETNAM $FFBD, SETLFS $FFBA, OPEN $FFC0) with a non-empty name sends LISTEN, + the secondary with $F0, the name and UNLISTEN, which the drive opens and logs. On + secondary 15 that is a command; on any other it is an open, whose status is the next + status read. A zero-length name sends no bytes the drive parses, so it records + nothing, but a successful OPEN still enters the logical file in the KERNAL table. + * CLOSE (CLOSE $FFC3) sends nothing for a logical file that is not open, and LISTEN, + the secondary with $E0 and UNLISTEN for one that is, whether or not it was opened with + a name, which the drive logs as a close of that secondary address. So a close is + recorded only for a logical file this recorder saw opened, with the secondary address + it was opened on. Secondary 15, the command channel, does not log closes. + * READ_TO_EOI and READ_COUNT read data and log nothing. + * I (with anything after it) closes data channels 0 to 14 through the same close the bus + uses (IecCommandChannel::do_initialize_buffers) and answers 00; UJ, U: and U with a + shifted J do the same (do_reset) and answer 73. Each of those closes logs a close line + for its channel, whether or not the channel had anything open, and all of them come + before the command's own line. A later CLOSE from the C64 still logs its close. + + An operation that raises Failure may or may not have reached the drive, so it is recorded + as an optional event. Events are appended only while session.recording is on, but the + KERNAL table and the pending command are tracked throughout, so a close inside the window + knows whether the file was opened before it. + """ + + def __init__(self, agent, session): + self._agent = agent + self._session = session + self._open_files = {} # logical file number -> the secondary address it was opened on + self._pending = None # (kind, txt, dev, t0, chan) awaiting a status read + + def __getattr__(self, name): + return getattr(self._agent, name) + + @property + def softiec_device(self): + return self._agent.softiec_device + + @softiec_device.setter + def softiec_device(self, value): + self._agent.softiec_device = value + + move_drive = Agent.move_drive + + def start(self): + """Starts the agent again. Uploading it resets the C64, which empties the KERNAL's file + table, so the logical files this recorder tracked as open are gone, and a CLOSE of + one of them afterwards sends nothing on the bus.""" + self._open_files.clear() + self._pending = None + return self._agent.start() + + def _append(self, op, chan, txt, dev, status, t0, t1, reply=None, optional=False): + if not self._session.recording: + return + # U0> logs the device number it changed to, which this side cannot predict, so its + # dev is not compared (SI-100). + if bytes(txt).startswith(b"U0>"): + dev = None + self._session.log_events.append(softiec_log.Event( + op=op, chan=chan, txt=bytes(txt), status=status, reply=reply, + dev=dev, t0=t0, t1=t1, optional=optional)) + + @staticmethod + def closes_data_channels(txt, status): + """Whether a command closed data channels 0 to 14 before its own line was logged: I + answered 00, or UJ, U: or U with a shifted J answered 73. A command of 254 bytes or + more is refused before it is dispatched (32), so it closes nothing.""" + if (not txt) or (len(txt) >= 254): + return False + if (txt[0] == ord("I")) and (status == 0): + return True + return (len(txt) >= 2) and (txt[0] == ord("U")) and (txt[1] in b"J:\xca") and (status == 73) + + def _finish_pending(self, result, now): + pending = self._pending + self._pending = None + kind, txt, dev, t0, chan = pending + text = result.decode("latin-1", "replace") if result else "" + is_status = (len(text) >= 3) and text[:2].isdigit() and (text[2] == ",") + if kind == "command": + status = int(text[:2]) if is_status else 0 + reply = None if is_status else bytes(result) + if is_status and self.closes_data_channels(txt, status): + for data_channel in range(15): + self._append("close", data_channel, b"", dev, None, t0, now) + self._append("command", 15, txt, dev, status, t0, now, reply=reply) + else: + status = int(text[:2]) if is_status else None + self._append("open", chan, txt, dev, status, t0, now) + + def _flush_unknown(self, now): + pending = self._pending + self._pending = None + kind, txt, dev, t0, chan = pending + self._append(kind, 15 if kind == "command" else chan, txt, dev, None, t0, now) + + def call(self, op, channel=5, data=b"", device=11, count=None, secondary=None, expect=None): + now = time.monotonic() + is_status_read = (op == READ_TO_EOI) and (channel == 15) + if (self._pending is not None) and not is_status_read: + self._flush_unknown(now) + try: + result = self._agent.call(op, channel=channel, data=data, device=device, + count=count, secondary=secondary, expect=expect) + except Failure: + if is_status_read and (self._pending is not None): + # The command or open was sent but its status was not read; it may have logged. + kind, txt, dev, t0, chan = self._pending + self._pending = None + self._append(kind, 15 if kind == "command" else chan, txt, dev, None, t0, now, + optional=True) + elif (op == OPEN) and (len(data) > 0): + sa = channel if secondary is None else secondary + self._append("command" if sa == 15 else "open", + 15 if sa == 15 else sa, data, device, None, now, now, optional=True) + elif (op == WRITE) and (channel == 15): + self._append("command", 15, data, device, None, now, now, optional=True) + raise + if is_status_read: + if self._pending is not None: + self._finish_pending(result, now) + elif (op == WRITE) and (channel == 15) and data: + self._pending = ("command", bytes(data), device, now, 15) + elif op == OPEN: + sa = channel if secondary is None else secondary + self._open_files[channel] = sa + if len(data) > 0: + self._pending = ("command" if sa == 15 else "open", bytes(data), device, now, sa) + elif op == CLOSE: + sa = self._open_files.pop(channel, None) + if (sa is not None) and (sa != 15): + self._append("close", sa, b"", device, None, now, now) + return result + + +class Session: + """One suite run: the device, the agent, the fixture, and what happened.""" + + def __init__(self, args): + self.args = args + self.api = UltimateApi(args.host, args.password, args.timeout) + agent = Agent(self.api) + agent.verify_writes = True # the stress lanes can fill the RAM disk REST uploads use + self.agent = RecordingAgent(agent, self) + self.random = random.Random(args.seed) + self.folder = "soak" + uuid.uuid4().hex[:6] + self.here = self.folder.upper() + self.root = None + self.policy = None + self.history = [] + self.iteration = 0 + self.counts = {} + self.anomalies = {} + self.anomaly_examples = [] + self.statuses = {} + self.lane_errors = [] + self.lane_counts = {"rest": 0, "ftp": 0} + self.heap_before = None + self.heap_after = None + self.stop = threading.Event() + self.quiet = threading.Event() # set while the lanes must leave the network alone + self.device = 11 + # The log correlation. `recording` gates event capture; `log_events` is what the C64 + # lane and the UCI steps did; `flips` is when a toggle phase changed the setting. + self.recording = False + self.log_events = [] + self.flips = [] + self.flip_lock = threading.Lock() + self.log_mode = "off" + self.log_on = False + self.uci = None + # Where the device log is read from: a spool file an external collector writes, or a + # UDP socket this run binds. None when correlation is not configured. + self.syslog_source = None + + def begin_phase(self): + """Clear the per-phase tallies so a both run reports each phase on its own.""" + self.iteration = 0 + self.counts = {} + self.anomalies = {} + self.anomaly_examples = [] + self.statuses = {} + self.lane_errors = [] + self.lane_counts = {"rest": 0, "ftp": 0} + self.heap_before = None + self.heap_after = None + self.log_events = [] + self.flips = [] + + # -- the C64 lane: shared helpers ------------------------------------------------ + + def note(self, what): + self.history.append(f"{self.iteration}: {what}") + del self.history[:-HISTORY] + + def record_status(self, kind, response): + """Tally a status a fuzzed step produced, so the report can list them all.""" + code = response[:2] if response else "--" + self.statuses[code] = self.statuses.get(code, 0) + 1 + self.note(f"{kind} answered {response!r}") + + def anomaly(self, what, exc): + """Record a KERNAL or DOS error that is an allowed outcome of a hostile step.""" + self.anomalies[what] = self.anomalies.get(what, 0) + 1 + self.note(f"{what} raised {exc}") + if len(self.anomaly_examples) < ANOMALY_EXAMPLES: + self.anomaly_examples.append(f"iteration {self.iteration} ({what}): {exc}; before it: " + + " | ".join(self.history[-4:-1])) + + def emit(self, op, chan, txt, status=None, reply=None, optional=False): + """Record an event the wrapped agent cannot see because it did not cross the bus: the + UCI target's opens and closes reach the channels over the cartridge registers, not the + agent. A no-op unless a phase is recording.""" + if not self.recording: + return + now = time.monotonic() + self.log_events.append(softiec_log.Event( + op=op, chan=chan, txt=bytes(txt), status=status, reply=reply, + dev=self.device, t0=now, t1=now, optional=optional)) + + def command(self, text, allowed=None): + data = text if isinstance(text, bytes) else text.encode("latin-1") + self.note(f"command {data!r}") + self.agent.call(WRITE, 15, data) + response = self.agent.call(READ_TO_EOI, 15, expect=STATUS_BYTES).decode("latin-1").strip() + code = response[:2] + if not code.isdigit(): + raise Failure(f"{data!r} answered {response!r}, which is not a status") + if allowed is not None and int(code) not in allowed: + raise Failure(f"{data!r} answered {response!r}") + return response + + def command_reply(self, text, size): + """A command whose answer is data rather than a status line, such as G-P, T-RA and + M-R. The wrapped agent records it as a command whose reply is the bytes read here.""" + data = text if isinstance(text, bytes) else text.encode("latin-1") + self.note(f"command_reply {data!r}") + self.agent.call(WRITE, 15, data) + return self.agent.call(READ_TO_EOI, 15, expect=size) + + def status(self): + return self.agent.call(READ_TO_EOI, 15, expect=STATUS_BYTES).decode("latin-1").strip() + + def open(self, channel, name, secondary=None): + data = name if isinstance(name, bytes) else name.encode("latin-1") + self.note(f"open {channel} {data!r}") + self.agent.call(OPEN, channel=channel, data=data, secondary=secondary) + return self.status() + + def close(self, channel): + self.note(f"close {channel}") + self.agent.call(CLOSE, channel=channel) + + def read(self, channel, limit=None): + """Bytes from a channel up to its end, or at most `limit` of them.""" + out = b"" + while limit is None or len(out) < limit: + want = 254 if limit is None else min(254, limit - len(out)) + block = self.agent.call(READ_COUNT, channel, count=want) + out += block + if len(block) < want or (self.agent.last_status & 64): + break + return out + + def write_stream(self, channel, data): + """Sends data to a channel in mailbox sized pieces.""" + for start in range(0, len(data), 254): + self.agent.call(WRITE, channel, data[start:start + 254]) + + def read_file(self, channel, name): + response = self.open(channel, name) + try: + if not response.startswith("00"): + return response, None + return response, self.read(channel) + finally: + self.close(channel) + + def expect_file(self, channel, name, fixture): + response, data = self.read_file(channel, name) + if data is None: + raise Failure(f"{name} did not open: {response}") + want = pattern(fixture, FIXTURE[fixture]) + if data != want: + raise Corruption(f"{name} read {len(data)} bytes that differ from the {len(want)} stored") + + def save_and_verify(self, name, data, replace=False): + """Writes data to a new or replaced sequential file, reads it back, compares. + + Reading dominates the time: a 254 byte read costs about 0.7 s on this C64, so a + caller sizes data to keep one iteration bounded. + """ + prefix = "@:" if replace else "" + response = self.open(7, f"{prefix}{name},S,W") + if not response.startswith("00"): + raise Failure(f"{prefix}{name},S,W answered {response}") + self.write_stream(7, data) + self.close(7) + response, back = self.read_file(8, f"{name},S") + if back != data: + raise Corruption(f"{name} saved {len(data)} bytes and read back " + f"{len(back or b'')} that differ ({response})") + + def partition(self): + self.command(bytes([ord("C"), 0xD0, 1]), allowed=(2,)) + + def boot(self): + """The order of operations C64 OS follows at boot, from the #877 trace. + + Run once as the session start, and again as an occasional reboot. + """ + here = self.here + self.partition() + self.command(f"CD//{here}/OS\r", allowed=(0,)) + for low, high in ((0xA4, 0xFE), (0xC5, 0xE5), (0xE8, 0xA6), (0x02, 0x00)): + reply = self.command_reply(bytes([ord("M"), ord("-"), ord("R"), low, high, 2]), 2) + self.note(f"M-R answered {reply!r}") + if reply != bytes(2): + raise Corruption(f"M-R ${high:02x}{low:02x},2 answered {reply!r}, expected two zeros") + self.command("UI", allowed=(73,)) + self.command("S/TEMPORARY/:*", allowed=(1,)) + self.open(3, "$", secondary=0) + self.read(3, limit=5) + self.close(3) + held = self.open(2, "/SETTINGS/:SYSTEM.T") + if not held.startswith("00"): + raise Failure(f"/SETTINGS/:SYSTEM.T did not open: {held}") + first = self.read(2, limit=40) + for name, fixture in (("/LIBRARY/:WORKSPACE.O", "OS/LIBRARY/WORKSPACE.O.prg"), + ("/LIBRARY/:IEC.LIB.R", "OS/LIBRARY/IEC.LIB.R.prg"), + ("/KERNAL/:MENU.O", "OS/KERNAL/MENU.O.prg")): + self.open(4, name) + header = self.read(4, limit=2) + self.close(4) + if header != pattern(fixture, 2): + raise Corruption(f"the first two bytes of {name} read {header!r}") + self.expect_file(5, name, fixture) + missing = self.open(6, "/TEMPORARY/:UPDATER") + self.close(6) + if not missing.startswith("62"): + raise Failure(f"a file that is not there answered {missing}") + self.expect_file(14, "/SETTINGS/:CONFIG.T", "OS/SETTINGS/CONFIG.T.seq") + self.command(bytes([ord("C"), 0xD0, 1]), allowed=(2,)) + self.command(f"CD//{here}/OS/DRIVERS/", allowed=(0,)) + self.expect_file(5, "KBD.C64", "OS/DRIVERS/KBD.C64.prg") + self.command(f"CD//{here}/OS/SETTINGS/", allowed=(0,)) + self.open(3, "$:CONFIG*", secondary=0) + listing = self.read(3) + self.close(3) + self.command(f"CD//{here}/OS", allowed=(0,)) + if b"CONFIG.T" not in listing: + raise Failure(f"$:CONFIG* in SETTINGS did not list CONFIG.T: {listing!r}") + rest = self.read(2) + self.close(2) + if first + rest != pattern("OS/SETTINGS/SYSTEM.T.seq", 400): + raise Corruption("the settings file held open during the boot read back changed") + + # -- the C64 lane: soak operations ----------------------------------------------- + + def load_document(self): + """Loads an application or document and reads it to the end, as a launch or a + file open does, and checks it reads back byte for byte.""" + self.partition() + fixture = self.random.choice(FIXTURE_DOCUMENTS) + directory, _, base = fixture.rpartition("/") + cbm_name = base.rsplit(".", 1)[0] # the CBM name; the .prg extension is cut + self.command(f"CD//{self.here}/{directory}/", allowed=(0,)) + self.expect_file(5, cbm_name, fixture) + + def poll_status(self): + """Reads the status channel, and sometimes the clock and the partition info, as + a program does between actions to see the drive is well. The clock is read in each + of its four forms, and G-P is read with no byte and with a partition byte, so every + RTC and partition-info path is covered over a run.""" + self.status() + if self.random.randrange(2): + clock = self.random.choice([b"T-RA", b"T-RI", b"T-RB", b"T-RD"]) + self.note(f"{clock!r} answered {self.command_reply(clock, 40)!r}") + pick = self.random.randrange(4) + if pick == 0: + self.note(f"G-P answered {self.command_reply(b'G-P', 40)!r}") + elif pick == 1: + # G-P with a partition byte, with 255 (the current partition), and with 0 (the + # system partition, which this drive does not have and answers type 0). + byte = self.random.choice([1, 255, 0]) + self.note(f"G-P {byte} answered {self.command_reply(b'G-P' + bytes([byte]), 40)!r}") + + def settings_write(self, replace=True): + """Saves a small settings file, the way a session writes its preferences, and + reads it back to check it.""" + self.partition() + self.command(f"CD//{self.here}/OS/SETTINGS/", allowed=(0,)) + size = self.random.randrange(20, 400) + data = bytes(self.random.randrange(256) for _ in range(size)) + self.save_and_verify(f"PREFS{self.random.randrange(3)}.T", data, replace=replace) + + def temporary_files(self): + """Creates a few temporary files in OS/TEMPORARY and scratches them, as a session + does with working files it does not keep.""" + self.partition() + self.command(f"CD//{self.here}/OS/TEMPORARY/", allowed=(0,)) + made = [] + for _ in range(self.random.randrange(1, 4)): + name = f"T{self.random.randrange(6)}" + size = self.random.randrange(1, 300) + response = self.open(7, f"@:{name},S,W") + if response.startswith("00"): + self.write_stream(7, bytes(self.random.randrange(256) for _ in range(size))) + made.append(name) + self.close(7) + for name in made: + self.command(f"S:{name}", allowed=(1,)) + + def save_and_scratch(self): + """Saves a working file, reads it back and compares, and scratches it now and + then, as a session does with a document it saves.""" + size = self.random.randrange(1, 1500) + name = f"F{self.random.randrange(4)}" + data = bytes(self.random.randrange(256) for _ in range(size)) + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + self.save_and_verify(name, data, replace=True) + if self.random.randrange(3) == 0: + self.command(f"S:{name}", allowed=(1,)) + + def relative(self): + length = self.random.randrange(2, 120) + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + name = f"R{length}" + self.command(f"S:{name}", allowed=(1,)) + self.open(9, name.encode("ascii") + b",L," + bytes([length])) + records = {} + for _ in range(self.random.randrange(1, 5)): + record = self.random.randrange(1, 40) + payload = bytes(self.random.randrange(1, 256) for _ in range(self.random.randrange(1, length))) + self.command(bytes([ord("P"), 0x60 | 9, record & 0xFF, record >> 8, 1]), allowed=(0, 50)) + self.agent.call(WRITE, 9, payload) + records[record] = payload + for record, payload in records.items(): + self.command(bytes([ord("P"), 0x60 | 9, record & 0xFF, record >> 8, 1]), allowed=(0,)) + back = self.read(9, limit=length) + if back[:len(payload)] != payload: + raise Corruption(f"record {record} of {name} read {back!r}, wrote {payload!r}") + self.close(9) + + def direct_access(self): + self.partition() + self.command(f"CD//{self.here}/DISK.D64", allowed=(0,)) + self.open(10, "#") + data = bytes(self.random.randrange(256) for _ in range(256)) + sector = self.random.randrange(0, 21) + self.command("B-P 10 0", allowed=(0,)) + self.agent.call(WRITE, 10, data[:254]) + self.agent.call(WRITE, 10, data[254:]) + self.command(f"U2:10,0,1,{sector}", allowed=(0,)) + self.command(f"U1:10,0,1,{sector}", allowed=(0,)) + self.command("B-P 10 0", allowed=(0,)) + back = self.read(10, limit=256) + self.close(10) + self.command(f"CD//{self.here}", allowed=(0,)) + if back != data: + raise Corruption(f"sector 1/{sector} read back differs after U2 and U1") + + def directories(self): + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + name = f"D{self.random.randrange(3)}" + self.command(f"MD:{name}", allowed=(0, 63)) + self.command(f"CD:{name}", allowed=(0,)) + self.command("CD_", allowed=(0,)) + self.command(f"C:COPY=//{self.here}/OS/SETTINGS/:CONFIG.T", allowed=(0, 62, 63)) + self.command("R:MOVED=COPY", allowed=(0, 62, 63)) + self.command("S:MOVED", allowed=(1,)) + self.command(f"RD:{name}", allowed=(0, 62)) + + def listings(self): + """Directory listings of several kinds, some read whole and some abandoned part + way, the way a session browses.""" + self.partition() + name = self.random.choice([f"$//{self.here}/OS/", "$=P", f"$//{self.here}/:*=S", + f"$//{self.here}/OS/KERNAL/:*=L", "$//", f"$//{self.here}/NOSUCH/"]) + secondary = 0 if self.random.randrange(4) else 3 + response = self.open(11, name, secondary=secondary) + if response.startswith("00"): + self.read(11, limit=None if self.random.randrange(2) else self.random.randrange(1, 60)) + self.close(11) + + def other_commands(self): + # The commands a session sends now and then, and the ones a person tries by mistake. + # XPWD answers the working directory as data; I and UJ close channels; the rest are + # the deliberately-unimplemented forms of section 18.1 (V is 31, E and X other than + # XPWD are 30, S-8/S-9/S-D are 31, T-W is 30). + for text, allowed in (("I", (0,)), ("I0", (0,)), ("UJ", (73,)), ("U9", (73,)), + ("UI+", (0,)), ("UI-", (0,)), ("Z9", (31,)), ("E", (30,)), + ("XYZ", (30,)), ("V", (31,)), ("S-8", (31,)), ("T-W", (30,))): + if self.random.randrange(2): + continue + self.command(text, allowed=allowed) + if self.random.randrange(2): + where = self.command_reply(b"XPWD\r", 40).decode("latin-1").strip() + self.note(f"XPWD answered {where!r}") + if not where.startswith("1:"): + raise Failure(f"XPWD in partition 1 answered {where!r}") + + def secondaries(self): + """A PRG LOAD on secondary 0 and a PRG SAVE on secondary 1, the KERNAL's own + defaults: secondary 0 with no mode reads a PRG, secondary 1 with no mode writes one. + The saved file is read back on secondary 0 and compared.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + fixture = self.random.choice(FIXTURE_DOCUMENTS) + cbm = fixture.rpartition("/")[2].rsplit(".", 1)[0] + directory = fixture.rpartition("/")[0] + self.command(f"CD//{self.here}/{directory}/", allowed=(0,)) + response = self.open(5, cbm, secondary=0) + loaded = self.read(5) if response.startswith("00") else None + self.close(5) + if loaded != pattern(fixture, FIXTURE[fixture]): + raise Corruption(f"a LOAD of {cbm} on secondary 0 read {len(loaded or b'')} bytes") + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + data = bytes(self.random.randrange(256) for _ in range(self.random.randrange(2, 300))) + name = f"SAVED{self.random.randrange(3)}" + response = self.open(6, f"@0:{name}", secondary=1) + if not response.startswith("00"): + raise Failure(f"a SAVE of {name} on secondary 1 answered {response}") + self.write_stream(6, data) + self.close(6) + response, back = self.read_file(8, name) + if back != data: + raise Corruption(f"{name} saved on secondary 1 read back {len(back or b'')} bytes ({response})") + + def usr_append(self): + """A USR file written and read back, and an append that lands after existing data.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + name = f"U{self.random.randrange(3)}" + head = bytes(self.random.randrange(256) for _ in range(self.random.randrange(2, 120))) + tail = bytes(self.random.randrange(256) for _ in range(self.random.randrange(2, 120))) + response = self.open(7, f"@:{name},U,W") + if not response.startswith("00"): + raise Failure(f"{name},U,W answered {response}") + self.write_stream(7, head) + self.close(7) + response = self.open(7, f"{name},U,A") + if response.startswith("00"): + self.write_stream(7, tail) + self.close(7) + response, back = self.read_file(8, f"{name},U") + if back != head + tail: + raise Corruption(f"{name},U after an append read {len(back or b'')} bytes, " + f"expected {len(head + tail)} ({response})") + + def x00_files(self): + """Reads an x00 wrapped fixture by the CBM name in its header and checks the data, + and now and then makes a throwaway wrapper, renames it through the drive and scratches + it, which is how the drive's rename rewrites the header and its scratch removes it.""" + self.partition() + self.command(f"CD//{self.here}/X00/", allowed=(0,)) + host, (cbm, record_length, size) = self.random.choice(list(FIXTURE_X00.items())) + body = pattern(host, size) + if record_length == 0: + response, data = self.read_file(5, cbm) + if data != body: + raise Corruption(f"the x00 file {host} read {len(data or b'')} bytes as {cbm} ({response})") + if self.random.randrange(3) == 0: + throwaway = f"TMP{self.random.randrange(4)}" + payload = bytes(self.random.randrange(256) for _ in range(self.random.randrange(2, 80))) + with ftp.session(self.args.host, self.args.password) as client: + target = f"{self.root.rstrip('/')}/{self.folder}/X00/{throwaway}.S00" + ftp.store(client, target, x00_wrapper(throwaway, 0, payload)) + response, data = self.read_file(5, throwaway) + if data != payload: + raise Corruption(f"the throwaway wrapper {throwaway} read {len(data or b'')} bytes") + renamed = f"{throwaway}X" + self.command(f"R:{renamed}={throwaway}", allowed=(0, 62)) + self.command(f"S:{renamed}", allowed=(1,)) + + def images(self): + """Enters a D71, D81 or DNP image, lists it, saves a file inside it and reads it back, + makes and enters a subdirectory in the DNP image, and reads a sector by direct access + at the image's own geometry, then leaves the image.""" + self.partition() + host = self.random.choice(["DISK.D71", "DISK.D81", "DISK.DNP"]) + self.command(f"CD//{self.here}/IMAGES/{host}", allowed=(0,)) + self.open(11, "$", secondary=0) + self.read(11) + self.close(11) + name = f"IN{self.random.randrange(3)}" + data = bytes(self.random.randrange(256) for _ in range(self.random.randrange(2, 200))) + self.save_and_verify(name, data, replace=True) + if host == "DISK.DNP": + sub = f"SUB{self.random.randrange(3)}" + self.command(f"MD:{sub}", allowed=(0, 63)) + self.command(f"CD:{sub}", allowed=(0,)) + self.save_and_verify(f"DEEP{self.random.randrange(2)}", + bytes(self.random.randrange(256) for _ in range(20)), replace=True) + self.command("CD_", allowed=(0,)) + else: + # A direct-access read at a track only this image type has: track 40 on a D71 + # (70 tracks), track 40 sector 30 on a D81 (80 tracks of 40 sectors). + track, sector = (40, 5) if host == "DISK.D71" else (40, 30) + self.open(10, "#") + if self.command(f"U1:10,0,{track},{sector}", allowed=(0, 66)).startswith("00"): + self.read(10, limit=256) + self.close(10) + self.command(f"CD//{self.here}", allowed=(0,)) + + def many_entries(self): + """Reads a directory of dozens of files to its end, which walks the listing across + many blocks and produces the listing-end log line.""" + self.partition() + response = self.open(11, f"$//{self.here}/MANY/", secondary=0) + if response.startswith("00"): + listing = self.read(11) + quotes = listing.count(b"\"") + if quotes < 2 * MANY_ENTRIES: + raise Failure(f"the many-entry listing held {quotes} quotes, " + f"expected at least {2 * MANY_ENTRIES}") + self.close(11) + + def uci_between(self): + """The UCI SoftIEC target, reached between bus operations over the cartridge + registers. Skipped with a reason where the command interface is not present.""" + if self.uci is None: + return + with self.lanes_paused(): + self.uci.exercise(self) + + # -- the C64 lane: stress operations --------------------------------------------- + # + # These push the interface as hard as the agent allows. Any DOS or KERNAL error is an + # allowed outcome of the edge being tested, so they raise Failure freely; the run loop + # records that as an anomaly rather than a failure. Only a data mismatch of a file the + # step owns raises Corruption, which is a real failure. + + def fuzz(self, data): + """Sends raw bytes to the command channel and reads the status. Records the + answer. Fails only if the answer is not a two-digit status, which would mean the + drive lost the shape of a DOS reply.""" + data = data if isinstance(data, bytes) else data.encode("latin-1") + self.note(f"fuzz command {data!r}") + self.agent.call(WRITE, 15, data) + response = self.agent.call(READ_TO_EOI, 15, expect=STATUS_BYTES).decode("latin-1").strip() + if not response[:2].isdigit(): + raise Failure(f"{data!r} answered {response!r}, which is not a status") + self.record_status("command", response) + return response + + def fuzz_command(self): + """Sends a command a well-behaved program would not: random bytes after a command + letter, a command that fills the buffer, binary parameters including 13 and 0, a + lone carriage return, a carriage return and line feed ending, and unknown letters. + Runs in WORK so an accidentally valid destructive command hits disposable files + rather than the read-only fixtures under OS.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + letters = b"BCGINPRSTUXELMW?$@" + kind = self.random.randrange(6) + if kind == 0: + # A command of 250 to 254 bytes. The command buffer holds 254, so a command of + # 254 or more answers 32 and is not executed (cbmdos_parser execute_command). + # The mailbox carries at most 254 bytes, so 255 cannot be sent from here. + length = self.random.randrange(250, 255) + data = bytes([self.random.choice(letters)]) + \ + bytes(self.random.randrange(1, 256) for _ in range(length - 1)) + elif kind == 1: + data = b"\r" # a lone carriage return: the ROM answers 31 + elif kind == 2: + letter = bytes([self.random.choice(b"BUPMR")]) + data = letter + bytes(self.random.choice([0, 13, 32, 255, self.random.randrange(256)]) + for _ in range(self.random.randrange(1, 6))) + elif kind == 3: + data = bytes([self.random.choice(letters)]) + \ + bytes(self.random.randrange(256) for _ in range(self.random.randrange(0, 20))) + b"\r\n" + elif kind == 4: + data = bytes([self.random.choice(b"ABDEFGHKQWYZ")]) + \ + bytes(self.random.randrange(65, 91) for _ in range(self.random.randrange(0, 8))) + else: + data = bytes(self.random.randrange(1, 256) for _ in range(self.random.randrange(1, 40))) + self.fuzz(data) + + def fuzz_open(self): + """Opens a channel under a name a program would not send: random PETSCII, a type + or mode suffix, wildcards, doubled and single slashes, and names of 16, 17, 40 and + 250 bytes. A name of 254 bytes or more answers 32 and opens nothing. The mailbox + holds 254 bytes, so 255 or more cannot be sent from here.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + kind = self.random.randrange(7) + if kind == 0: + name = bytes(self.random.randrange(1, 256) for _ in range(self.random.choice([16, 17, 40]))) + elif kind == 1: + body = "".join(chr(self.random.randrange(65, 91)) for _ in range(self.random.randrange(1, 20))) + name = f"@:{body}," + self.random.choice("PSUL") + "," + self.random.choice("RWA") + elif kind == 2: + name = self.random.choice(["$", "$:*", "$=P", "#", "#2", ":", ",", "*", "??", "@"]) + elif kind == 3: + name = f"//{self.here}//OS//KERNAL//:MENU.O" + elif kind == 4: + name = "A" * self.random.choice([250, 253, 254]) # 254 answers 32 + elif kind == 5: + name = self.random.choice(["ABC:DEF", "1:X", "9//:Y", "OS/:*=S"]) + else: + name = bytes([self.random.randrange(0xA0, 0x100)]) + \ + bytes(self.random.randrange(1, 256) for _ in range(self.random.randrange(0, 16))) + channel = self.random.choice([2, 3, 4, 5, 6]) + secondary = 0 if self.random.randrange(3) == 0 else None + response = self.open(channel, name, secondary=secondary) + if response and not response[:2].isdigit(): + raise Failure(f"open {name!r} answered {response!r}") + self.record_status("open", response) + if response.startswith("00"): + self.read(channel, limit=self.random.choice([5, 254, None])) + self.close(channel) + + def many_channels(self): + """Opens as many channels as the KERNAL table allows (it holds ten logical files, + and this agent uses the channel number as the logical file number and the secondary + address, so the command channel leaves nine), reads across them, some abandoned, + writes to a channel opened for reading, closes a channel never opened, and reopens + an open one. Every channel it touched is closed at the end.""" + self.partition() + self.command(f"CD//{self.here}/OS", allowed=(0,)) + names = ["/KERNAL/:MENU.O", "/KERNAL/:FILE.O", "/TK/:TKVIEW.O", + "/DRIVERS/:KBD.C64", "/LIBRARY/:WORKSPACE.O"] + attempted = [] + opened = [] + for channel in range(2, 11): + try: + response = self.open(channel, self.random.choice(names)) + except Failure: + break # the KERNAL refused another open + attempted.append(channel) + if response.startswith("00"): + opened.append(channel) + for channel in opened: + self.read(channel, limit=self.random.choice([2, 40, 254])) + if opened: + try: + self.agent.call(WRITE, self.random.choice(opened), b"junk") # write to a read channel + except Failure as exc: + self.anomaly("write to read channel", exc) + self.close(12) # a channel that was never opened logs nothing, and records none + try: + self.open(opened[0], self.random.choice(names)) # reopen an open channel + except Failure as exc: + self.anomaly("reopen open channel", exc) + for channel in attempted: + self.close(channel) + + def abandoned_transfers(self): + """Starts a read or a listing and closes it after a few bytes, the way a program + that only needs a file's start does. The directory a listing left open must be + released (close_file in the firmware does that).""" + self.partition() + if self.random.randrange(2): + self.command(f"CD//{self.here}/OS/KERNAL", allowed=(0,)) + response = self.open(5, self.random.choice(["MENU.O", "FILE.O"])) + if response.startswith("00"): + self.read(5, limit=self.random.randrange(1, 10)) + self.close(5) + else: + name = self.random.choice([f"$//{self.here}/OS/", "$=P", "$//"]) + response = self.open(11, name, secondary=0) + if response.startswith("00"): + self.read(11, limit=self.random.randrange(1, 20)) + self.close(11) + + def large_file(self): + """Saves a file of several kilobytes and reads it back byte for byte. A 254 byte + read costs about 0.7 s on this C64, so a 30 KB file would be about two minutes of + bus time; the size is capped near 8 KB to keep one iteration under about 30 s + while still crossing many blocks.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + size = self.random.randrange(4000, 8001) + data = bytes(self.random.randrange(256) for _ in range(size)) + self.save_and_verify(f"BIG{self.random.randrange(2)}", data, replace=True) + + def relative_edges(self): + """A relative file at the edges of the record layout: record length 1 and 254, and a + position command to record 0, to a high record and to record 65535, which pushes + seek_record and its file growth. The record number is kept moderate for the payload + it verifies so the firmware does not spend long filling a huge gap with empty + records; record 65535 is only positioned to, and 0, 50, 51 or 72 is allowed there.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + length = self.random.choice([1, 200, 254]) + name = f"RB{length}" + self.command(f"S:{name}", allowed=(0, 1)) + try: + self.open(9, name.encode("ascii") + b",L," + bytes([length])) + # Record 0 is treated as record 1 by the firmware; record 65535 is the top of the + # 16 bit record number, and growing the file that far fills a RAM disk partition, + # which answers 72. + for edge in (0, 65535): + self.command(bytes([ord("P"), 0x60 | 9, edge & 0xFF, edge >> 8, 1]), + allowed=(0, 50, 51, 72)) + record = self.random.choice([80, 160, 250]) + payload = bytes(self.random.randrange(1, 256) for _ in range(self.random.randrange(1, length + 1))) + self.command(bytes([ord("P"), 0x60 | 9, record & 0xFF, record >> 8, 1]), allowed=(0, 50)) + self.agent.call(WRITE, 9, payload) + self.command(bytes([ord("P"), 0x60 | 9, record & 0xFF, record >> 8, 1]), allowed=(0, 50)) + back = self.read(9, limit=length) + finally: + # The file grown towards record 65535 is scratched whatever happened, so a full + # medium does not outlast this step and starve the lanes of the phases after it. + self.close(9) + self.command(f"S:{name}", allowed=(0, 1)) + if back[:len(payload)] != payload: + raise Corruption(f"record {record} of {name} read {back!r}, wrote {payload!r}") + + def buffer_exhaustion(self): + """Opens direct-access buffers until the KERNAL table is full, and sends a block + command to a channel that was never opened with # (70 NO CHANNEL). Every channel it + opened is closed.""" + self.partition() + self.command(f"CD//{self.here}/DISK.D64", allowed=(0,)) + opened = [] + for channel in range(2, 11): + try: + response = self.open(channel, "#") + except Failure: + break + if response.startswith("00"): + opened.append(channel) + else: + self.record_status("buffer open", response) + self.close(channel) + # A block command naming a channel that is not a buffer answers 70. + self.record_status("block on non-buffer", self.command("U1:13,0,18,0", allowed=range(100))) + for channel in opened: + self.close(channel) + self.command(f"CD//{self.here}", allowed=(0,)) + + def locked_files(self): + """Locks a file, checks a scratch refuses it and it lists with the lock marker, + unlocks it and scratches it, and locks a directory so a remove refuses it. All in a + throwaway directory the teardown removes.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + name = f"LK{self.random.randrange(4)}" + response = self.open(7, f"@:{name},S,W") + if response.startswith("00"): + self.write_stream(7, bytes(self.random.randrange(256) for _ in range(20))) + self.close(7) + self.command(f"L:{name}", allowed=(0, 62)) + # A locked file is not scratched: the count is zero. + locked = self.command(f"S:{name}", allowed=(1,)) + self.record_status("scratch locked", locked) + self.command(f"L:{name}", allowed=(0, 62)) # unlock + self.command(f"S:{name}", allowed=(1,)) + + def copy_sources(self): + """A copy that concatenates up to eight sources, some of which do not exist, and a + copy whose destination already exists (63) and whose destination is a wildcard (33). + The concatenation's own bytes are verified when every source was present.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + made = [] + parts = [] + for i in range(self.random.randrange(2, 6)): + src = f"SRC{i}" + body = bytes([65 + i]) * self.random.randrange(1, 30) + response = self.open(7, f"@:{src},S,W") + if response.startswith("00"): + self.write_stream(7, body) + made.append(src) + parts.append(body) + self.close(7) + dest = f"CAT{self.random.randrange(3)}" + self.command(f"S:{dest}", allowed=(1,)) # clear a previous run's destination + sources = ",".join(made + [f"NONE{self.random.randrange(9)}"] * self.random.randrange(0, 2)) + expected = b"".join(parts) + answer = self.command(f"C:{dest}={sources},S", allowed=range(100)) + self.record_status("copy sources", answer) + if answer.startswith("00") and made and "NONE" not in sources: + response, back = self.read_file(8, f"{dest},S") + if back != expected: + raise Corruption(f"a copy of {sources} read back {len(back or b'')} bytes, " + f"expected {len(expected)} ({response})") + # A destination that already exists and a wildcard destination. + self.record_status("copy exists", self.command(f"C:{dest}={made[0] if made else 'SRC0'}", + allowed=range(100))) + self.record_status("copy wildcard dest", self.command(f"C:D*={made[0] if made else 'SRC0'}", + allowed=(33,))) + self.command(f"S:{dest}", allowed=(1,)) + + def format_images(self): + """N creates or formats an image of each type in a throwaway directory, and N inside a + mounted image is refused (30). The created image is scratched again, because a D81 + takes 800 KB of a RAM disk partition.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + name = f"NEW{self.random.randrange(4)}" + spec = self.random.choice([(f"N:{name}.D64,AA", (0, 63, 72)), + (f"N:{name}.D71,AB", (0, 63, 72)), + (f"N:{name}.D81,AC", (0, 63, 72)), + (f"N:{name}.DNP,002", (0, 63, 72)), + (f"N:{name}", (0, 63, 72)), # no extension gets .D64 + (f"N:{name}.D64", (30,)), # a new image needs an id + ("NNOCOLON,AA", (34,))]) + self.record_status("format", self.command(spec[0], allowed=spec[1])) + self.command(f"S:{name}*", allowed=(0, 1)) + # N inside a mounted image is refused rather than making an image in the image. + self.command(f"CD//{self.here}/DISK.D64", allowed=(0,)) + self.record_status("format in image", self.command("N:INNER,01", allowed=(30,))) + self.command(f"CD//{self.here}", allowed=(0,)) + + def mount_churn(self): + """Enters one image after another, more than the mount cache holds, while a listing + of the first is still open, which is the eviction the firmware fixed. The extra + images are created here and left for the teardown.""" + self.partition() + images = [] + with ftp.session(self.args.host, self.args.password) as client: + base = f"{self.root.rstrip('/')}/{self.folder}/IMAGES" + for i in range(10): + name = f"CH{i}.D64" + if not ftp.quietly(lambda: client.size(f"{base}/{name}")): + self.api.files.create_d64(f"{base}/{name}", diskname=f"CHURN{i}") + images.append(name) + # Hold a listing of the first image open, then walk through the rest. + self.command(f"CD//{self.here}/IMAGES/{images[0]}", allowed=(0,)) + held = self.open(11, "$", secondary=0) + if held.startswith("00"): + self.read(11, limit=self.random.choice([10, 20])) + for name in images[1:]: + self.command(f"CD//{self.here}/IMAGES/{name}", allowed=(0, 71)) + self.open(5, "$", secondary=0) + self.read(5, limit=10) + self.close(5) + self.close(11) + self.command(f"CD//{self.here}", allowed=(0,)) + + def uci_stress(self): + """The UCI target interleaved with the bus channels, which takes the drive lock while + a bus channel may be open (CR-6). Skipped where the command interface is absent.""" + if self.uci is None: + return + with self.lanes_paused(): + self.uci.exercise(self, hostile=True) + + def direct_access_edges(self): + """Direct access to a D64 at the edges of its geometry and past them: B-P, U1, U2, + B-A and B-F at track and sector numbers that are valid, at the last valid ones, and + at illegal ones. Any two-digit status is accepted; an illegal track or sector + answers 66 in the firmware, but that is recorded rather than asserted.""" + self.partition() + self.command(f"CD//{self.here}/DISK.D64", allowed=(0,)) + self.open(10, "#") + data = bytes(self.random.randrange(256) for _ in range(256)) + track = self.random.choice([1, 18, 35, 36, 40, 0]) + sector = self.random.choice([0, 20, 21, 255]) + self.command("B-P 10 0", allowed=(0,)) + self.agent.call(WRITE, 10, data[:254]) + self.agent.call(WRITE, 10, data[254:]) + for cmd in (f"U2:10,0,{track},{sector}", f"U1:10,0,{track},{sector}", + f"B-A:0,{track},{sector}", f"B-F:0,{track},{sector}"): + self.record_status("block", self.command(cmd, allowed=range(100))) + self.command("B-P 10 0", allowed=(0,)) + self.read(10, limit=self.random.choice([16, 256])) + self.close(10) + self.command(f"CD//{self.here}", allowed=(0,)) + + def scratch_storm(self): + """Fills a directory, scratches it with wide patterns, and nests directories deep. + A non-empty directory refuses removal (63), so the throwaway directory is left for + the teardown to remove with the rest of the run's tree.""" + self.partition() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + storm = f"ST{self.random.randrange(6)}" + self.command(f"MD:{storm}", allowed=(0, 63)) + self.command(f"CD:{storm}", allowed=(0,)) + for i in range(self.random.randrange(4, 10)): + response = self.open(7, f"@:F{i},S,W") + if response.startswith("00"): + self.write_stream(7, bytes([i]) * self.random.randrange(1, 40)) + self.close(7) + self.command(self.random.choice(["S:*", "S:F*", "S:*,*,*", "S:F?"]), allowed=(1,)) + if self.random.randrange(2): + # Nest directories and change into each, so the working directory grows deep. + for level in range(self.random.randrange(3, 8)): + self.command(f"MD:N{level}", allowed=(0, 63)) + self.command(f"CD:N{level}", allowed=(0,)) + self.status() + self.command(f"CD//{self.here}/WORK/", allowed=(0,)) + self.command(f"RD:{storm}", allowed=(0, 62, 63)) + + def race_file(self): + """Reads and writes a file in the RACE directory that the FTP lanes create, + overwrite and delete at the same time, or lists a subdirectory the FTP lanes remove + and create again while the drive is in it. A DOS error here is an expected outcome + of the race, not a failure, and the content is not owned by the C64, so it is not + compared.""" + self.partition() + self.command(f"CD//{self.here}/RACE/", allowed=(0,)) + if self.random.randrange(3) == 0: + self.command(f"CD:SUB{self.random.randrange(3)}", allowed=range(100)) + response = self.open(11, "$", secondary=0) + if response.startswith("00"): + self.read(11, limit=self.random.choice([10, None])) + self.close(11) + self.command(f"CD//{self.here}/RACE/", allowed=(0,)) + return + name = f"C{self.random.randrange(3)}" + if self.random.randrange(2): + size = self.random.randrange(1, 500) + response = self.open(7, f"@:{name},S,W") + if response.startswith("00"): + self.write_stream(7, bytes(self.random.randrange(256) for _ in range(size))) + self.close(7) + else: + response = self.open(5, name) + if response.startswith("00"): + self.read(5, limit=self.random.choice([5, 254, None])) + self.close(5) + + def resets_with_open_channels(self): + """UJ, U and shifted J, and I sent while a data channel is open. None may + reconfigure the bus (SI-103); all close the open data channels, so the KERNAL side + is closed here afterwards.""" + self.partition() + self.command(f"CD//{self.here}/OS/KERNAL", allowed=(0,)) + try: + self.open(5, "MENU.O") + except Failure as exc: + self.anomaly("open before reset", exc) + self.command(self.random.choice(["UJ", "I", "I0"]), allowed=(0, 73)) + self.fuzz(bytes([ord("U"), 0xCA])) # U and shifted J, CHR$(202) + self.close(5) + + def device_number(self): + """U0> moves the drive to another device number and back (SI-100). The agent's + move_drive follows the drive list rather than addressing a device that may not be + there, and the move back always runs, because every later step addresses 11.""" + other = self.random.choice([12, 13, 30]) + try: + moved = self.agent.move_drive(other) + self.note(f"U0> to {other}: the drive list reports {moved}") + if moved == other: + self.record_status("status on the new number", + self.agent.call(READ_TO_EOI, 15, device=other, + expect=STATUS_BYTES).decode("latin-1").strip()) + finally: + self.agent.move_drive(11) + self.status() + + SOAK_OPERATIONS = (("browse", listings, 6), ("load", load_document, 5), + ("poll", poll_status, 3), ("save", save_and_scratch, 2), + ("settings", settings_write, 2), ("temporary", temporary_files, 2), + ("secondaries", secondaries, 2), ("usr append", usr_append, 2), + ("x00", x00_files, 2), ("images", images, 2), + ("many entries", many_entries, 1), ("uci", uci_between, 2), + ("relative", relative, 1), ("direct access", direct_access, 1), + ("directories", directories, 1), ("other commands", other_commands, 1), + ("reboot", boot, 1)) + + STRESS_OPERATIONS = (("fuzz command", fuzz_command, 4), ("fuzz open", fuzz_open, 3), + ("many channels", many_channels, 2), ("abandoned", abandoned_transfers, 2), + ("direct access edges", direct_access_edges, 2), ("scratch storm", scratch_storm, 2), + ("race file", race_file, 2), ("large file", large_file, 1), + ("relative edges", relative_edges, 1), ("resets", resets_with_open_channels, 1), + ("device number", device_number, 1), ("buffer exhaustion", buffer_exhaustion, 2), + ("locked files", locked_files, 2), ("copy sources", copy_sources, 2), + ("format images", format_images, 1), ("mount churn", mount_churn, 1), + ("uci stress", uci_stress, 2)) + + # -- the per-step stress oracle -------------------------------------------------- + + def checkpoint(self): + """After a hostile step: check the drive still answers a plain status read, and, on + every third step, that a small read-only fixture still reads back byte for byte. A + drive that has stopped answering the C64 while REST still answers is dead; a fixture + that reads back changed is corruption. The read-only fixture is under OS, which no + lane touches, so a difference there is the drive's own doing.""" + try: + self.status() + except Failure: + try: + self.recover_quietly() + self.status() + except Failure as exc: + if self.alive(): + raise Dead(f"the drive stopped answering a status read after iteration " + f"{self.iteration} while REST answers: {exc}") from exc + raise + if self.iteration % 3 == 0: + try: + self.close(6) + self.partition() + self.expect_file(6, f"//{self.here}/OS/SETTINGS/:CONFIG.T", "OS/SETTINGS/CONFIG.T.seq") + except Corruption: + raise + except Failure as exc: + self.anomaly("checkpoint fixture", exc) + + # -- the PC lanes ---------------------------------------------------------------- + + def flip_log(self, api, on): + """Change Log Every Operation and wait for a read-back to confirm it, recording when + the change was requested and when it took, so a toggle phase can say which setting was + in force while each operation ran. Changing this setting alone does not reconfigure + the IEC processor, so it does not drop a transfer (Suite11-OperationLogNoReconfigure).""" + requested = time.monotonic() + api.configs.set(LOG_CATEGORY, LOG_ITEM, "Enabled" if on else "Disabled") + want = "Enabled" if on else "Disabled" + deadline = time.monotonic() + LOG_CONFIRM_SECONDS + confirmed = None + while time.monotonic() < deadline: + if str(api.configs.get(LOG_CATEGORY, LOG_ITEM)) == want: + confirmed = time.monotonic() + break + with self.flip_lock: + self.flips.append(softiec_log.Flip(requested=requested, + confirmed=confirmed or time.monotonic(), on=on)) + self.log_on = on + + def rest_lane(self): + # A client of its own: the agent's lane must not share a connection with this one, and + # its own random source, because the C64 lane owns self.random. + api = UltimateApi(self.args.host, self.args.password, self.args.timeout) + lane_rnd = random.Random(self.args.seed + 100) + next_flip = time.monotonic() + lane_rnd.uniform(LOG_FLIP_MIN_SECONDS, LOG_FLIP_MAX_SECONDS) + flip_on = self.log_on + last_reset = time.monotonic() + while not self.stop.wait(self.policy.rest_seconds): + if self.quiet.is_set(): + self.stop.wait(0.2) + continue + try: + api.rest.json("/v1/drives") + api.machine.heap_free() + self.lane_counts["rest"] += 1 + # In a toggle phase, flip the log setting while the bus runs so a transfer + # overlaps a flip. Only the log setting moves; the bus id and enable stay, so + # the drive stays on device 11 enabled. + if self.log_mode == "toggle" and time.monotonic() >= next_flip: + flip_on = not flip_on + self.flip_log(api, flip_on) + next_flip = time.monotonic() + lane_rnd.uniform( + LOG_FLIP_MIN_SECONDS, LOG_FLIP_MAX_SECONDS) + # A stress phase resets the Software IEC drive over REST during traffic, which + # takes the drive lock (CR-6), closes the data channels and returns every + # partition to its root. The C64 lane reselects its partition and directory + # each step, so it recovers; the reset is the hostile event. + if self.policy.rest_reset and (time.monotonic() - last_reset > 20): + # The drives helper knows only the emulated slots a and b, so the softiec + # slot is reset through the route directly. + api.rest.request("PUT", "/v1/drives/softiec:reset") + last_reset = time.monotonic() + except Exception as exc: # the main lane decides whether this is a death + self.lane_errors.append(f"rest at iteration {self.iteration}: {exc}") + + def ftp_lane(self, index): + directory = f"{self.root.rstrip('/')}/{self.folder}" + payload = pattern(f"pclane{index}", 3000) + lane_random = random.Random(self.args.seed + index) # the C64 lane owns self.random + while not self.stop.wait(self.policy.ftp_seconds): + if self.quiet.is_set(): + continue + try: + with ftp.session(self.args.host, self.args.password, timeout=20) as client: + if self.policy.race: + # Fight over files and a directory the C64's stress lane also + # touches. These are owned by the stress lanes, so a difference in + # them is not the corruption the suite fails on; the fixture files + # under OS are never touched here. + # C0 to C2 are the names race_file reads and writes from the C64, + # stored by the drive as sequential files. + name = f"{directory}/RACE/C{lane_random.randrange(3)}.seq" + ftp.store(client, name, payload) + if lane_random.randrange(2): + ftp.quietly(lambda: client.delete(name)) + ftp.quietly(lambda: client.rmd(f"{directory}/RACE/SUB{index}")) + ftp.quietly(lambda: client.mkd(f"{directory}/RACE/SUB{index}")) + # Write a file inside the disk image the C64's direct access uses, so + # an FTP mount of the image and the drive's sector access race. The + # image content is not owned by the C64, so a difference is not the + # corruption the suite fails on. + if lane_random.randrange(3) == 0: + image_file = f"{directory}/DISK.D64/FTP{index}.SEQ" + ftp.quietly(lambda: ftp.store(client, image_file, payload[:200])) + ftp.quietly(lambda: client.delete(image_file)) + else: + ftp.names(client, f"{directory}/OS/KERNAL") + data = ftp.retrieve(client, f"{directory}/OS/KERNAL/MENU.O.prg") + if data != pattern("OS/KERNAL/MENU.O.prg", 2209): + self.lane_errors.append(f"ftp at iteration {self.iteration}: MENU.O.prg differs") + ftp.store(client, f"{directory}/PCLANE/PC.BIN", payload) + client.delete(f"{directory}/PCLANE/PC.BIN") + self.lane_counts["ftp"] += 1 + except Exception as exc: + self.lane_errors.append(f"ftp at iteration {self.iteration}: {exc}") + + # -- the run --------------------------------------------------------------------- + + def alive(self): + """Whether REST still answers, asked with the lanes paused and several times, so a + request the saturated network stack refused is not taken for a dead firmware.""" + self.quiet.set() + try: + for _attempt in range(LIVENESS_ATTEMPTS): + try: + self.api.rest.json("/v1/info") + return True + except Exception: + time.sleep(LIVENESS_RETRY_SECONDS) + return False + finally: + self.quiet.clear() + + @contextlib.contextmanager + def lanes_paused(self): + """Pauses the REST and FTP lanes for a UCI step. The target is driven one register write + per REST request, and with the stress lanes filling the network a queued command byte + was seen not to arrive, so the next command's bytes ran as part of it.""" + self.quiet.set() + try: + time.sleep(LANE_PAUSE_SECONDS) # let the requests already on the way finish + yield + finally: + self.quiet.clear() + + def recover_quietly(self): + """recover(), and if that fails, once more with the lanes paused: the agent is driven + over REST, so a recovery the lanes starved of the network is not yet a drive that has + stopped answering the C64.""" + try: + self.recover() + except Failure: + self.quiet.set() + try: + time.sleep(LIVENESS_RETRY_SECONDS) + self.recover() + finally: + self.quiet.clear() + + def fixture(self): + directory = f"{self.root.rstrip('/')}/{self.folder}" + with ftp.session(self.args.host, self.args.password) as client: + client.mkd(directory) + for sub in FIXTURE_DIRS: + client.mkd(f"{directory}/{sub}") + for name, size in FIXTURE.items(): + ftp.store(client, f"{directory}/{name}", pattern(name, size)) + # The x00 wrapped files, read by the CBM name in their header (SI-144). + for host, (cbm, record_length, size) in FIXTURE_X00.items(): + ftp.store(client, f"{directory}/X00/{host}", + x00_wrapper(cbm, record_length, pattern(host, size))) + # A directory of dozens of files, to read a listing to its end. + for i in range(MANY_ENTRIES): + ftp.store(client, f"{directory}/MANY/FILE{i:03d}.PRG", pattern(f"many{i}", 1 + i)) + # The disk images of every type: a D64 in the run root for direct access, and one of + # each in IMAGES for the image operations. create_dnp needs a track count. + self.api.files.create_d64(f"{directory}/DISK.D64", diskname="SOAK") + for name, creator in FIXTURE_IMAGES.items(): + target = f"{directory}/IMAGES/{name}" + if creator == "create_dnp": + self.api.files.create_dnp(target, tracks=4, diskname="SOAKNAT") + else: + getattr(self.api.files, creator)(target, diskname="SOAKIMG") + + def marker(self, nonce): + """A unique command that always fails (X is a command letter, so anything but XPWD + answers 30), so it produces a "command failed" line whatever the log setting. The + line's source address identifies this device in a shared spool, and the markers at + the start and end of a phase bound the window of lines that belong to it.""" + data = softiec_log.marker_text(nonce) + self.note(f"marker {data!r}") + # The wrapped agent records this as a failed command; its "command failed" line is + # what select_window finds by the nonce in the marker text. + self.agent.call(WRITE, 15, data) + return self.agent.call(READ_TO_EOI, 15, expect=STATUS_BYTES).decode("latin-1").strip() + + def dump_log_window(self, device_ip, texts): + """With --log-dump, writes the operations this phase recorded and the device's log lines + in its window side by side, so a verdict can be checked by hand.""" + if not getattr(self.args, "log_dump", None): + return + base = Path(self.args.log_dump) + base.mkdir(parents=True, exist_ok=True) + stem = base / f"{self.policy.name}-log-{self.log_mode}-{int(time.time())}" + with open(f"{stem}-operations.txt", "w", encoding="utf-8", errors="replace") as out: + for ev in self.log_events: + out.write(f"{ev.what} chan={ev.chan} dev={ev.dev} len={len(ev.txt)} " + f"txt=\"{softiec_log.render_text(ev.txt)}\" status={ev.status} " + f"reply={None if ev.reply is None else softiec_log.render_text(ev.reply)!r} " + f"optional={ev.optional} hex={ev.txt.hex()}\n") + with open(f"{stem}-lines.txt", "w", encoding="utf-8", errors="replace") as out: + out.write(f"# from {device_ip}\n") + for text in texts: + out.write(text + "\n") + + def log_verdict(self, start_nonce, end_nonce, pre_nonce=None, post_nonce=None): + """Read this phase's device log and correlate it with what the C64 lane did. Returns + (a Correlation or None, a note). None with a reason where no syslog source is + configured or the marker was not found, which the caller reports without failing.""" + source = self.syslog_source + if source is None: + return None, "no syslog source (pass --syslog-spool or configure the device's syslog to this host)" + # The device's syslog task sends at most about 200 lines a second and waits between + # rounds, so under load the end marker arrives seconds after the C64 sent it. The + # window is read once the end marker is there, or after LOG_FLUSH_SECONDS. + end_txt = softiec_log.render_text(softiec_log.marker_text(post_nonce or end_nonce)) + deadline = time.monotonic() + LOG_FLUSH_SECONDS + while True: + time.sleep(1.0) + entries = source.entries() + device_ip, texts = softiec_log.select_window(entries, start_nonce, end_nonce, + pre_nonce, post_nonce) + if any(end_txt in text for text in texts[-50:]) or (time.monotonic() > deadline): + break + if device_ip is None: + return None, ("the start marker was not found in the syslog; it may have been " + "split or dropped, or the device does not log to this collector") + self.dump_log_window(device_ip, texts) + if self.log_mode == "toggle": + with self.flip_lock: + flips = list(self.flips) + result = softiec_log.correlate_toggle(self.log_events, texts, flips, initial_on=False, + label=f"toggle from {device_ip}") + else: + result = softiec_log.correlate(self.log_events, texts, logging_on=self.log_on, + label=f"logging {'on' if self.log_on else 'off'} " + f"from {device_ip}") + return result, None + + def run(self, policy, duration, log_mode): + """Runs one phase: boot the session, set the log setting the phase asks for, then + repeat the policy's operations under its pacing until the deadline, sampling the heap + and, for stress, checking the drive after each step. A start and an end marker bound + the window the device log is correlated over. Returns the heap samples, the failures, + and the log correlation (or None).""" + self.policy = policy + self.log_mode = log_mode + self.stop = threading.Event() + self.quiet = threading.Event() # set while the lanes must leave the network alone + heap = [] + failures = [] + + # The C64 OS boot sequence is the session start (see #877), run once before timing and + # before recording, so the boot's own lines are not looked for in the phase window. + self.recording = False + self.boot() + # Fix the log setting for an off or an on phase; a toggle phase starts off and the + # REST lane flips it. The setting is restored by the category snapshot at the end. + self.log_on = (log_mode == "on") + if log_mode in ("on", "off"): + self.api.configs.set(LOG_CATEGORY, LOG_ITEM, "Enabled" if self.log_on else "Disabled") + elif log_mode == "toggle": + self.api.configs.set(LOG_CATEGORY, LOG_ITEM, "Disabled") + time.sleep(2.0) # a short settle so the first heap reading is not mid-cache-fill + self.heap_before = self.api.machine.heap_free() + + # Four markers: an outer pair that is not recorded and bounds the window, and an inner + # pair that is recorded. Another task's message can split a marker's line like any + # other; with a numbered line on each side, a split inner marker shows as a gap in the + # sequence numbers rather than as a line the window cannot account for. + pre_nonce, start_nonce, end_nonce, post_nonce = (uuid.uuid4().hex[:8] for _ in range(4)) + if hasattr(self.syslog_source, "mark"): + self.syslog_source.mark() + self.marker(pre_nonce) + self.recording = True + self.marker(start_nonce) + + deadline = time.monotonic() + duration + lanes = [] + if not self.args.no_lanes: + lanes.append(threading.Thread(target=self.rest_lane, daemon=True)) + for i in range(policy.ftp_lanes): + lanes.append(threading.Thread(target=self.ftp_lane, args=(i,), daemon=True)) + for lane in lanes: + lane.start() + try: + while time.monotonic() < deadline: + self.iteration += 1 + label, action = policy.choose(self.random) + self.counts[label] = self.counts.get(label, 0) + 1 + self.note(f"begin {label}") + try: + action(self) + except Corruption as exc: + failures.append(f"iteration {self.iteration} ({label}): {exc}") + self.recover_quietly() + if len(failures) > 5: + break + except Dead: + raise + except Failure as exc: + if not self.alive(): + raise Dead(f"the firmware stopped answering during iteration {self.iteration} " + f"({label}): {exc}") from exc + if policy.tolerant: + self.anomaly(label, exc) + self.recover_quietly() + else: + failures.append(f"iteration {self.iteration} ({label}): {exc}") + try: + self.recover_quietly() + except Failure as stuck: + raise Dead(f"the drive stopped answering the C64 during iteration " + f"{self.iteration} ({label}) while REST still answers: " + f"{exc}; then {stuck}") from stuck + if len(failures) > 5: + break + if policy.checkpoint: + try: + self.checkpoint() + except Corruption as exc: + failures.append(f"iteration {self.iteration} checkpoint: {exc}") + if len(failures) > 5: + break + if self.iteration >= WARMUP_ITERATIONS: + heap.append(self.api.machine.heap_free()) + if self.iteration % 10 == 0: + detail(f"{self.iteration} iterations, {dict(sorted(self.counts.items()))}, " + f"heap {heap[-1] if heap else '-'}, lanes {self.lane_counts}") + think = policy.think_time(self.random) + if think: + time.sleep(min(think, max(0.0, deadline - time.monotonic()))) + # The end marker closes the correlation window while the setting is still what + # the phase held; anything after it is outside the window. + try: + self.marker(end_nonce) + self.recording = False + self.marker(post_nonce) + except Failure: + pass + self.recording = False + finally: + self.stop.set() + for lane in lanes: + lane.join(timeout=30) + + correlation, note = self.log_verdict(start_nonce, end_nonce, pre_nonce, post_nonce) + # An idle settle, then the final heap reading for the before-and-after verdict. + time.sleep(IDLE_SETTLE_SECONDS) + try: + self.recover() + except Failure: + pass + self.heap_after = self.api.machine.heap_free() + return heap, failures, (correlation, note) + + def recover(self): + """Close what an interrupted operation left open, so the next one starts clean.""" + for channel in range(2, 15): + try: + self.agent.call(CLOSE, channel=channel) + except Failure: + pass + try: + self.agent.call(CLOSE, channel=15) + self.agent.call(OPEN, channel=15) + self.status() + except Failure: + self.agent.start() + self.agent.call(OPEN, channel=15) + self.status() + + +class Policy: + """One kind of run: which operations, how they are paced, how the lanes load the + device, and how the heap is judged. The two kinds share Session.run; only this data + differs between them. + + tolerant: a Failure from an operation is recorded as an anomaly rather than a failure, + because a hostile step is expected to draw DOS and KERNAL errors. + checkpoint: after each step, check the drive still answers and the fixture is intact. + heap_mode: "slope" judges a steady per-iteration loss; "settled" judges the drop from + before the load to after an idle settle. + """ + + def __init__(self, name, operations, *, think_min, think_max, rest_seconds, + ftp_seconds, ftp_lanes, rest_reset, race, tolerant, heap_mode, checkpoint): + self.name = name + self.operations = operations + self.think_min = think_min + self.think_max = think_max + self.rest_seconds = rest_seconds + self.ftp_seconds = ftp_seconds + self.ftp_lanes = ftp_lanes + # Whether the REST lane resets the Software IEC drive during traffic (stress only). + self.rest_reset = rest_reset + self.race = race + self.tolerant = tolerant + self.heap_mode = heap_mode + self.checkpoint = checkpoint + + def think_time(self, rnd): + """Seconds to wait between actions. Zero for stress, a few seconds for soak.""" + if self.think_max <= 0: + return 0.0 + return rnd.uniform(self.think_min, self.think_max) + + def choose(self, rnd): + total = sum(weight for _, _, weight in self.operations) + pick = rnd.randrange(total) + for label, action, weight in self.operations: + if pick < weight: + return label, action + pick -= weight + raise AssertionError("unreachable") + + +SOAK_POLICY = Policy("soak", Session.SOAK_OPERATIONS, think_min=1.0, think_max=6.0, + rest_seconds=REST_LANE_SECONDS, ftp_seconds=FTP_LANE_SECONDS, + ftp_lanes=1, rest_reset=False, race=False, tolerant=False, + heap_mode="slope", checkpoint=False) + +# The firmware has four FTP and four HTTP slots, so three racing FTP lanes leaves one +# free for the teardown's FTP session. +STRESS_POLICY = Policy("stress", Session.STRESS_OPERATIONS, think_min=0.0, think_max=0.0, + rest_seconds=0.0, ftp_seconds=0.3, ftp_lanes=3, rest_reset=True, + race=True, tolerant=True, heap_mode="settled", checkpoint=True) + + +class SpoolSource: + """A device log read from a file an external collector writes, one line per datagram as + softiec_log.SPOOL_FORMAT. mark() remembers where the file ends when a phase starts, and + entries() reads what the collector has written since, so a phase sees its own lines + without reading a spool that long runs have grown to tens of megabytes.""" + + def __init__(self, path): + self.path = path + self.offset = 0 + + def mark(self): + try: + self.offset = os.path.getsize(self.path) + except OSError: + self.offset = 0 + + def entries(self): + return softiec_log.read_spool(self.path, self.offset) + + def stop(self): + pass + + +# The UCI SoftIEC target command bytes, from software/io/command_interface/softiec_target.h. +# uci_targets_test defines only the few it uses, so the rest are named here. +UCI_TARGET_SOFTIEC = 0x05 +UCI_CMD_OPEN = 0x13 +UCI_CMD_CLOSE = 0x14 +UCI_CMD_CHKIN = 0x15 +UCI_CMD_ADD_PARTITION = 0x20 +UCI_CMD_DEL_PARTITION = 0x21 + + +class UciProbe: + """The UCI SoftIEC target, reached over the cartridge registers ($DF1B-$DF1F) with the + Uci and RestSession classes from tests/e2e/io/command_interface/uci_targets_test.py. Its + steps run only between bus operations, on the C64 lane's own thread, so a register access + never lands in an agent transaction. Its opens and closes go through the same channels the + bus does, so they log too; they are recorded as optional events.""" + + def __init__(self, module, uci, session_ref): + self.module = module + self.uci = uci + self.session = session_ref + + @classmethod + def create(cls, args, session): + """Set up the probe, or return (None, reason) where the command interface is not + present or the SoftIEC target is not loaded. The caller enables the Command Interface + setting and restores it; this only uses it.""" + try: + sys.path.insert(0, bootstrap.directory("e2e", "io", "command_interface")) + import uci_targets_test as module # noqa: PLC0415 + except Exception as exc: # noqa: BLE001 - any import trouble means skip UCI + return None, f"the UCI test module could not be imported: {exc}" + try: + rest_session = module.RestSession(args.host, args.password, args.timeout) + uci = module.Uci(rest_session, module.BUSY_TIMEOUT_SECONDS) + # The registers read $FF everywhere when nothing decodes them; that is a machine + # without the interface at these addresses. + if all(rest_session.peek(0xDF1B + offset) == 0xFF for offset in range(5)): + return None, "the command interface registers read $FF, so it is not present" + uci.release() + reply, status = uci.transact(bytes([module.TARGET_SOFTIEC, module.SOFTIEC_CMD_IDENTIFY])) + if status == module.SOFTIEC_NOT_LOADED: + return None, "the SoftIEC target reports the drive is not loaded" + if not reply.startswith(b"SOFTWARE IEC TARGET"): + return None, f"the SoftIEC target did not identify itself: {reply!r}" + except Exception as exc: # noqa: BLE001 - a device that cannot answer skips UCI + return None, f"the command interface did not answer: {exc}" + return cls(module, uci, session), None + + def _read_through_target(self, name, secondary=3): + """Open a file through the target, read it with CHKIN, close it, and return the bytes + the response FIFO carried. The open and close log lines, recorded as optional.""" + module = self.module + target = module.TARGET_SOFTIEC + self.uci.transact(bytes([target, UCI_CMD_OPEN, secondary, 0]) + name) + self.session.emit("open", secondary, name, status=0, optional=True) + data, _status = self.uci.transact(bytes([target, UCI_CMD_CHKIN, secondary])) + self.uci.transact(bytes([target, UCI_CMD_CLOSE, secondary])) + self.session.emit("close", secondary, b"", optional=True) + return data + + def exercise(self, session, hostile=False): + """Run a handful of target commands. IDENTIFY, GET_FATNAME and GET_IECNAME touch no + channel and log nothing; the read through the target opens and closes a channel. In + hostile mode a partition is added and removed, which is a lock path (CR-6).""" + module = self.module + target = module.TARGET_SOFTIEC + here = session.here + self.uci.transact(bytes([target, module.SOFTIEC_CMD_IDENTIFY])) + self.uci.transact(bytes([target, module.SOFTIEC_CMD_GET_FATNAME, 0x02]) + b"#") + # GET_IECNAME on an x00 fixture: its reply is the CBM name in the header (SI-144). + host = "WRAPPED.P00" + full = f"{session.root.rstrip('/')}/{session.folder}/X00/{host}".encode("ascii") + self.uci.transact(bytes([target, module.SOFTIEC_CMD_GET_IECNAME]) + full) + # Read a small fixture through the target and compare it byte for byte. + data = self._read_through_target(f"//{here}/OS/SETTINGS/:CONFIG.T".encode("ascii")) + want = pattern("OS/SETTINGS/CONFIG.T.seq", FIXTURE["OS/SETTINGS/CONFIG.T.seq"]) + if data != want: + raise Corruption(f"a UCI CHKIN of CONFIG.T read {data!r}, expected {want!r}") + if hostile: + index = 200 + path = f"{session.root.rstrip('/')}/{session.folder}/WORK".encode("ascii") + self.uci.transact(bytes([target, UCI_CMD_ADD_PARTITION, index]) + b"UCITMP:" + path) + self.uci.transact(bytes([target, UCI_CMD_DEL_PARTITION, index])) + + def stop(self): + try: + self.uci.release() + except Exception: # noqa: BLE001 - leaving the interface is best effort + pass + + +def heap_verdict(session, policy, heap): + """The heap section of a phase's report. Returns the failures it found, prints the + numbers as detail either way.""" + if policy.heap_mode == "settled": + if (session.heap_before is None) or (session.heap_after is None): + return [] + loss = session.heap_before - session.heap_after + detail(f"heap free {session.heap_before} before the stress, {session.heap_after} " + f"after an idle settle, {loss} lost") + if loss > STRESS_HEAP_LOSS_TOLERANCE_BYTES: + return [f"the heap lost {loss} bytes over the stress run"] + return [] + # The caches fill during the first part of a session: in a 30 minute soak the free heap + # fell by about 30 KB over the first 60 to 70 iterations on an Ultimate 64 Elite and on a + # U2+L (the mount cache alone keeps eight disk images) and then stayed flat to the end. So + # the second half of the samples is judged, where a steady loss is a leak. + tail = heap[len(heap) // 2:] + if len(tail) < 3: + return [] + # A sample taken while a lane holds a transfer buffer reads up to about 20 KB low, so + # the most free heap of the first and the last quarter of the second half are compared + # rather than two single samples. + window = max(1, len(tail) // 4) + first, last = max(tail[:window]), max(tail[-window:]) + slope = (first - last) / max(1, len(tail) - window) + detail(f"heap free {heap[0]} after warm-up, {first} at the start of the second half, {last} " + f"at the end, {slope:.0f} bytes lost per iteration over the second half") + if slope > LEAK_TOLERANCE_BYTES_PER_ITERATION: + return [f"the heap shrank by {slope:.0f} bytes per iteration"] + return [] + + +def log_verdict_report(correlation, note): + """Print the log correlation and return the failures it found. A missing source or an + unfound marker is reported as detail, not a failure, so a run without a collector still + passes; a real mismatch between the log and the operations is a failure.""" + if correlation is None: + detail(f"log correlation skipped: {note}") + return [] + detail(f"log correlation, {correlation.summary()}") + for problem in correlation.contradictions[:5]: + detail(f" contradiction: {problem}") + for problem in correlation.logging_off_success[:5]: + detail(f" {problem}") + for problem in correlation.unexpected_bad[:5]: + detail(f" {problem}") + return correlation.problems() + + +def run_phase(session, duration, policy, log_mode): + """Runs one phase and reports it as its own section and check with its own heap and log + verdicts. Returns True if the phase passed. A dead firmware stops the whole run and is + not caught here.""" + session.begin_phase() + section(f"{policy.name}, log {log_mode} ({duration:.0f} s)") + try: + with check("the drive keeps answering, keeps its data, its heap and a log that matches"): + heap, failures, (correlation, note) = session.run(policy, duration, log_mode) + detail(f"{session.iteration} iterations: {dict(sorted(session.counts.items()))}; " + f"lanes {session.lane_counts}") + if session.statuses: + detail(f"statuses seen: {dict(sorted(session.statuses.items()))}") + if session.anomalies: + detail(f"anomalies recorded: {dict(sorted(session.anomalies.items()))}") + for example in session.anomaly_examples: + detail(f" {example}") + if session.lane_errors: + detail("lane errors: " + "; ".join(session.lane_errors[:10])) + failures = failures + heap_verdict(session, policy, heap) + failures = failures + log_verdict_report(correlation, note) + if failures: + detail("recent operations: " + " | ".join(session.history)) + raise Failure("; ".join(failures)) + return True + except Dead: + detail("recent operations: " + " | ".join(session.history)) + raise + except Failure: + return False + + +def plan_phases(args): + """The phases to run, in order, from the mode, the durations and the log setting. + + A base phase is one mode run for one duration; --log then splits it into log phases: + off, on and toggle each give one phase in that state, and both gives an off phase then an + on phase. --profile maps to a single mode for run-tests and defaults --log to off so an + unattended gate needs no collector; --profile overrides --mode. + """ + if args.profile: + if args.profile == "stress": + base = [(args.duration or PROFILE_STRESS_SECONDS, STRESS_POLICY)] + else: + base = [(args.duration or PROFILE_SOAK_SECONDS, SOAK_POLICY)] + elif args.mode == "soak": + base = [(args.duration or SOAK_DEFAULT_SECONDS, SOAK_POLICY)] + elif args.mode == "stress": + base = [(args.duration or STRESS_DEFAULT_SECONDS, STRESS_POLICY)] + else: + base = [(args.soak_duration, SOAK_POLICY), (args.stress_duration, STRESS_POLICY)] + + log = args.log or ("off" if args.profile else "both") + modes = {"off": ["off"], "on": ["on"], "toggle": ["toggle"], "both": ["off", "on"]}[log] + return [(duration, policy, log_mode) + for duration, policy in base for log_mode in modes] + + +def setup_syslog_source(session, api, args): + """Where this phase's device log comes from, and a note for the report. A spool file when + --syslog-spool is given; otherwise the UDP port the device's syslog setting names, when + that address is one of this host's; otherwise None with the reason, which leaves the + phases running with the log verdict skipped rather than failing the run.""" + if args.syslog_spool: + return SpoolSource(args.syslog_spool), f"reading the spool {args.syslog_spool}" + if SYSLOG_CATEGORY not in api.configs.category_names(): + return None, "this device has no Network Settings; pass --syslog-spool" + parsed = softiec_log.parse_syslog_server(str(api.configs.get(SYSLOG_CATEGORY, SYSLOG_ITEM))) + if parsed is None: + return None, "the device's 'Log to Syslog Server' setting is empty; pass --syslog-spool" + ip, port = parsed + if ip not in softiec_log.local_addresses(): + return None, (f"the device logs to {ip}, which is not this host; run the collector " + f"there and pass --syslog-spool") + try: + source = softiec_log.UdpLogSource("", port) + source.start() + except OSError as exc: + return None, (f"could not bind UDP {port}: {exc}; two suites cannot share the port, " + f"so pass --syslog-spool with an external collector") + return source, f"binding UDP {port} for the log the device sends to {ip}" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + cli.add_device_arguments(parser) + parser.add_argument("--mode", choices=("soak", "stress", "both"), default="both", + help="soak is the realistic C64 OS session, stress edge-tests the " + "interface as hard as the agent allows, both runs the soak " + "phase then the stress phase (default: both).") + parser.add_argument("--profile", choices=("stress", "soak"), + help="Kept for run-tests: stress runs the stress mode for ten " + "minutes, soak runs the soak mode for four hours. Overrides " + "--mode.") + parser.add_argument("--duration", type=float, + help="seconds of one soak or stress run, instead of the default") + parser.add_argument("--soak-duration", type=float, default=SOAK_DEFAULT_SECONDS, + help=f"seconds of the soak phase of a both run (default: {SOAK_DEFAULT_SECONDS})") + parser.add_argument("--stress-duration", type=float, default=STRESS_DEFAULT_SECONDS, + help=f"seconds of the stress phase of a both run (default: {STRESS_DEFAULT_SECONDS})") + parser.add_argument("--seed", type=int, default=877) + parser.add_argument("--no-lanes", action="store_true", + help="only the C64's operations, to tell the drive's heap use from REST's and FTP's") + parser.add_argument("--log", choices=("off", "on", "both", "toggle"), + help="whether the drive logs every operation: off, on, both (off " + "then on, the default), or toggle (a lane flips it during the " + "phase). --profile defaults this to off.") + parser.add_argument("--syslog-spool", + help="a file an external collector writes, one line per datagram as " + f"'{softiec_log.SPOOL_FORMAT}', to read the device log from; " + "without it the UDP port the device's syslog setting names is " + "bound when it points at this host.") + parser.add_argument("--log-dump", + help="a directory to write each phase's recorded operations and the " + "device log lines of its window to, for checking a verdict by hand.") + args = parser.parse_args() + phases = plan_phases(args) + session = Session(args) + api = session.api + cmd_if_snapshot = {} + try: + section("setup") + with check("the device has one Software IEC partition and device 11 is free"): + drives = {name: value for entry in api.rest.json("/v1/drives")["drives"] for name, value in entry.items()} + if any(d.get("enabled") and d.get("bus_id") == 11 for name, d in drives.items() + if name not in ("a", "IEC Drive")): + raise Failure("Device 11 is already in use") + partitions = drives["IEC Drive"]["partitions"] + if len(partitions) != 1 or partitions[0]["id"] != 1: + raise Failure("This suite requires one Software IEC partition, numbered 1") + original_path = partitions[0]["path"] + plan = [(policy.name, log_mode, int(duration)) for duration, policy, log_mode in phases] + detail(f"{api.rest.json('/v1/info').get('firmware_version')}, seed {args.seed}, phases {plan}") + # The snapshot restores both the Software IEC settings (the log setting included) and, + # where it exists, the Command Interface setting the UCI steps enable. + snapshot = {LOG_CATEGORY: api.configs.category(LOG_CATEGORY)} + if CMD_IF_CATEGORY in api.configs.category_names(): + cmd_if_snapshot = api.configs.category(CMD_IF_CATEGORY) + snapshot[CMD_IF_CATEGORY] = cmd_if_snapshot + saved = Snapshot(args.host, snapshot) + started = created = False + try: + with check("start the IEC agent and build the fixture"): + api.configs.set(LOG_CATEGORY, "Soft Drive Bus ID", 11) + api.configs.set(LOG_CATEGORY, "IEC Drive", "Enabled") + session.agent.start() + started = True + session.agent.call(OPEN, channel=15) + session.status() + session.command("CD//") + session.root = iec_drive(api)["partitions"][0]["path"] + session.fixture() + created = True + with check("set up the device log source and the UCI target"): + source, note = setup_syslog_source(session, api, args) + session.syslog_source = source + detail(f"device log: {note}") + if cmd_if_snapshot: + api.configs.set(CMD_IF_CATEGORY, CMD_IF_ITEM, "Enabled") + session.uci, uci_note = UciProbe.create(args, session) + else: + session.uci, uci_note = None, "no Command Interface setting on this device" + detail(f"UCI target: {'available' if session.uci else 'skipped, ' + uci_note}") + ok = True + for duration, policy, log_mode in phases: + ok = run_phase(session, duration, policy, log_mode) and ok + if not ok: + raise Failure("one or more phases failed; see the sections above") + except Dead: + detail("recent operations: " + " | ".join(session.history)) + raise + finally: + def restore_directory(): + if started and session.alive(): + session.agent.call(CLOSE, channel=15) + session.agent.call(OPEN, channel=15) + session.command("CD//" + original_path[len(session.root or ""):].upper()) + session.agent.call(CLOSE, channel=15) + + def remove_fixture(): + if created and session.alive(): + with ftp.session(args.host, args.password) as client: + ftp.remove_tree(client, f"{session.root.rstrip('/')}/{session.folder}") + + if session.uci is not None: + session.uci.stop() + if session.syslog_source is not None: + session.syslog_source.stop() + ok = True + for label, action in (("restore the IEC working directory", restore_directory), + ("restore the Software IEC and Command Interface settings", + lambda: saved.restore(api)), + ("remove this run's directory", remove_fixture), + ("return the C64 to BASIC", lambda: api.machine.reset(force=True))): + ok = teardown_step(label, action) and ok + except Exception as exc: + traceback.print_exc() + suite_fail(SUITE, str(exc)) + return 1 + suite_ok(SUITE) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From e7e59151287f9f0ffcb3ae8931bb54db5b6759de Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Sun, 20 Sep 2026 20:01:13 +0100 Subject: [PATCH 021/514] feat(iec): set the clock, swap the device number, rename partitions and headers SI-120 T-W, SI-101 S-8/S-9/S-D, SI-051 R-P, SI-064 R-H. --- doc/softiec_compatibility_spec.md | 146 ++++++++----- software/filemanager/dos.cc | 5 +- software/filemanager/filemanager.cc | 20 ++ software/filemanager/filemanager.h | 1 + software/filesystem/file_system.h | 6 +- software/filesystem/filesystem_d64.cc | 50 +++++ software/filesystem/filesystem_d64.h | 1 + software/io/iec/cbmdos_parser.cc | 298 +++++++++++++++++++++++++- software/io/iec/cbmdos_parser.h | 7 + software/io/iec/cbmdos_parser_test.cc | 175 ++++++++++++++- software/io/iec/cbmdos_stubs.cc | 34 ++- software/io/iec/iec_channel.cc | 89 ++++++++ software/io/iec/iec_channel.h | 3 + software/io/iec/iec_drive.cc | 6 + software/io/iec/iec_drive.h | 1 + software/io/rtc/current_time.h | 18 ++ software/io/rtc/rtc.cc | 10 + software/io/rtc/rtc_dummy.cc | 10 + software/io/rtc/rtc_i2c.cc | 10 + software/io/rtc/rtc_only_i2c.cc | 10 + software/test/iecdrive/testdrive.cc | 121 +++++++++++ 21 files changed, 944 insertions(+), 77 deletions(-) create mode 100644 software/io/rtc/current_time.h diff --git a/doc/softiec_compatibility_spec.md b/doc/softiec_compatibility_spec.md index 88e268c19..7f635f530 100644 --- a/doc/softiec_compatibility_spec.md +++ b/doc/softiec_compatibility_spec.md @@ -602,16 +602,20 @@ Recorded so the omission is deliberate rather than accidental. ### 5.4 Other partition commands -**SI-051.** `R-P:newname=oldname` renames a partition. Source: HD 9-14, FD, RL. -Not implemented. `U execute_command()` routes every `R` whose second character is not -`D` to `rename_command()`, which strips the leading letter and then hands `-P:WORK` -to `parse_full_path()`; that rejects the `-` and answers `30`. **Change required:** -recognise `R-P` and `R-H` before falling through to the file rename, as -`SD parse_doscommand()` does with `if (command_length > 2 && command_buffer[1] == '-')`. +**SI-051.** `R-P:newname=oldname` renames a partition. Source: HD 9-14, FD, RL. The +old name is a partition's name and not a path, so the partition list is searched for it, +without regard to case; a name no partition carries answers `77,SELECTED PARTITION +ILLEGAL`. An empty name on either side answers `34` and a command with no `=` answers +`30`. The new name is what the partition directory, `G-P` and the header of a listing +of that partition's root then show. -**Decision (PR #881): not implemented.** Neither report nor GAP nor TRACE uses `R-P`, -and the rename would live only in memory until the partition list is saved from the -menu. The drive answers `30`, as before. +The dash in the second character is what separates `R-P` and `R-H` (SI-064) from a file +rename, as `SD parse_doscommand()` separates them with +`if (command_length > 2 && command_buffer[1] == '-')`. + +The name lives as long as the drive runs. The partition list is written to an `.IPR` +file only when the menu saves it, which is equally true of a partition renamed from the +menu, so the command is as durable as the user interface it shares the list with. **SI-052.** `N[n]:name[,id]` formats. Its full behaviour is specified in SI-071. @@ -675,23 +679,30 @@ removing a subdirectory which is a parent of the directory in which you are loca `00, OK`, which is the case HD 9-19 forbids in order to stop a user removing a parent of the directory they are standing in. **Change required** for the path rejection. -**SI-064.** `R-H[n][path]:newname` renames a directory header. The name is at most -16 characters. Sources: HD 9-15; IDE 15.6.5; `SD parse_set_header(3)`, which also -accepts an id of at most five characters. On a host file system a directory has no -header separate from its name, so this renames the directory itself, which is what -GSD says sd2iec does with the equivalent operation. Not implemented; -**change required.** C64 OS depends on the header for a related reason: GAP says -"C64 OS in particular uses the directory header when creating a favorite... The name -of the favorite is taken from the directory header name." - -**Decision (PR #881): not implemented.** On a CMD HD, `R-H` changes only the header -block and leaves the directory's name in its parent unchanged; on a host file system the -only equivalent is renaming the directory itself, which is a different operation and -would surprise a program written for a CMD HD. GSD states that "The R-H command is not -supported by sd2iec". C64 OS takes a favorite's name from the header, and SI-065, which -is implemented, makes the header show the directory's own name as sd2iec does. The -reporter wrote that `R-H` "should add not to far away, for the time being ok". The -drive answers `30`. +**SI-064.** `R-H[n][path]:newname[,id]` renames the header of a directory. The name is +at most 16 characters and the id two. Sources: HD 9-15; IDE 15.6.5; +`SD parse_set_header(3)`. The path selects the directory and the name behind the colon +is the new header; with no path it is the current directory of the partition. An empty +name answers `34`, a name with a wildcard `33`, and a path that is not there +`71,DIRECTORY ERROR`. + +What a header is depends on what the directory sits in, and in each case it is what a +listing of that directory shows (SI-065). + +| Directory | Header | What `R-H` changes | +| --- | --- | --- | +| inside a CBM disk image | the disk name in the BAM of the root, or in the header block of a subdirectory | that name; the disk id and the DOS version stay as they are unless an id is given | +| a subdirectory on the host file system | the name the parent holds, which is all a host directory has | the directory's name, and the drive's current directory follows it when it is standing in or below that directory | +| the root of a partition | the partition's name | the partition's name, as `R-P` does (SI-051) | + +C64 OS reads the header for a related reason: GAP says "C64 OS in particular uses the +directory header when creating a favorite... The name of the favorite is taken from the +directory header name." + +The drive asks the file system for the label first and renames the directory only where +the file system has none, so a medium that gains a separate label later needs no change +here. GSD states that "The R-H command is not supported by sd2iec"; the CMD manuals +describe it and this drive follows them. **SI-065.** The header line of a directory listing carries the name of the directory as it appears in its parent, and of the partition when the root is listed. Source: @@ -1058,18 +1069,17 @@ device number slot without holding the processor in reset, because the command i on the bus, and it is not written to the configuration. **SI-101.** `S-8`, `S-9` and `S-D` are the typed aliases for swapping to device 8, -device 9 and back to the configured default. Sources: HD 9-34; IDE 15.4.1. On this -drive there is nothing to swap with, so `S-8` and `S-9` set the device number -directly and `S-D` restores the configured one. **Change required**, and note the -parsing hazard: `U execute_command()` routes every `S` to `scratch_command()`, so -`S-8` currently tries to scratch a file named `-8` and answers, measured, -`62,FILE NOT FOUND`. `SD parse_doscommand()` guards -this with `if (command_length == 3 && command_buffer[1] == '-')`, and then answers -`31`: sd2iec recognises the form but does not implement the swap. - -**Decision (PR #881): not implemented.** There is no second drive to swap with, and no -report or program asks for the aliases. The three byte forms answer `31`, as sd2iec -answers them, and are not taken for a scratch of a file named `-8`. +device 9 and back to the configured default. Sources: HD 9-34; IDE 15.4.1. On this drive +there is one drive behind the number, so `S-8` and `S-9` set the device number to 8 and +to 9 and `S-D` returns it to the one the settings hold. The number is not written to the +settings, as `U0>` does not write it (SI-100). + +The command is exactly three characters with a dash in the second, which is how +`SD parse_doscommand()` tells it from a scratch: `S:-8` scratches a file named `-8` and +`S-88` scratches one named `-88`. A third character that is none of `8`, `9` and `D` +answers `30`, because `S` is a command letter and its argument is not (SI-030); that +covers `S-C`, the SCSI pass-through of SI-106. sd2iec answers the whole group `31`, +recognising the form without implementing the swap. **SI-102.** `W-0` and `W-1` clear and set a software write protect for the whole drive. Sources: HD 9-35; IDE 15.4.10. While set, every write answers @@ -1145,9 +1155,9 @@ accepts only `MD`. **Change required.** **Decision (PR #881): `M-R` implemented; `M-W` and `M-E` answer `30`.** Nothing of what `M-W` writes is kept and `M-E` runs nothing, so answering `00, OK` would tell a fast -loader that its drive code is in place and running; this is the same reason SI-120 gives -for not answering OK to a clock write that sets nothing. The reporter's request was for -`M-R`, which C64 OS sends four times at boot (TRACE). +loader that its drive code is in place and running. An `00, OK` means the work was done, +which is also why a clock write that the clock does not accept answers `30` (SI-120). The +reporter's request was for `M-R`, which C64 OS sends four times at boot (TRACE). **SI-106.** `S-C`, the SCSI pass-through of HD 9-39, is out of scope. @@ -1237,17 +1247,47 @@ minute, second, an AM or PM flag, and `CHR$(13)`, BCD-coded for `B`. The `I` for is the ISO 8601 subset `"YYYY-MM-DDThh:mm:ss dow"+CHR$(13)`. Sources: HD 9-36 to 9-38; IDE 15.4.8; SD README under `T-R and T-W`; GSD "Realtime Clock". -Current behaviour: the four read forms are implemented in -`U IecParser::time_command()`. The write forms answer `00, OK` and do nothing. -**Change required** only in that the write forms should set the Ultimate's real time -clock, which is the device's clock, or answer `30,SYNTAX ERROR` as sd2iec does when -there is no clock to set. Silently answering OK and not setting the clock is the one -thing that must not remain. +A write sets the Ultimate's own real time clock, which is the clock every other +interface reads and writes: the drive has no clock of its own. The parser validates the +command, converts it to a calendar date and time, and passes that to +`set_current_time()`, the accessor each real time clock driver defines beside +`get_current_time()`; the control interface's `DOS_CMD_SET_TIME` passes through the same +accessor. A write that is refused, and a write the clock does not accept, answer +`30,SYNTAX ERROR` and leave the clock alone, so an `00, OK` means the clock was set. -**Decision (PR #881): the write forms answer `30`.** The clock belongs to the system, -and GAP notes that C64 OS sets it through its UCI real time clock driver. Setting it from -the IEC bus would have needed a setter in each of the three real time clock drivers. -`30` is the answer this requirement allows. +**SI-121.** Each write form carries the fields of the matching read form, at the same +offsets. + +| Form | After `T-Wx` | Shortest accepted | +| --- | --- | --- | +| `A` | `dow. mo/da/yr hr:mi:se xM`, the day of week matched on its first two characters, the space and the marker optional | 26 bytes | +| `B` | day of week, year, month, day, hour in 12-hour form, minute, second, PM flag, all BCD | 12 bytes | +| `D` | the same eight fields in binary | 12 bytes | +| `I` | `YYYY-MM-DDThh:mm:ss`, with the day of week a `T-RI` answer ends in accepted and ignored | 23 bytes | + +Source: `SD parse_timewrite()`, which is also the source for the rules below. + +* The day of week is stored as the `A`, `B` and `D` forms send it, without being checked + against the date, as a CMD drive stores it. The `I` form carries none and derives it. +* A twelve in a 12-hour hour field is midnight or noon, and the PM flag adds half a day. + The `A` form without its marker is a 24-hour time. +* A two-digit year below 80 is in this century and from 80 in the last one. +* A `CHR$(13)` inside the binary fields of `B` and `D` is data. Only a terminator after + the last field of a form is dropped (SI-016). + +**SI-122.** A write is refused with `30` when a field is out of range: a month outside 1 +to 12, a day outside the length of that month in that year, a day of week above 6, an +hour above 23, a minute or a second above 59, a BCD field whose nibbles are not digits, +or a year outside 1980 to 2079, which is what two BCD digits counted from the epoch hold. +`SD parse_timewrite()` checks the same ranges apart from the length of the month; that +check is added here because a 31 February would otherwise reach the clock chip and be +read back as a different date. + +**SI-123.** Every field sits at a fixed offset and every separator is checked. A field +written to another width is refused, where `SD parse_timewrite()` reads a number of any +width and then skips one character. The `A` form's AM or PM marker is at a fixed offset +in that source as well, so a command whose earlier fields are of another width cannot be +read consistently in any case. --- @@ -1916,15 +1956,11 @@ affected by them. | Requirement | Why it is not implemented | What the drive answers | | --- | --- | --- | -| SI-051 `R-P` | No report, GAP or TRACE uses it, and the new name would only live in memory until the partition list is saved from the menu | `30` | | SI-054 `V` | Inside a disk image, an OK would claim a validation of the block map that did not happen | `31` | -| SI-064 `R-H` | On a host directory it would rename the directory itself, which a CMD HD's header rename does not do; sd2iec does not support it either | `30` | | SI-077 `EL:`, `EU:`, `EH:`, `A:`, `XH:`, `D:` | `L` (SI-076) provides lock and unlock; hiding files has no effect while listings show hidden files; the header forms are `R-H` | `30` for the `E` and `X` forms, `31` for `A` and `D` | | SI-090 `##n`, SI-092 | Large buffers serve sd2iec's 512 byte sector commands `DR` and `DW`, which are out of scope (SI-096); this drive's block commands use 256 byte sectors | `##n` opens a standard buffer; a third `B-P` number is ignored | -| SI-101 `S-8`, `S-9`, `S-D` | There is no second drive to swap with | `31`, as sd2iec answers | | SI-102 `W-0`, `W-1` | No report or program asks for a software write protect, and it needs a check in every path that writes | `31` | | SI-105 `M-W`, `M-E` | Nothing written is kept and nothing is run, so an OK would tell a fast loader its drive code runs | `30` | -| SI-120 `T-WA`, `T-WB`, `T-WD`, `T-WI` | The clock belongs to the system, and C64 OS sets it through its UCI clock driver (GAP) | `30`, which SI-120 allows | | SI-137 raw directory | It would change what existing programs, and clients of the UCI target, receive when they open `$` on a data channel | the listing, as before | | SI-145 writing x00 files | A new user setting that no report asks for; reading x00 files (SI-144) already gives the interchange | new files are written plain | diff --git a/software/filemanager/dos.cc b/software/filemanager/dos.cc index 28de4fb84..5de2b02ef 100644 --- a/software/filemanager/dos.cc +++ b/software/filemanager/dos.cc @@ -3,6 +3,7 @@ #include "home_directory.h" #include "endianness.h" #include "rtc.h" +#include "current_time.h" #include #include "c64.h" @@ -557,9 +558,7 @@ void Dos::parse_command(Message *command, Message **reply, Message **status) { wdz = wdz % 7; if (wdz < 0) wdz += 7; - int corr = rtc.get_correction(); - rtc.set_time(y, M, D, wdz, h, m, s); - rtc.set_time_in_chip(corr, y, M, D, wdz, h, m, s); + set_current_time(wdz, command->message[2] + 1900, M, D, h, m, s); rtc.get_time(y, M, D, wd, h, m, s); sprintf((char*) data_message.message, "%s %4d/%02d/%02d %02d:%02d:%02d", wdnames[wd], diff --git a/software/filemanager/filemanager.cc b/software/filemanager/filemanager.cc index 595917b1e..30e348a06 100644 --- a/software/filemanager/filemanager.cc +++ b/software/filemanager/filemanager.cc @@ -1238,6 +1238,26 @@ FRESULT FileManager::set_attributes(const char *pathname, uint8_t attrib, uint8_ return fres; } +// The label the file system itself holds for a directory, where it has one (SI-064). +FRESULT FileManager::set_dir_label(const char *pathname, const char *name, const char *id) +{ + PathInfo pathInfo(rootfs); + pathInfo.init(pathname); + lock(); + // A mount point is entered, as open_directory() does, so the label of a directory + // inside a mounted image is the one the command reaches. + FRESULT fres = find_pathentry(pathInfo, true); + if (fres == FR_OK) { + fres = pathInfo.getLastInfo()->fs->dir_set_label(pathInfo.getPathFromLastFS(), name, id); + if (fres == FR_OK) { + mstring work; + sendEventToObservers(eRefreshDirectory, pathInfo.getFullPath(work, -1), ""); + } + } + unlock(); + return fres; +} + FRESULT FileManager::delete_file(Path *path, const char *name) { PathInfo pathInfo(rootfs); diff --git a/software/filemanager/filemanager.h b/software/filemanager/filemanager.h index a5cf33061..5854006d8 100644 --- a/software/filemanager/filemanager.h +++ b/software/filemanager/filemanager.h @@ -234,6 +234,7 @@ class FileManager FRESULT get_free(Path *path, uint32_t &free, uint32_t &cluster_size); FRESULT get_total(Path *path, uint32_t &total, uint32_t &cluster_size); FRESULT set_attributes(const char *pathname, uint8_t attrib, uint8_t mask); + FRESULT set_dir_label(const char *pathname, const char *name, const char *id); FRESULT fs_read_sector(Path *path, uint8_t *buffer, int track, int sector); FRESULT fs_write_sector(Path *path, uint8_t *buffer, int track, int sector); FRESULT fs_allocate_sector(Path *path, int &track, int §or, bool alloc); diff --git a/software/filesystem/file_system.h b/software/filesystem/file_system.h index aaab07541..f6a40d27e 100644 --- a/software/filesystem/file_system.h +++ b/software/filesystem/file_system.h @@ -65,7 +65,11 @@ class FileSystem virtual FRESULT file_open(const char *filename, uint8_t flags, File **); // Opens file (creates file object) virtual FRESULT file_rename(const char *old_name, const char *new_name); // Renames a file virtual FRESULT file_delete(const char *path); // deletes a file - virtual FRESULT file_attrib(const char *path, uint8_t attrib, uint8_t mask) { return FR_NOT_ENABLED; } // sets the attribute bits in mask to those in attrib + virtual FRESULT file_attrib(const char *path, uint8_t attrib, uint8_t mask) { return FR_NOT_ENABLED; } // sets the attribute bits in mask to those in attrib + // Sets the label a directory carries inside the file system itself, where it has one + // that is separate from the name its parent holds. An empty id leaves the one that + // is there. A file system whose directories have no such label answers FR_NOT_ENABLED. + virtual FRESULT dir_set_label(const char *path, const char *name, const char *id) { return FR_NOT_ENABLED; } virtual void file_print_info(File *f) { } // debug diff --git a/software/filesystem/filesystem_d64.cc b/software/filesystem/filesystem_d64.cc index a075be8bf..ef1fd7f56 100644 --- a/software/filesystem/filesystem_d64.cc +++ b/software/filesystem/filesystem_d64.cc @@ -314,6 +314,56 @@ FRESULT FileSystemCBM::dir_open(const char *path, Directory **dir) // Opens dire return res; } +// The header a directory carries in the file system itself: the volume name in the BAM +// of the root, and the header block of a subdirectory. The disk id and the DOS version +// keep what they hold unless an id is given, because a rename of the header is not a +// format (SI-064). +FRESULT FileSystemCBM::dir_set_label(const char *path, const char *name, const char *id) +{ + if (!writable) { + return FR_WRITE_PROTECTED; + } + Directory *d = NULL; + FRESULT fres = dir_open(path, &d); + if (fres != FR_OK) { + return fres; + } + DirInCBM *cd = (DirInCBM *)d; + uint8_t *header; + if (cd->root) { + header = root_buffer + volume_name_offset; + } else { + int abs_sect = get_abs_sector(cd->header_track, cd->header_sector); + if ((abs_sect < 0) || (move_window(abs_sect) != FR_OK)) { + delete d; + return FR_DISK_ERR; + } + header = sect_buffer + 4; // as get_volume_name() reads it for a subdirectory + } + // Sixteen characters of name, padded with shifted spaces, then a shifted space, the + // two character id, a shifted space and the two character DOS version. + for (int i = 0; i < 16; i++) { + header[i] = 0xA0; + } + for (int i = 0; (i < 16) && name[i]; i++) { + header[i] = (uint8_t)toupper(name[i]); + } + if (id && *id) { + header[18] = 0xA0; + header[19] = 0xA0; + for (int i = 0; (i < 2) && id[i]; i++) { + header[18 + i] = (uint8_t)toupper(id[i]); + } + } + if (cd->root) { + root_dirty = true; + } else { + dirty = 1; + } + delete d; + return sync(); +} + // Creates subdirectory FRESULT FileSystemCBM::dir_create(const char *path) { diff --git a/software/filesystem/filesystem_d64.h b/software/filesystem/filesystem_d64.h index 4e347e492..dc49d1ad8 100644 --- a/software/filesystem/filesystem_d64.h +++ b/software/filesystem/filesystem_d64.h @@ -218,6 +218,7 @@ class FileSystemCBM : public FileSystem // functions for reading directories FRESULT dir_open(const char *path, Directory **); // Opens directory (creates dir object) FRESULT dir_create(const char *path); + FRESULT dir_set_label(const char *path, const char *name, const char *id); // functions for reading and writing files FRESULT file_open(const char *filename, uint8_t flags, File **); // Opens file (creates file object) diff --git a/software/io/iec/cbmdos_parser.cc b/software/io/iec/cbmdos_parser.cc index fd6c4b871..4bea0e83e 100644 --- a/software/io/iec/cbmdos_parser.cc +++ b/software/io/iec/cbmdos_parser.cc @@ -36,10 +36,9 @@ // T-RI -> "YYYY-MM-DDThh:mm:ss dow\r" // T-RD -> "{WD}{Y}{M}{D}{h}{m}{s}{am/pm}\r" Documentation says it's decimal, but it is actually binary h in 12 hour format, Y+1900 // T-RB -> "{WD}{Y}{M}{D}{h}{m}{s}{am/pm}\r" BCD format Y<80:+2000, else+1900, also 12 hour format for some strange reason -// T-WA -> not supported, as the RTC is not part of the drive, but of the system -// T-WI -> not supported, as the RTC is not part of the drive, but of the system -// T-WD -> not supported, as the RTC is not part of the drive, but of the system -// T-WB -> not supported, as the RTC is not part of the drive, but of the system +// T-WA, T-WB, T-WD, T-WI -> set the system clock from the same layout the matching +// read answers with. The day of week is taken from the command except for the ISO +// form, which has none and derives it from the date. // Directories // $ [=T] [[n][path]:] [= commalist([TP|OPTION])], OPTION = { L, N, stamp }, stamp = MM/DD/YY HH:MM xM, x = {A | P} @@ -52,12 +51,27 @@ // methods should work. #include "cbmdos_parser.h" +#include "current_time.h" + +// A build with no real time clock driver, which is every host test build, keeps the +// clock in memory so that the clock commands can still be exercised end to end. +static int clock_wd = 3, clock_year = 2025, clock_month = 6, clock_day = 26; +static int clock_hour = 0, clock_min = 41, clock_sec = 1; extern "C" { void get_current_time(int& wd, int& year, int& month, int& day, int& hour, int& min, int& sec) __attribute__((weak)); void get_current_time(int& wd, int& year, int& month, int& day, int& hour, int& min, int& sec) { - wd = 3; year = 2025; month = 6; day = 26; hour = 0; min = 41; sec = 1; + wd = clock_wd; year = clock_year; month = clock_month; day = clock_day; + hour = clock_hour; min = clock_min; sec = clock_sec; + } + + bool set_current_time(int wd, int year, int month, int day, int hour, int min, int sec) __attribute__((weak)); + bool set_current_time(int wd, int year, int month, int day, int hour, int min, int sec) + { + clock_wd = wd; clock_year = year; clock_month = month; clock_day = day; + clock_hour = hour; clock_min = min; clock_sec = sec; + return true; } } int parse_full_path(const char *buf, filename_t& name, bool *replace = NULL, bool path_only = false) @@ -546,6 +560,51 @@ int IecParser :: rename_command(const uint8_t *buffer, int len) return exec->do_rename(src, dest); } +// R-P:newname=oldname renames a partition and R-H[n][path]:newname[,id] renames the +// header of a directory (SI-051, SI-064). SD parse_doscommand() finds both the same +// way, by the dash in the second character, before it falls through to a file rename. +int IecParser :: rename_dashed_command(const uint8_t *buffer, int len) +{ + mstring cmd((const char *)buffer, 3, len-1); + switch (buffer[2]) { + case 'P': { + const char *rest; + if (!cmd.split('=', &rest)) { + return ERR_SYNTAX; + } + const char *newname = cmd.c_str(); + if (*newname == ':') { + newname++; + } + if (!*newname || !*rest) { + return ERR_NO_NAME; + } + return exec->do_rename_partition(newname, rest); + } + case 'H': { + filename_t dest; + int err = parse_full_path(cmd.c_str(), dest, NULL, false); + if (err) { + return err; + } + const char *id = ""; + const char *rest; + if (dest.filename.split(',', &rest)) { + id = rest; + } + if (dest.filename.length() == 0) { + return ERR_NO_NAME; + } + if (dest.filename.contains_any("?*")) { + return ERR_ILLEGAL_NAME; + } + return exec->do_set_header(dest, id); + } + default: + return ERR_SYNTAX; + } +} + int IecParser :: scratch_command(const uint8_t *buffer, int len) { while(isalpha(*buffer)) { @@ -565,6 +624,20 @@ int IecParser :: scratch_command(const uint8_t *buffer, int len) return exec->do_scratch(filenames, n); } +// S-8, S-9 and S-D, exactly three characters, change the device number to 8, to 9 and +// back to the configured one (SI-101, HD 9-34). On a CMD device they swap the drive the +// number addresses; here there is one drive, so they move that drive's number. Any other +// name after the S is a scratch, so a file named "-8" is scratched as S:-8. +int IecParser :: swap_command(const uint8_t *buffer, int len) +{ + switch (buffer[2]) { + case '8': return exec->do_set_device_number(8); + case '9': return exec->do_set_device_number(9); + case 'D': return exec->do_restore_device_number(); + default: return ERR_SYNTAX; // S is a command letter, its argument is not (SI-030) + } +} + // L[n][path]:name toggles the lock of one file or directory (SI-076, HD 9-30). int IecParser :: lock_command(const uint8_t *buffer, int len) { @@ -613,10 +686,198 @@ static uint8_t bcdbyte(int a) return r; } +// The day of week names a clock answer carries, which a clock write is also matched +// against, so the two cannot name the days differently. +static const char *const c_weekday_4[] = { "SUN.", "MON.", "TUES", "WED.", "THUR", "FRI.", "SAT." }; +static const char *const c_weekday_3[] = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" }; + +// The clock chip holds two BCD digits of year counted from 1980, so a write outside +// that century is refused rather than wrapped. +#define CLOCK_FIRST_YEAR 1980 +#define CLOCK_LAST_YEAR 2079 + +// The time a clock write carries, before it is checked. +typedef struct { + int wd, year, month, day, hour, min, sec; +} clock_time_t; + +// A field of decimal digits at a fixed place in a clock command, or -1 when it is not +// digits. The formats place every field and every separator at a fixed offset, and the +// A format's AM or PM marker is at a fixed offset even in SD parse_timewrite(), so a +// field of another width could not be read consistently and is refused. +static int clock_field(const uint8_t *p, int digits) +{ + int value = 0; + for (int i = 0; i < digits; i++) { + if (!isdigit(p[i])) { + return -1; + } + value = (value * 10) + (p[i] - '0'); + } + return value; +} + +static int clock_bcd(uint8_t b) +{ + if (((b & 0x0F) > 9) || ((b >> 4) > 9)) { + return -1; + } + return ((b >> 4) * 10) + (b & 0x0F); +} + +// A two digit year is in this century below 80 and in the last one from 80, which is +// the Y2K rule of SD parse_timewrite(). +static int clock_year_of(int two_digit) +{ + return (two_digit < 80) ? (2000 + two_digit) : (1900 + two_digit); +} + +static int clock_days_in_month(int year, int month) +{ + static const int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + if ((month == 2) && (((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0)))) { + return 29; + } + return days[month - 1]; +} + +// The day of week of a date, 0 for Sunday, by the method SD parse_timewrite() uses for +// the ISO form, which is the one form that carries no day of week. +static int clock_day_of_week(int year, int month, int day) +{ + int y = year; + int d = day + ((month < 3) ? y-- : (y - 2)); + return ((23 * month / 9) + d + 4 + (y / 4) - (y / 100) + (y / 400)) % 7; +} + +static bool clock_time_valid(const clock_time_t& t) +{ + return (t.year >= CLOCK_FIRST_YEAR) && (t.year <= CLOCK_LAST_YEAR) && + (t.month >= 1) && (t.month <= 12) && + (t.day >= 1) && (t.day <= clock_days_in_month(t.year, t.month)) && + (t.wd >= 0) && (t.wd <= 6) && + (t.hour >= 0) && (t.hour <= 23) && + (t.min >= 0) && (t.min <= 59) && + (t.sec >= 0) && (t.sec <= 59); +} + +// T-W in the four forms of SI-120, each laid out exactly as the matching T-R answers +// it. The A, B and D forms carry the day of week and it is stored as sent, as a CMD +// drive stores it; the I form has none and it is derived from the date. +static int parse_clock_write(const uint8_t *buffer, int len, clock_time_t& t) +{ + const uint8_t *p = buffer + 4; + int hour12, year2; + + switch (buffer[3]) { + case 'A': + // "dow. mo/da/yr hr:mi:se xM", with the marker and the space before it optional. + if (len < 26) { + return ERR_SYNTAX; + } + for (t.wd = 0; t.wd < 7; t.wd++) { + if (memcmp(p, c_weekday_4[t.wd], 2) == 0) { + break; + } + } + if ((t.wd == 7) || (p[4] != ' ') || (p[7] != '/') || (p[10] != '/') || + (p[13] != ' ') || (p[16] != ':') || (p[19] != ':')) { + return ERR_SYNTAX; + } + t.month = clock_field(p + 5, 2); + t.day = clock_field(p + 8, 2); + year2 = clock_field(p + 11, 2); + t.hour = clock_field(p + 14, 2); + t.min = clock_field(p + 17, 2); + t.sec = clock_field(p + 20, 2); + if ((t.month < 0) || (t.day < 0) || (year2 < 0) || + (t.hour < 0) || (t.min < 0) || (t.sec < 0)) { + return ERR_SYNTAX; + } + t.year = clock_year_of(year2); + // Without the marker the hour is already a 24 hour time. + if ((len >= 29) && (p[22] == ' ') && (p[24] == 'M')) { + if (t.hour == 12) { + t.hour = 0; + } + if (p[23] == 'P') { + t.hour += 12; + } else if (p[23] != 'A') { + return ERR_SYNTAX; + } + } + break; + + case 'B': + case 'D': + // wd, year, month, day, hour in 12 hour form, minute, second, PM flag. The + // fields are BCD for B and binary for D, and none of them is a terminator. + if (len < 12) { + return ERR_SYNTAX; + } + if (buffer[3] == 'B') { + t.wd = clock_bcd(p[0]); + year2 = clock_bcd(p[1]); + t.month = clock_bcd(p[2]); + t.day = clock_bcd(p[3]); + hour12 = clock_bcd(p[4]); + t.min = clock_bcd(p[5]); + t.sec = clock_bcd(p[6]); + } else { + t.wd = (int)p[0]; + year2 = (int)p[1]; + t.month = (int)p[2]; + t.day = (int)p[3]; + hour12 = (int)p[4]; + t.min = (int)p[5]; + t.sec = (int)p[6]; + } + if ((year2 < 0) || (hour12 < 0)) { + return ERR_SYNTAX; + } + t.year = clock_year_of(year2); + // A twelve in the hour field is midnight or noon, and the flag adds the half day. + t.hour = (hour12 == 12) ? 0 : hour12; + if (p[7]) { + t.hour += 12; + } + break; + + case 'I': + // "YYYY-MM-DDThh:mm:ss", with the day of week a T-RI answer ends in ignored. + if (len < 23) { + return ERR_SYNTAX; + } + if ((p[4] != '-') || (p[7] != '-') || (p[10] != 'T') || (p[13] != ':') || (p[16] != ':')) { + return ERR_SYNTAX; + } + t.year = clock_field(p, 4); + t.month = clock_field(p + 5, 2); + t.day = clock_field(p + 8, 2); + t.hour = clock_field(p + 11, 2); + t.min = clock_field(p + 14, 2); + t.sec = clock_field(p + 17, 2); + if ((t.year < CLOCK_FIRST_YEAR) || (t.year > CLOCK_LAST_YEAR) || + (t.month < 1) || (t.month > 12)) { + return ERR_SYNTAX; + } + t.wd = clock_day_of_week(t.year, t.month, t.day); + break; + + default: + return ERR_SYNTAX; + } + + if (!clock_time_valid(t)) { + return ERR_SYNTAX; + } + return 0; +} + int IecParser :: time_command(const uint8_t *buffer, int len) { - const char *wd4[] = { "SUN.", "MON.", "TUES", "WED.", "THUR", "FRI.", "SAT." }; - const char *wd3[] = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" }; + const char *const *wd4 = c_weekday_4; + const char *const *wd3 = c_weekday_3; uint8_t result[32]; if (buffer[1] != '-') { @@ -676,8 +937,22 @@ int IecParser :: time_command(const uint8_t *buffer, int len) } return exec->do_cmd_response(result, reslen); break; - case 'W': - return ERR_SYNTAX; // the clock belongs to the system, and answering OK would not set it (SI-120) + case 'W': { + // The clock the drive answers with is the system clock, so a write sets that one + // and a read of it through any other interface sees the same moment (SI-120). + clock_time_t t; + if (len < 4) { + return ERR_SYNTAX; + } + int err = parse_clock_write(buffer, len, t); + if (err) { + return err; + } + if (!set_current_time(t.wd, t.year, t.month, t.day, t.hour, t.min, t.sec)) { + return ERR_SYNTAX; // nothing was set, so nothing may answer OK + } + return 0; + } } return ERR_SYNTAX; } @@ -798,10 +1073,13 @@ int IecParser :: execute_command(const uint8_t *buffer, int len) if (buffer[1] == 'D') { return dir_command(buffer, len); } + if ((len > 2) && (buffer[1] == '-')) { + return rename_dashed_command(buffer, len); + } return rename_command(buffer, len); case 'S': if ((len == 3) && (buffer[1] == '-')) { - return ERR_UNKNOWN_CMD; // S-8, S-9 and S-D swap device numbers, which this drive does not do (SD parse_doscommand()) + return swap_command(buffer, len); } return scratch_command(buffer, len); case 'T': return time_command(buffer, len); diff --git a/software/io/iec/cbmdos_parser.h b/software/io/iec/cbmdos_parser.h index bbb6b3384..88225456f 100644 --- a/software/io/iec/cbmdos_parser.h +++ b/software/io/iec/cbmdos_parser.h @@ -103,7 +103,12 @@ class IecCommandExecuter virtual int do_pwd_command() { return 0; } virtual int do_get_partition_info(int part) { return 0; } virtual int do_set_device_number(int dev) { return 0; } + virtual int do_restore_device_number() { return 0; } // S-D, back to the configured number virtual int do_lock(filename_t& name) { return 0; } // L: toggles the lock of one entry + // R-H sets the header of the directory the name's path points at, and R-P renames + // the partition that carries a name (SI-064, SI-051). + virtual int do_set_header(filename_t& dest, const char *id) { return 0; } + virtual int do_rename_partition(const char *newname, const char *oldname) { return 0; } }; class IecParser @@ -125,6 +130,8 @@ class IecParser int get_command(const uint8_t *buffer, int len); int memory_command(const uint8_t *buffer, int len); int lock_command(const uint8_t *buffer, int len); + int swap_command(const uint8_t *buffer, int len); + int rename_dashed_command(const uint8_t *buffer, int len); public: IecParser(IecCommandExecuter *e) : exec(e) { } diff --git a/software/io/iec/cbmdos_parser_test.cc b/software/io/iec/cbmdos_parser_test.cc index 4122f9929..83e3c1574 100644 --- a/software/io/iec/cbmdos_parser_test.cc +++ b/software/io/iec/cbmdos_parser_test.cc @@ -306,10 +306,30 @@ void test_dispatch_text(const char *cmd, int len, int exp_retval, const char *wh // them before it falls through to rename and scratch. void test_added_commands(void) { - // S-8, S-9 and S-D swap device numbers, which this drive does not do; they are not a - // scratch of a file called -8 (SD parse_doscommand()). - test_dispatch("S-8", 3, 31, NULL); - test_dispatch("S-D\r", 4, 31, NULL); + // SI-101: S-8, S-9 and S-D move the device number to 8, to 9 and back to the + // configured one. Exactly three characters, so S:-8 is still a scratch of "-8" + // (SD parse_doscommand()). + test_dispatch("S-8", 3, 0, "device number", 8); + test_dispatch("S-9\r", 4, 0, "device number", 9); + test_dispatch("S-D\r", 4, 0, "restore device number"); + test_dispatch("S-C", 3, ERR_SYNTAX, NULL); // the SCSI pass-through, out of scope (SI-106) + test_dispatch_text("S:-8", 4, 0, "scratch", "-1||-8", 1); + test_dispatch_text("S-88", 4, 0, "scratch", "-1||-88", 1); + // SI-051 and SI-064: the dash after the R finds the partition rename and the header + // rename before a file rename (SD parse_doscommand()). + test_dispatch_text("R-P:NEW=OLD", 11, 0, "rename partition", "NEW|OLD"); + test_dispatch_text("R-P:NEW=OLD\r", 12, 0, "rename partition", "NEW|OLD"); + test_dispatch("R-P:NEW", 7, ERR_SYNTAX, NULL); + test_dispatch("R-P:=OLD", 8, ERR_NO_NAME, NULL); + test_dispatch("R-P:NEW=", 8, ERR_NO_NAME, NULL); + test_dispatch_text("R-H:NAME", 8, 0, "set header", "-1||NAME|"); + test_dispatch_text("R-H3//GAMES/:NAME,ID", 20, 0, "set header", "3|//GAMES/|NAME|ID"); + test_dispatch("R-H:", 4, ERR_NO_NAME, NULL); + test_dispatch("R-H:N*", 6, ERR_ILLEGAL_NAME, NULL); + test_dispatch("R-X:NAME", 8, ERR_SYNTAX, NULL); + // A file rename still reaches the file rename. + test_dispatch("R:NEW=OLD", 9, 0, NULL); + // SI-100: U0> followed by the device number as a byte. test_dispatch("U0>\x0C", 4, 0, "device number", 12); test_dispatch("U0>\x1E\r", 5, 0, "device number", 30); @@ -331,9 +351,10 @@ void test_added_commands(void) test_dispatch("M-W\x00\x05\x01\xEA", 7, 30, NULL); test_dispatch("M-E\x00\x05", 5, 30, NULL); test_dispatch("M-X", 3, 30, NULL); - // SI-120: the clock belongs to the system, so T-W answers 30 rather than an OK that - // would set nothing. - test_dispatch("T-WI2026-09-12T13:02:03", 23, 30, NULL); + // SI-120: T-W sets the system clock, and a form the clock cannot hold answers 30. + // The four formats are checked in test_clock_commands(). + test_dispatch("T-WI2026-09-12T13:02:03", 23, 0, NULL); + test_dispatch("T-WI2026-13-12T13:02:03", 23, 30, NULL); test_dispatch("MD:DIR", 6, 0, NULL); // still a directory command } @@ -420,6 +441,145 @@ void test_lock_command(void) test_dispatch("L:", 2, 34, NULL); } +// Sends a command and compares the bytes it answered with, so a clock write can be +// checked by reading the clock back through each of the four read forms. +static void test_reply(const char *cmd, int len, int exp_retval, const char *label, + const uint8_t *expected, int exp_len) +{ + last_stub_call.command = NULL; + last_stub_call.reply_len = 0; + int retval = parser.execute_command((const uint8_t *)cmd, len); + bool ok = (retval == exp_retval) && (last_stub_call.reply_len == exp_len) && + (memcmp(last_stub_call.reply, expected, exp_len) == 0); + if (ok) { + printf("Reply '%s' => OK!\n", label); + return; + } + printf("Reply '%s' returned %d (expected %d) and answered %d bytes:\n", + label, retval, exp_retval, last_stub_call.reply_len); + dump_hex(last_stub_call.reply, last_stub_call.reply_len); + printf(" expected %d bytes:\n", exp_len); + dump_hex(expected, exp_len); + failures++; +} + +static void test_reply_text(const char *cmd, int len, const char *label, const char *expected) +{ + test_reply(cmd, len, 0, label, (const uint8_t *)expected, strlen(expected)); +} + +// SI-120. The four write forms set the system clock, and the four read forms then +// answer with the time that was written. The formats and the validation follow +// SD parse_timewrite(): the day of week is taken from the command for A, B and D and +// derived from the date for I, a twelve hour field of 12 means midnight or noon, and a +// year below 80 is in this century. +void test_clock_commands(void) +{ + // 2026-09-12 13:02:03, a Saturday, written in each of the four forms and read back + // in each of the four forms. + static const uint8_t t_rd[] = { 6, 126, 9, 12, 1, 2, 3, 1, 0x0d }; + static const uint8_t t_rb[] = { 6, 0x26, 0x09, 0x12, 0x01, 0x02, 0x03, 1, 0x0d }; + static const uint8_t t_wd[] = { 'T','-','W','D', 6, 126, 9, 12, 1, 2, 3, 1 }; + static const uint8_t t_wb[] = { 'T','-','W','B', 6, 0x26, 0x09, 0x12, 0x01, 0x02, 0x03, 1 }; + const char *iso = "2026-09-12T13:02:03 SAT\r"; + const char *ascii = "SAT. 09/12/26 01:02:03 PM\r"; + // Written between two checks, so that the next write has something to change. + const char *elsewhere = "T-WI1999-01-01T01:01:01"; + + test_dispatch("T-WI2026-09-12T13:02:03", 23, 0, NULL); + test_reply_text("T-RI", 4, "T-WI then T-RI", iso); + test_reply_text("T-RA", 4, "T-WI then T-RA", ascii); + test_reply("T-RD", 4, 0, "T-WI then T-RD", t_rd, sizeof(t_rd)); + test_reply("T-RB", 4, 0, "T-WI then T-RB", t_rb, sizeof(t_rb)); + + // The ISO form derives the day of week from the date, so the three characters a + // T-RI answer ends in are accepted and ignored when they are sent back. + test_dispatch(elsewhere, 23, 0, NULL); + test_dispatch("T-WI2026-09-12T13:02:03 SAT\r", 28, 0, NULL); + test_reply_text("T-RI", 4, "a T-RI answer sent back", iso); + + // Each of the other three forms writes the same moment. + test_dispatch(elsewhere, 23, 0, NULL); + test_dispatch("T-WA" "SAT. 09/12/26 01:02:03 PM", 29, 0, NULL); + test_reply_text("T-RI", 4, "T-WA then T-RI", iso); + + test_dispatch(elsewhere, 23, 0, NULL); + test_dispatch((const char *)t_wd, sizeof(t_wd), 0, NULL); + test_reply_text("T-RI", 4, "T-WD then T-RI", iso); + + test_dispatch(elsewhere, 23, 0, NULL); + test_dispatch((const char *)t_wb, sizeof(t_wb), 0, NULL); + test_reply_text("T-RI", 4, "T-WB then T-RI", iso); + + // The terminator BASIC appends is dropped, and a 13 inside the binary data is data: + // 11:13:13 on Sunday 13 September 2026 in the decimal form, sent with a terminator. + static const uint8_t t_wd13[] = { 'T','-','W','D', 0, 126, 9, 13, 11, 13, 13, 0, 0x0d }; + test_dispatch((const char *)t_wd13, sizeof(t_wd13), 0, NULL); + test_reply_text("T-RI", 4, "a 13 inside the data", "2026-09-13T11:13:13 SUN\r"); + + // The day of week of the A, B and D forms is the one the command carries, as on a + // CMD drive, which stores it without checking it against the date. + static const uint8_t t_wd_dow[] = { 'T','-','W','D', 0, 126, 9, 12, 1, 2, 3, 1 }; + test_dispatch((const char *)t_wd_dow, sizeof(t_wd_dow), 0, NULL); + test_reply_text("T-RI", 4, "the day of week the command carries", "2026-09-12T13:02:03 SUN\r"); + + // The leap day of a leap year is a date; the same day in 2021 is not, and a refused + // write leaves the clock alone. + test_dispatch("T-WI2020-02-29T00:00:00", 23, 0, NULL); + test_reply_text("T-RI", 4, "the leap day of 2020", "2020-02-29T00:00:00 SAT\r"); + test_dispatch("T-WI2021-02-29T00:00:00", 23, ERR_SYNTAX, NULL); + test_reply_text("T-RI", 4, "the clock after a refused write", "2020-02-29T00:00:00 SAT\r"); + + // The ranges a write refuses, each of which would otherwise reach the clock chip. + test_dispatch("T-WI2026-13-01T00:00:00", 23, ERR_SYNTAX, NULL); + test_dispatch("T-WI2026-00-01T00:00:00", 23, ERR_SYNTAX, NULL); + test_dispatch("T-WI2026-04-31T00:00:00", 23, ERR_SYNTAX, NULL); + test_dispatch("T-WI2026-09-00T00:00:00", 23, ERR_SYNTAX, NULL); + test_dispatch("T-WI2026-09-12T24:00:00", 23, ERR_SYNTAX, NULL); + test_dispatch("T-WI2026-09-12T00:60:00", 23, ERR_SYNTAX, NULL); + test_dispatch("T-WI2026-09-12T00:00:60", 23, ERR_SYNTAX, NULL); + // The clock chip holds two digits of year from 1980, so nothing outside that. + test_dispatch("T-WI1979-12-31T23:59:59", 23, ERR_SYNTAX, NULL); + test_dispatch("T-WI2080-01-01T00:00:00", 23, ERR_SYNTAX, NULL); + // A day of week of 7, and a BCD field whose low nibble is not a digit. + static const uint8_t t_wd_bad_dow[] = { 'T','-','W','D', 7, 126, 9, 12, 1, 2, 3, 1 }; + test_dispatch((const char *)t_wd_bad_dow, sizeof(t_wd_bad_dow), ERR_SYNTAX, NULL); + static const uint8_t t_wb_bad_bcd[] = { 'T','-','W','B', 6, 0x26, 0x0A, 0x12, 0x01, 0x02, 0x03, 1 }; + test_dispatch((const char *)t_wb_bad_bcd, sizeof(t_wb_bad_bcd), ERR_SYNTAX, NULL); + // A command that stops before the last field it needs. + test_dispatch("T-WI2026-09-12T13:02", 20, ERR_SYNTAX, NULL); + test_dispatch("T-WA" "SAT. 09/12/26 01:02", 23, ERR_SYNTAX, NULL); + static const uint8_t t_wd_short[] = { 'T','-','W','D', 6, 126, 9, 12, 1, 2, 3 }; + test_dispatch((const char *)t_wd_short, sizeof(t_wd_short), ERR_SYNTAX, NULL); + // A day of week name no drive prints, and a field that is not a number. + test_dispatch("T-WA" "XYZ. 09/12/26 01:02:03 PM", 29, ERR_SYNTAX, NULL); + test_dispatch("T-WI2026-XX-12T13:02:03", 23, ERR_SYNTAX, NULL); + // An unknown format letter, as for a read (SI-030). + test_dispatch("T-WX", 4, ERR_SYNTAX, NULL); + test_dispatch("T-W", 3, ERR_SYNTAX, NULL); + + // The ASCII form without its AM or PM marker is a 24 hour time, and a twelve hour + // field of 12 with the marker is midnight or noon (SD parse_timewrite()). + test_dispatch(elsewhere, 23, 0, NULL); + test_dispatch("T-WA" "SAT. 09/12/26 13:02:03", 26, 0, NULL); + test_reply_text("T-RI", 4, "an ASCII write without a marker", iso); + test_dispatch("T-WA" "SAT. 09/12/26 12:02:03 AM", 29, 0, NULL); + test_reply_text("T-RI", 4, "twelve AM is midnight", "2026-09-12T00:02:03 SAT\r"); + test_dispatch("T-WA" "SAT. 09/12/26 12:02:03 PM", 29, 0, NULL); + test_reply_text("T-RI", 4, "twelve PM is noon", "2026-09-12T12:02:03 SAT\r"); + + // A year below 80 is in this century, as the Y2K fix in SD parse_timewrite() has it. + static const uint8_t t_wd_y2k[] = { 'T','-','W','D', 5, 5, 3, 4, 2, 0, 0, 0 }; + test_dispatch((const char *)t_wd_y2k, sizeof(t_wd_y2k), 0, NULL); + test_reply_text("T-RI", 4, "a year below 80 is this century", "2005-03-04T02:00:00 FRI\r"); + + // Leave the clock where the rest of the suite expects it, which is a day of week + // the date does not have, so it has to be written in a form that carries one. + static const uint8_t t_wd_restore[] = { 'T','-','W','D', 3, 125, 6, 26, 12, 41, 1, 0 }; + test_dispatch((const char *)t_wd_restore, sizeof(t_wd_restore), 0, NULL); + test_reply_text("T-RI", 4, "the clock the rest of the suite reads", "2025-06-26T00:41:01 WED\r"); +} + // B-P positions within the 256 byte buffer; a third number is ignored, as the ROM ignores it. // SI-094: B-R and B-W use the first byte of the block as a length, U1 and U2 do not. void test_block_positions_and_lengths(void) @@ -850,6 +1010,7 @@ int main(int argc, const char *argv[]) test_md_rd_grammar(); test_name_mapping(); test_lock_command(); + test_clock_commands(); test_block_positions_and_lengths(); test_command(34, (const uint8_t *)"C99:EMPTY=", 10); test_command( 0, (const uint8_t *)"C1:FCOPY=3:FCOPY", 16); diff --git a/software/io/iec/cbmdos_stubs.cc b/software/io/iec/cbmdos_stubs.cc index ec01df41b..68a469c7c 100644 --- a/software/io/iec/cbmdos_stubs.cc +++ b/software/io/iec/cbmdos_stubs.cc @@ -10,9 +10,11 @@ typedef struct { const char *command; int a, b, c, d; char text[96]; // the names a command carried, where it carried any + uint8_t reply[64]; // the bytes a command answered with + int reply_len; } stub_call_t; -stub_call_t last_stub_call = { NULL, 0, 0, 0, 0, "" }; +stub_call_t last_stub_call = { NULL, 0, 0, 0, 0, "", { 0 }, 0 }; static void record_stub_call(const char *command, int a = 0, int b = 0, int c = 0, int d = 0) { @@ -22,6 +24,7 @@ static void record_stub_call(const char *command, int a = 0, int b = 0, int c = last_stub_call.c = c; last_stub_call.d = d; last_stub_call.text[0] = 0; + last_stub_call.reply_len = 0; } // A file name as partition, path and name, for a test to compare as one string. @@ -54,6 +57,9 @@ class IecCommandExecuterStubs : public IecCommandExecuter int do_pwd_command(); int do_get_partition_info(int part); int do_set_device_number(int dev); + int do_restore_device_number(); + int do_set_header(filename_t& dest, const char *id); + int do_rename_partition(const char *newname, const char *oldname); int do_lock(filename_t& name); }; @@ -161,6 +167,8 @@ int IecCommandExecuterStubs::do_rename(filename_t &src, filename_t &dest) int IecCommandExecuterStubs::do_scratch(filename_t filenames[], int n) { + record_stub_call("scratch", n); + record_stub_name(filenames[0]); printf("Scratch %d files:\n", n); for(int i=0;iset_error(ERR_DIRECTORY_ERROR, drive->vfs->GetTargetPartitionNumber(name.partition), 0); + return 0; + } + fres = fm->set_dir_label(work.c_str(), name.filename.c_str(), id); + if (fres != FR_NOT_ENABLED) { + if (fres != FR_OK) { + drive->set_error_fres(fres); + } + return 0; + } + + // No label of its own: the name the parent holds is the header. + const char *rel = relative.c_str(); + int rel_len = strlen(rel); + while ((rel_len > 0) && (rel[rel_len - 1] == '/')) { + rel_len--; + } + if (rel_len == 0) { + partition->SetName(name.filename.c_str()); + return 0; + } + char fat_name[52]; + petscii_to_fat(name.filename.c_str(), fat_name, sizeof(fat_name)); + mstring renamed; + int cut = strlen(work.c_str()); + while ((cut > 0) && (work[cut - 1] == '/')) { + cut--; + } + while ((cut > 0) && (work[cut - 1] != '/')) { + cut--; + } + renamed.copy(work.c_str(), 0, cut - 1); + append_path_component(renamed, fat_name); + fres = fm->rename(work.c_str(), renamed.c_str()); + if (fres != FR_OK) { + drive->set_error_fres(fres); + return 0; + } + + // The drive may be standing in the directory it renamed, or below it, so its current + // directory follows the new name. + int start = rel_len; + while ((start > 0) && (rel[start - 1] != '/')) { + start--; + } + mstring current(partition->GetRelativePath()); + if (!strncasecmp(current.c_str(), rel, rel_len) && + ((current[rel_len] == 0) || (current[rel_len] == '/'))) { + mstring moved; + moved.copy(rel, 0, start - 1); + moved += fat_name; + moved += current.c_str() + rel_len; + if (!partition->cd(moved.c_str())) { + partition->cd("/"); + } + } + return 0; +} + +// R-P (SI-051). The old name is the name a partition carries, not a path, so the +// partition list is searched for it. +int IecCommandChannel::do_rename_partition(const char *newname, const char *oldname) +{ + for (int i = 1; i < MAX_PARTITIONS; i++) { + IecPartition *p = drive->vfs->GetPartition(i); + if (p && (p->GetPartitionNumber() == i) && !strcasecmp(p->GetName(), oldname)) { + p->SetName(newname); + return 0; + } + } + return ERR_PARTITION_ERROR; +} + // U0> (SI-100). The drive answers this command on the number it was addressed on and // every later one on the new number. int IecCommandChannel::do_set_device_number(int dev) @@ -2712,6 +2795,12 @@ int IecCommandChannel::do_set_device_number(int dev) return 0; } +int IecCommandChannel::do_restore_device_number() +{ + drive->set_device_number(drive->configured_device_number()); + return 0; +} + int IecCommandChannel::ext_open_file(const char *filenameOrCommand) { strncpy((char *) wr_buffer, filenameOrCommand, CBMDOS_COMMAND_BUFFER_SIZE - 1); diff --git a/software/io/iec/iec_channel.h b/software/io/iec/iec_channel.h index 9847d950b..8f2a7817b 100644 --- a/software/io/iec/iec_channel.h +++ b/software/io/iec/iec_channel.h @@ -424,7 +424,10 @@ class IecCommandChannel: public IecChannel, public IecCommandExecuter { int do_pwd_command(); int do_get_partition_info(int part); int do_set_device_number(int dev); + int do_restore_device_number(); int do_lock(filename_t& name); + int do_set_header(filename_t& dest, const char *id); + int do_rename_partition(const char *newname, const char *oldname); public: IecCommandChannel(IecDrive *dr, int ch); virtual ~IecCommandChannel(); diff --git a/software/io/iec/iec_drive.cc b/software/io/iec/iec_drive.cc index 5a84230f6..3ac6858aa 100644 --- a/software/io/iec/iec_drive.cc +++ b/software/io/iec/iec_drive.cc @@ -407,6 +407,12 @@ bool IecDrive :: log_every_operation(void) return cfg->get_value(CFG_IEC_LOG) > 0; } +// The device number the settings hold, which S-D returns the drive to (SI-101). +int IecDrive :: configured_device_number(void) +{ + return cfg->get_value(CFG_IEC_BUS_ID); +} + // The device number for as long as the drive runs, from U0> (SI-100). It is not written to // the configuration: HD 9-49 describes the change as temporary. void IecDrive :: set_device_number(int dev) diff --git a/software/io/iec/iec_drive.h b/software/io/iec/iec_drive.h index 8d9eaa1d8..6968e818c 100644 --- a/software/io/iec/iec_drive.h +++ b/software/io/iec/iec_drive.h @@ -94,6 +94,7 @@ class IecDrive : public IecSlave, SubSystem, ObjectWithMenu, ConfigurableObject // Local Functions void set_device_number(int dev); + int configured_device_number(void); bool log_every_operation(void); void set_error(int err, int track, int sector); void set_error_fres(FRESULT fres); diff --git a/software/io/rtc/current_time.h b/software/io/rtc/current_time.h new file mode 100644 index 000000000..22acc707c --- /dev/null +++ b/software/io/rtc/current_time.h @@ -0,0 +1,18 @@ +#ifndef CURRENT_TIME_H +#define CURRENT_TIME_H + +// The system clock as local calendar time, for code that has no business knowing which +// clock chip is fitted. Each real time clock driver defines both functions; a build +// without one keeps the clock in memory. +// +// The year is a calendar year and the day of week is 0 for Sunday. set_current_time() +// stores the day of week it is given rather than deriving it, because the DOS clock +// commands and the control interface both carry one, and it answers false when the +// clock could not be set. + +extern "C" { + void get_current_time(int& wd, int& year, int& month, int& day, int& hour, int& min, int& sec); + bool set_current_time(int wd, int year, int month, int day, int hour, int min, int sec); +} + +#endif /* CURRENT_TIME_H */ diff --git a/software/io/rtc/rtc.cc b/software/io/rtc/rtc.cc index c53d993a3..1d116f5cb 100644 --- a/software/io/rtc/rtc.cc +++ b/software/io/rtc/rtc.cc @@ -1,5 +1,6 @@ #include "rtc.h" #include "rtc_epoch.h" +#include "current_time.h" #include #include #include @@ -423,5 +424,14 @@ extern "C" void get_current_time(int& wd, int& year, int& month, int& day, int& year += RTC_EPOCH_YEAR; // get_time() counts years from the epoch, callers do not } +extern "C" bool set_current_time(int wd, int year, int month, int day, int hour, int min, int sec) +{ + int y = year - RTC_EPOCH_YEAR; + int corr = rtc.get_correction(); + rtc.set_time(y, month, day, wd, hour, min, sec); + rtc.set_time_in_chip(corr, y, month, day, wd, hour, min, sec); + return true; +} + #include "init_function.h" InitFunction init_rtc("RTC", [](void *_obj, void *_param) { rtc.init(); }, NULL, NULL, 2); diff --git a/software/io/rtc/rtc_dummy.cc b/software/io/rtc/rtc_dummy.cc index 9b25effe2..6288599bd 100644 --- a/software/io/rtc/rtc_dummy.cc +++ b/software/io/rtc/rtc_dummy.cc @@ -1,5 +1,6 @@ #include "rtc_dummy.h" #include "rtc_epoch.h" +#include "current_time.h" #include #include #include @@ -127,3 +128,12 @@ extern "C" void get_current_time(int& wd, int& year, int& month, int& day, int& rtc.get_time(year, month, day, wd, hour, min, sec); year += RTC_EPOCH_YEAR; // get_time() counts years from the epoch, callers do not } + +extern "C" bool set_current_time(int wd, int year, int month, int day, int hour, int min, int sec) +{ + int y = year - RTC_EPOCH_YEAR; + int corr = rtc.get_correction(); + rtc.set_time(y, month, day, wd, hour, min, sec); + rtc.set_time_in_chip(corr, y, month, day, wd, hour, min, sec); + return true; +} diff --git a/software/io/rtc/rtc_i2c.cc b/software/io/rtc/rtc_i2c.cc index 5d4f79c0e..a30a7abf7 100644 --- a/software/io/rtc/rtc_i2c.cc +++ b/software/io/rtc/rtc_i2c.cc @@ -4,6 +4,7 @@ #include "rtc.h" #include "rtc_epoch.h" +#include "current_time.h" #include #include #include @@ -404,5 +405,14 @@ extern "C" void get_current_time(int& wd, int& year, int& month, int& day, int& year += RTC_EPOCH_YEAR; // get_time() counts years from the epoch, callers do not } +extern "C" bool set_current_time(int wd, int year, int month, int day, int hour, int min, int sec) +{ + int y = year - RTC_EPOCH_YEAR; + int corr = rtc.get_correction(); + rtc.set_time(y, month, day, wd, hour, min, sec); + rtc.set_time_in_chip(corr, y, month, day, wd, hour, min, sec); + return true; +} + #include "init_function.h" InitFunction init_rtc("RTC", [](void *_obj, void *_param) { rtc.init(); }, NULL, NULL, 2); diff --git a/software/io/rtc/rtc_only_i2c.cc b/software/io/rtc/rtc_only_i2c.cc index a58b02af2..834cf7981 100644 --- a/software/io/rtc/rtc_only_i2c.cc +++ b/software/io/rtc/rtc_only_i2c.cc @@ -1,6 +1,7 @@ #include #include "rtc_only.h" #include "rtc_epoch.h" +#include "current_time.h" #include "i2c_drv.h" #include "itu.h" @@ -228,5 +229,14 @@ extern "C" void get_current_time(int& wd, int& year, int& month, int& day, int& year += RTC_EPOCH_YEAR; // get_time() counts years from the epoch, callers do not } +extern "C" bool set_current_time(int wd, int year, int month, int day, int hour, int min, int sec) +{ + int y = year - RTC_EPOCH_YEAR; + int corr = rtc.get_correction(); + rtc.set_time(y, month, day, wd, hour, min, sec); + rtc.set_time_in_chip(corr, y, month, day, wd, hour, min, sec); + return true; +} + Rtc rtc; // global diff --git a/software/test/iecdrive/testdrive.cc b/software/test/iecdrive/testdrive.cc index 192c0c531..382f38147 100644 --- a/software/test/iecdrive/testdrive.cc +++ b/software/test/iecdrive/testdrive.cc @@ -4,6 +4,7 @@ #include "file_device.h" #include "filesystem_fat.h" #include "macros.h" +#include "current_time.h" #include #include @@ -1469,6 +1470,33 @@ static void run_suite8_time_copy_rename_scratch(IecDrive *dr) expect_command_bytes("Suite8-T-RD", dr, "T-RD", t_rd, sizeof(t_rd)); expect_command_bytes("Suite8-T-RB", dr, "T-RB", t_rb, sizeof(t_rb)); + // SI-120. A clock write reaches the system clock, which is the one every other + // interface reads, and a write the clock cannot hold answers 30 and changes nothing. + // The four formats and their validation are checked in target/pc/linux/parse. + expect_command_ok("Suite8-T-WA", dr, "T-WA" "SAT. 09/12/26 01:02:03 PM"); + expect_command_response("Suite8-T-WA-READ", dr, "T-RI", "2026-09-12T13:02:03 SAT\r"); + { + const char *testname = "Suite8-T-WA-SYSTEM-CLOCK"; + int wd, year, month, day, hour, min, sec; + get_current_time(wd, year, month, day, hour, min, sec); + if ((wd != 6) || (year != 2026) || (month != 9) || (day != 12) || + (hour != 13) || (min != 2) || (sec != 3)) { + printf("%s: the system clock reads %d-%02d-%02d %02d:%02d:%02d, day of week %d\n", + testname, year, month, day, hour, min, sec, wd); + } + REQUIRE((wd == 6) && (year == 2026) && (month == 9) && (day == 12) && + (hour == 13) && (min == 2) && (sec == 3)); + } + expect_command_response("Suite8-T-W-INVALID", dr, "T-WI2026-02-30T00:00:00", + "30,SYNTAX ERROR,00,00\r"); + expect_command_response("Suite8-T-W-INVALID-READ", dr, "T-RI", "2026-09-12T13:02:03 SAT\r"); + // Leave the clock where the rest of the suite expects it. Its day of week is not the + // one the date has, so it is written in a form that carries one. + static const uint8_t t_wd_restore[] = { 'T','-','W','D', 3, 125, 6, 26, 12, 41, 1, 0 }; + expect_command_data_response("Suite8-T-W-RESTORE", dr, t_wd_restore, sizeof(t_wd_restore), + "00, OK,00,00\r"); + expect_command_response("Suite8-T-W-RESTORE-READ", dr, "T-RI", "2025-06-26T00:41:01 WED\r"); + expect_command_response("Suite8-COPY-MISSING-SOURCE", dr, "C2:DEST=", "34,SYNTAX ERROR,00,00\r"); expect_command_ok("Suite8-COPY-A-BB", dr, "C2:DEST=1:A,1:BB"); expect_iec_file("Suite8-COPY-DEST", dr, 0, "2:DEST", "This is really a silly test.This is really a silly test."); @@ -3441,6 +3469,97 @@ static void s11_si076_lock(FileManager *fm, IecDrive *dr) expect_command_response(testname, dr, "S47:INIMAGE\r", "01, FILES SCRATCHED,00,00\r"); } +// SI-051: R-P:new=old renames the partition the old name belongs to, and names no +// partition when nothing carries the old name. +static void s11_si051_rename_partition(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI051-RenamePartition"; + s11_partition(fm, dr, "si051"); + dr->add_partition(41, "/Temp", "TORENAME"); + uint8_t listing[8192]; + int got; + + expect_command_ok(testname, dr, "R-P:RENAMED=TORENAME\r"); + got = read_directory_stream(testname, dr, "$=P", listing, sizeof(listing)); + REQUIRE(memmem(listing, got, "RENAMED", 7) != NULL); + REQUIRE(memmem(listing, got, "TORENAME", 8) == NULL); + + // The name a partition carries is also what G-P answers with, in bytes 3 to 18. + expect_command_data_response(testname, dr, (const uint8_t *)"CP41\r", 5, + "02,PARTITION SELECTED,41,00\r"); + send_command(dr, "G-P"); + REQUIRE(memcmp(last_status + 3, "RENAMED", 7) == 0); + + expect_command_response(testname, dr, "R-P:X=NOSUCHPART\r", + "77,SELECTED PARTITION ILLEGAL,00,00\r"); + expect_command_response(testname, dr, "R-P:=TORENAME\r", "34,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "R-P:RENAMED\r", "30,SYNTAX ERROR,00,00\r"); + // Put the partition back, so a later case that reads the partition directory is not + // looking at a name this one left behind. + expect_command_response(testname, dr, "CP40\r", "02,PARTITION SELECTED,40,00\r"); + dr->get_file_system()->RemovePartition(41); +} + +// SI-064: R-H renames the header a listing of that directory shows, which is the +// directory's own name on the host file system (SI-065), the partition's name at the +// root of a partition, and the disk name inside a CBM image. +static void s11_si064_rename_header(FileManager *fm, IecDrive *dr) +{ + const char *testname = "Suite11-SI064-RenameHeader"; + s11_partition(fm, dr, "si064"); + uint8_t listing[8192]; + char header[17]; + header[16] = 0; + + // A subdirectory: its header is its name, so the directory answers to the new one. + expect_command_ok(testname, dr, "MD:GAMES\r"); + expect_command_ok(testname, dr, "R-H/GAMES/:ARCADE\r"); + read_directory_stream(testname, dr, "$/ARCADE/", listing, sizeof(listing)); + memcpy(header, listing + 8, 16); + printf("%s: header of $/ARCADE/ is '%s'\n", testname, header); + REQUIRE(memcmp(listing + 8, "ARCADE ", 16) == 0); + expect_command_ok(testname, dr, "CD//ARCADE\r"); + expect_command_ok(testname, dr, "R-H:ACTION\r"); // no path: the current directory + read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + REQUIRE(memcmp(listing + 8, "ACTION ", 16) == 0); + expect_command_ok(testname, dr, "CD//\r"); + + // The root of a partition, whose header is the partition name. + expect_command_ok(testname, dr, "R-H:HOSTPART\r"); + read_directory_stream(testname, dr, "$", listing, sizeof(listing)); + memcpy(header, listing + 8, 16); + printf("%s: header at the partition root is '%s'\n", testname, header); + REQUIRE(memcmp(listing + 8, "HOSTPART ", 16) == 0); + + // Inside a CBM image the header is the disk name, and the id stays as it is unless + // the command carries one. + create_formatted_image(fm, "/Fat/s11_si064.d64", "OLDNAME", 683, e_image_d64); + dr->add_partition(42, "/Fat/s11_si064.d64", "IMAGEPART"); + read_directory_stream(testname, dr, "$42", listing, sizeof(listing)); + char id[6]; + memcpy(id, listing + 8 + 18, 5); + id[5] = 0; + expect_command_ok(testname, dr, "R-H42:NEWDISK\r"); + read_directory_stream(testname, dr, "$42", listing, sizeof(listing)); + memcpy(header, listing + 8, 16); + printf("%s: header of $42 is '%s'\n", testname, header); + REQUIRE(memcmp(listing + 8, "NEWDISK ", 16) == 0); + REQUIRE(memcmp(listing + 8 + 18, id, 5) == 0); + expect_command_ok(testname, dr, "R-H42:WITHID,QQ\r"); + read_directory_stream(testname, dr, "$42", listing, sizeof(listing)); + memcpy(header, listing + 8, 16); + printf("%s: header of $42 with an id is '%s'\n", testname, header); + REQUIRE(memcmp(listing + 8, "WITHID ", 16) == 0); + REQUIRE(memcmp(listing + 8 + 18, "QQ", 2) == 0); + + // A name that is empty or carries a wildcard is no name to give a header. + expect_command_response(testname, dr, "R-H:\r", "34,SYNTAX ERROR,00,00\r"); + expect_command_response(testname, dr, "R-H:NEW*\r", "33,SYNTAX ERROR,00,00\r"); + // A path that is not there. + expect_command_response(testname, dr, "R-H/NOSUCH/:NAME\r", "71,DIRECTORY ERROR,40,00\r"); + dr->get_file_system()->RemovePartition(42); +} + // A 1541 image on partition `part`, selected, with a buffer channel open on `chan`. static void s11_block_partition(FileManager *fm, IecDrive *dr, const char *testname, int part, const char *image, uint8_t chan) @@ -4942,6 +5061,8 @@ static const Suite11Case suite11_cases[] = { { "Suite11-SI147-ShiftedSpace", s11_si147_shifted_space }, { "Suite11-SI142-EscapedWildcards", s11_si142_escaped_wildcards }, { "Suite11-SI076-Lock", s11_si076_lock }, + { "Suite11-SI051-RenamePartition", s11_si051_rename_partition }, + { "Suite11-SI064-RenameHeader", s11_si064_rename_header }, { "Suite11-SI090-BufferPointer", s11_si090_buffer_pointer }, { "Suite11-SI093-BoundPartition", s11_si093_bound_partition }, { "Suite11-SI094-BlockLength", s11_si094_block_length }, From ce42694327da6c0957473473481b3d15e804ca4a Mon Sep 17 00:00:00 2001 From: Christian Gleissner Date: Sun, 20 Sep 2026 20:11:31 +0100 Subject: [PATCH 022/514] feat(iec): sd2iec attribute commands and the hidden flag SI-077 EL/EU/EH/A/XH/D, SI-134 hidden entries left out of a listing. --- doc/softiec_compatibility_spec.md | 87 ++++++------ software/io/iec/cbmdos_parser.cc | 186 ++++++++++++++++++++------ software/io/iec/cbmdos_parser.h | 17 ++- software/io/iec/cbmdos_parser_test.cc | 37 ++++- software/io/iec/cbmdos_stubs.cc | 14 +- software/io/iec/iec_channel.cc | 108 ++++++++++++++- software/io/iec/iec_channel.h | 3 +- software/test/iecdrive/testdrive.cc | 81 +++++++++++ 8 files changed, 437 insertions(+), 96 deletions(-) diff --git a/doc/softiec_compatibility_spec.md b/doc/softiec_compatibility_spec.md index 7f635f530..4d987d4d5 100644 --- a/doc/softiec_compatibility_spec.md +++ b/doc/softiec_compatibility_spec.md @@ -839,32 +839,42 @@ image it is bit 6 of the file type byte. A scratch skips a locked entry, and als unlocked entry of the same name and type that follows a locked one in a disk image, because deleting by name removes the first entry of that name. -**SI-077.** The sd2iec extensions `EL:`, `EU:`, `EH:`, `A:` and `XH:`/`D:` are -specified as follows, from `SD parse_ecommand()`, `parse_eunlock()`, `parse_attr()` -and `parse_set_header()`, and from SD README: +**SI-077.** The sd2iec spellings of the attribute commands, from +`SD parse_elock()`, `parse_eunlock()`, `parse_ehide()`, `parse_attr()`, +`parse_set_header()` and the dispatch in `parse_doscommand()`. | Command | Effect | | --- | --- | -| `EL:name[,name...]` | set read-only on each match; `EL:$` locks a whole mounted image | -| `EU:name[,name...]` | clear read-only on each match; `EU:$` unlocks a whole mounted image | -| `EH[path]:name` | toggle the hidden flag on one file | -| `EH:name,id` | with a colon straight after the partition, set the directory header | -| `A:[R][H][A]=name` | set exactly the named attributes and clear the others | -| `XH:name,id`, `D:name,id`, `R-H:name` | set the directory header | - -They are a second priority behind the CMD commands, because C64 OS hides files by a -leading dot rather than by a device attribute (Greg Nacu, "Hidden Files": "hiding -files doesn't work on a CMD HD, nor a RAMLink, nor an FD2000 or FD4000"), and the -Ultimate's name mapping already escapes a leading dot as `{2E}` so such names round -trip. - -**Decision (PR #881): not implemented.** `L` (SI-076) provides locking and unlocking, -which is what the reporter asked for on #877. `EL` and `EU` are sd2iec's spellings of the -same attribute. `EH` and `A:` with `H` hide files, which only has an effect if listings -leave hidden files out, and that was not implemented either (see SI-134). `XH:`, `D:` -and `EH:` with a colon set a directory header, which is `R-H` (SI-064). The drive -answers `30` for `E` and `X` forms and `31` for `A` and `D`, whose letters are not -command letters. +| `EL[n][path]:name[,name...]` | set the lock on every entry each name matches | +| `EU[n][path]:name[,name...]` | clear it on every entry each name matches | +| `EH[n][path]:name`, with something other than a colon after the partition number | turn the hidden flag of one entry over | +| `EH[n]:name[,id]`, `XH[n][path]:name[,id]`, `D:name[,id]` | set a directory header, which is `R-H` (SI-064) | +| `A:[R][H][A]=name[,name...]` | set exactly the attributes named on every entry each name matches, and clear the others | + +The lock these set and clear is the one `L` turns over (SI-076), so a file `EL` locks is +a file `L` unlocks and a file a scratch skips. `R` in `A` is that lock, `H` is the hidden +flag of SI-134 and `A` is the archive flag, which the drive stores and nothing reads. + +Two differences from the source are deliberate. `SD parse_elock()` and `parse_eunlock()` +skip directories and `parse_attr()` acts on the first match only; here all five commands +act on every entry the name matches, directories included, because `L` locks a directory +(HD 9-30) and a lock that `EL` and `L` disagreed about would be two locks. A name that +matches nothing answers `62,FILE NOT FOUND`, and a medium that does not carry the +attribute, such as the hidden flag inside a CBM disk image, answers `30`. + +`EL:$` and `EU:$`, which write-protect a whole mounted image in sd2iec, are not +implemented and answer `62`, because the name `$` matches no entry. Write-protecting a +mounted image means changing the writability of a file system that the file browser, FTP +and the REST interface share, and this drive has a per-entry lock that covers what a +program asks `EL` for. + +`XH+` and `XH-`, which turn hidden files on and off for every later listing, are one of +the sd2iec settings commands that section 19 places out of scope; the filter `=H` asks +for them per listing instead. They answer `30`. + +`A` and `D` are command letters because of `A:` and `D:`, so an unrecognised argument to +either answers `30` under SI-030. That covers the sd2iec direct sector commands `DI`, +`DR` and `DW` of SI-096. --- @@ -1385,17 +1395,19 @@ GSD warns that "If filtering a directory programmatically, B should be used for compatibility with CMD storage devices. D is only supported by sd2iec", and IDE 6.2 in fact maps `D` to DEL. `H` additionally shows hidden files. -Current behaviour: `U parse_dir_option()` accepts all of them, but it maps `H` to bit -6 of the type mask while `U read_dir_entry()` tests `1 << ftype` with `ftype` at most -5. Measured, `$:*=H` lists the header and no entries at all, where `$:*=P` and -`$:*=B` list correctly. -**Change required:** `H` is not a type, it is a flag that suppresses the hidden -filter, and it must be kept separate from the type bits. +`H` is not a type but a flag: a listing leaves out every entry that carries the hidden +attribute unless `H` asks for them, and it sets no type bit, so `$:*=H` lists what `$:*` +lists and the hidden entries as well. -**Decision (PR #881): `H` no longer filters; hidden files stay listed.** `H` is accepted -and sets no type bit, so `$:*=H` lists what `$:*` lists. Leaving hidden files out of a -listing by default is not implemented: before PR #881 they were listed, C64 OS hides -files by a leading dot rather than by an attribute, and no report asks for the change. +**SI-134a.** A hidden entry is left out of a listing and still answers to its name. Every +command that names an entry finds it: an open, a scratch, a rename, `L`, and the `EH` +that turns the flag back. `SD` reaches the same place from the other side, by passing +`FLAG_HIDDEN` to `first_match()` and `next_match()` in every command that names a file. +Without this a file could be hidden over the bus and never reached again. + +C64 OS hides files by a leading dot rather than by an attribute, and the name mapping +escapes a leading dot as `{2E}` (SI-141), so such a name round trips and is not touched +by this requirement. **SI-135.** `LOAD"$=T..."` produces a time-stamped listing, with options `L`, `N`, `>stamp` and `