Skip to content

fix(savegame): write and read unicode strings as 2 byte UTF-16 code units - #3720

Closed
alviss7 wants to merge 1 commit into
TheSuperHackers:mainfrom
alviss7:fix/savegame-unicode-wchar-width
Closed

alviss7 wants to merge 1 commit into
TheSuperHackers:mainfrom
alviss7:fix/savegame-unicode-wchar-width

Conversation

@alviss7

@alviss7 alviss7 commented Nov 22, 2026

Copy link
Copy Markdown

Problem

XferSave::xferUnicodeString and XferLoad::xferUnicodeString transfer sizeof( WideChar ) * len
bytes. WideChar is unichar, which is wchar_t, so a save file is written with 2 byte characters
on Windows and with 4 byte characters on the unix preset, where wchar_t is 4 bytes.

The save game format is therefore not the same on every target, and a save file written on Windows
is misread by a Unix build:

  • The description in the Load Game list keeps only every second character. Début de mission : USA 2
    reads back as invalid code points whose low 16 bits spell Dbtd iso éignrlaoiu.
  • The read consumes twice the bytes the string occupies, so the map label, the campaign side and the
    mission number that xferSaveGameInfo writes behind the description are all read from the wrong
    file position, and the load fails.

This was found on the GeneralsX port, where it is
issue #443, but the code is identical here and the
unix preset is affected the same way, so the fix belongs upstream rather than only in the port.

Change

XferSave and XferLoad now transfer unicode strings as 2 byte UTF-16 code units on every target,
converting to and from the native WideChar around the file access. The on-disk layout becomes the
Windows one everywhere: a single length byte followed by one 2 byte code unit per character.

On Windows, where wchar_t is already 2 bytes, the conversion is an identity copy and the bytes
written are unchanged.
The change is a no-op for the vc6, win32 and mingw-w64-i686 presets.

The two functions live in Core/, so Generals and Zero Hour both get the fix from the same change.

The same sizeof( WideChar ) pattern also appears in Xfer::xferUnicodeString (used by XferCRC)
and in XferDeepCRC::xferUnicodeString. Those feed CRCs rather than the save file and changing them
shifts CRC values, so they are deliberately left out of this change.

Compatibility

Save files written on Windows, by the retail game, and by this branch are all read correctly on
every target.

Save files written by an earlier Unix build use 4 byte characters and are not readable after this
change. That format was never interchangeable with a Windows build, and the same files already fail
to round-trip today. Detecting the old layout per string is not reliable, because a single character
string is two bytes in the new layout and four in the old one, with nothing in the file to tell them
apart, and a wrong guess desynchronizes the rest of the read. If maintainers would prefer a
migration path anyway, I am happy to add one in a follow-up.

Tests

Tests/Google/Core/GameEngine/Common/XferUnicodeStringTest.cpp is new and covers:

  • the written bytes are a length byte plus one 2 byte code unit per character, checked against the
    exact expected bytes for Début
  • a string survives a save and load round-trip
  • an AsciiString written behind a unicode string is read back intact, which is the stream
    desynchronization described above
  • an empty string writes its length byte alone

Verification

I do not have a Windows toolchain here, so this branch itself was not compiled. The change was
built and exercised on the GeneralsX port, whose XferSave.cpp, XferLoad.cpp and Xfer.h are
byte for byte the same as this repository's in the regions touched, as
PR fbraz3/GeneralsX#444:

  • z_generals and g_generals both build and link clean with the change, 0 errors, on a 64-bit
    Linux preset where sizeof(wchar_t) is 4.
  • The new test translation unit compiles for both the Zero Hour and the Generals Google Test objects.
    The test executable does not link there for a pre-existing reason unrelated to this change, so the
    Google Test cases have not been executed anywhere yet.
  • Behaviour was verified with a standalone harness holding the old and the new function bodies
    verbatim, run against a Windows written 00000000.sav starting at the description length byte:
OLD  description : "<unprintable code points>"
OLD  file pos after the string : 165
OLD  next value (map label)    : "<short read>"

NEW  description : "Début de mission : USA 2"
NEW  file pos after the string : 117
NEW  next value (map label)    : "MD_USA01.map"

NEW  writer reproduces the retail bytes : YES (49 bytes)

That file is 192 bytes and its CHUNK_GameState payload is 118 bytes, so the old position 165 is
already outside the chunk.

I would appreciate a CI run or a Windows reviewer confirming the no-op on the vc6 and win32
presets before this is merged.

AI disclosure

Implemented with Claude Code (Claude Opus 5) under my review. The byte dumps, the build results and
the harness output above come from files and commands that were actually read and run; the
limitations on what was not built or executed are stated explicitly above.

…nits

XferSave::xferUnicodeString and XferLoad::xferUnicodeString transfer
sizeof( WideChar ) * len bytes, and WideChar resolves to wchar_t, which is
2 bytes on Windows but 4 bytes on the Unix targets. The save file layout
therefore depends on the platform that wrote it, and a file written on
Windows is read on a Unix build with characters twice as wide as they are:
the Load Game list keeps only every second character of the description, and
the read runs past the string into the map label, the campaign side and the
mission number stored behind it.

Both functions now transfer 2 byte UTF-16 code units on every platform and
convert to and from the native WideChar around the file access, which makes
the on-disk layout the Windows one everywhere. On Windows the conversion is
an identity copy and the written bytes are unchanged.

Both functions live in Core/, so Generals and Zero Hour share the fix.
@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

Unicode string transfer now writes and reads UTF-16 code units instead of native-width WideChar data. A new constant defines the maximum encoded length. GoogleTest coverage checks serialization, deserialization, surrogate handling, and length limits.

Changes

Unicode string transfer

Layer / File(s) Summary
UTF-16 encoding, decoding, and validation
Core/GameEngine/Include/Common/Xfer.h, Core/GameEngine/Source/Common/System/XferSave.cpp, Core/GameEngine/Source/Common/System/XferLoad.cpp, Tests/Google/Core/GameEngine/Common/XferUnicodeStringTest.cpp, Tests/Google/Core/CMakeLists.txt
XferSave encodes strings as UTF-16 code units and writes the encoded-unit count in the length byte. It replaces values above 0x10FFFF with 0xFFFD and rejects strings over 255 encoded units. XferLoad reads UTF-16 units and combines valid surrogate pairs when WideChar is wider than two bytes. Tests cover encoded bytes, round trips, file-position preservation, empty strings, surrogate handling, and the length limit.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested labels: Saveload, Test

Suggested reviewers: xezon, bobtista

Merge Risk: Minimal · previous review 1e5cf

This change makes Unicode string save and load use a consistent 2-byte UTF-16 layout across platforms, and Windows behavior is unchanged. It also makes older Unix saves that used 4-byte characters unreadable, which the author states is intended. No concrete merge-blocking risk is identified; CI should confirm the builds and tests.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: Unicode strings in savegame transfer are written and read as 2-byte UTF-16 code units. The changeset modifies XferSave and XferLoad xferUnicodeString to do exactly thi…
Description check Passed The description is directly related to the changeset. It explains the problem with sizeof(WideChar) in XferSave and XferLoad::xferUnicodeString, describes the switch to 2-byte UTF-16 code units, lists…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: Unicode strings in savegame transfer are written and read as 2-byte UTF-16 code units. The changeset modifies XferSave and XferLoad xferUnicodeString to do exactly this, and adds tests for it. The 'fix(savegame)' prefix is a conventional-commit style that stays descriptive.

Full details: Description check

Explanation

The description is directly related to the changeset. It explains the problem with sizeof(WideChar) in XferSave and XferLoad::xferUnicodeString, describes the switch to 2-byte UTF-16 code units, lists the new XferUnicodeStringTest cases, and notes compatibility impact and verification status.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 395382ca-9514-445f-a13d-233d5025e74b
Commits

Reviewing files that changed from the base of the PR and between e4e15c9 and 1e5cf7f.

Files selected for processing: 1

  • Tests/Google/Core/GameEngine/Common/XferUnicodeStringTest.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

@greptile-apps

greptile-apps Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change reaches save-game string reads and writes in both Generals and Zero Hour.

The Windows source-encoding failure in the tests still needs fixing before merge.

Findings

  1. P1 Windows test literals change ▶

Summary

XferSave and XferLoad now transfer Unicode strings through two-byte UnsignedShort buffers.

  • Save files store Unicode strings as two-byte characters on every target.

Reviews (4) · Last reviewed commit: "fix(savegame): write and read unicode st..." · Reviewed by Greptile


TEST_F(XferUnicodeStringTest, WritesTwoBytesPerCharacter)
{
const std::vector<UnsignedByte> bytes = writeString(UnicodeString(L"Début"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Windows test literals change

If MSVC uses Windows-1252 to read this source, é in L"Début" becomes two wide characters. This UTF-8 file has no BOM, and the build does not set /utf-8 or /source-charset. The test then writes six characters and fails its fixed five-character byte checks, even when the save code works correctly.

Use L"D\u00E9but" here and in the other literals, or explicitly select UTF-8 for the source.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0fcc4a6b-0ebe-444b-8b1e-1b941f5b652c
Commits

Reviewing files that changed from the base of the PR and between 967a361 and 3d69518.

Files selected for processing: 5

  • Core/GameEngine/Include/Common/Xfer.h
  • Core/GameEngine/Source/Common/System/XferLoad.cpp
  • Core/GameEngine/Source/Common/System/XferSave.cpp
  • Tests/Google/Core/CMakeLists.txt
  • Tests/Google/Core/GameEngine/Common/XferUnicodeStringTest.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@alviss7

alviss7 commented Nov 23, 2026

Copy link
Copy Markdown
Author

Pushed e4e15c9, which handles characters outside the basic multilingual plane.

Where wchar_t is 4 bytes, UnicodeString holds whole code points, so such a character is one character and not the surrogate pair the save format stores. The writer was casting it to UnsignedShort, which turned U+1F600 into U+F600, and it took the length header from the character count rather than from the number of code units written. The reader copied each unit straight into the native buffer, so a pair read back as two unpaired surrogates.

The writer now encodes to UTF-16 first, counts the header in code units and applies the 255 unit limit to the encoded length. The reader combines a high surrogate followed by a low one, and leaves an unpaired surrogate alone. On Windows no code point exceeds U+FFFF, so both paths stay the identity copy they were and the written bytes are unchanged.

Six test cases cover it, including a reader fixture fed with hand-written bytes and the 255 unit boundary.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 772fad20-9a2b-49d2-8314-71e6cd685a08
Commits

Reviewing files that changed from the base of the PR and between 3d69518 and e4e15c9.

Files selected for processing: 3

  • Core/GameEngine/Source/Common/System/XferLoad.cpp
  • Core/GameEngine/Source/Common/System/XferSave.cpp
  • Tests/Google/Core/GameEngine/Common/XferUnicodeStringTest.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@OmniBlade

Copy link
Copy Markdown

I don't think we should be writing code to handle 32bit wchar on none windows, ICU UChar should be used as unichar on none windows platforms which is already UTF-16 like wchar is on windows so no code relating to the size of a code point needs altering.

@alviss7
alviss7 force-pushed the fix/savegame-unicode-wchar-width branch from 1e5cf7f to 3d69518 Compare November 24, 2026 13:10
@alviss7

alviss7 commented Nov 24, 2026 •

Copy link
Copy Markdown
Author

Agreed, unichar should end up as ICU's UChar on non Windows platforms. Once it is 16 bit there, sizeof(WideChar) * len is correct again and this conversion becomes a plain copy, as it already is on Windows.

ICU isn't in the tree yet though (#3187 is still open), and moving unichar to char16_t means reworking UnicodeString, which relies on wcslen/wcscpy/wcscat/vswprintf and L"" literals everywhere. Until that lands, the unix preset writes save files that Windows can't read, and the other way round.

So I'd like to keep this as a stopgap, but smaller. I dropped e4e15c9 (the surrogate pair handling), so all that's left for a 4 byte wchar_t is narrowing each character to 16 bits and widening it back. The file format stays 2 bytes per code unit, which is what Windows writes today and what it will be with UChar. The only loss is characters above U+FFFF in a save description, and the game fonts can't draw those anyway.

If you'd rather wait for ICU and fix it there, that's fine too and I'll close this.

@stephanmeesters

stephanmeesters commented Nov 24, 2026 •

Copy link
Copy Markdown

Looks like there are more WideChar sites that need fixing.

This is what Claude is saying compared to @bobtista 's branch which also has a similar fix to yours, but is also not ideal, so perhaps indeed better to wait for the ICU fix.

bobtista's branch uses the same idea as alviss7's PR: keep WideChar as native wchar_t and convert to 16-bit code units where the data is written or read. It differs in three ways.

  1. It wraps the conversion in #ifdef _WIN32. Windows keeps the original raw sizeof(WideChar) copy unchanged, and only non-Windows takes the convert-through-UnsignedShort[] path. That guarantees the no-op on Windows without anyone having to check the identity copy. The cost is two code paths per site, so it's arguably more of a hack than alviss7's version, not less.

  2. It covers more sites. It all lives in one big commit, 4ebfa4cca7 feat(save): save-load, replay, and map xfer under the macOS runtime:

    Site alviss7 PR bobtista trunk
    XferSave/XferLoad::xferUnicodeString ✅ ✅
    Xfer::xferUnicodeString (CRC) ❌ deliberately skipped ✅
    DataChunk (maps) ❌ ✅
    GameText (CSF) ❌ ✅
    NetPacketStructs sizes ❌ Partly; line 815 still uses sizeof(WideChar)
  3. The CRC fix undercuts the PR's reason for skipping it. alviss7 says changing the CRC path "shifts CRC values". bobtista's comment shows it doesn't on Windows: the data is fed in even chunks of at most 256 code units, so XferCRC folds the same 4-byte words as one contiguous call. On Unix the CRC is already wrong compared to Windows today, and Player::m_generalName desyncs cross-platform multiplayer. So the CRC site belongs in the same fix.

That also corrects my earlier suggestion. Calling xferUnsignedShort once per character is fine for XferSave/XferLoad, which are plain byte streams. It would not be safe in Xfer/XferCRC, because folding 2-byte pieces separately changes the CRC. That path needs whole-word chunks like bobtista's.

Also relevant to your first question: unichar.h on trunk now says outright that changing the type "requires adapting wide literals, character traits, and CRT/platform APIs". So making WideChar 2 bytes was looked at there and not done.

What I'd suggest for the review: the approach is right but the scope is too narrow. Ask alviss7 to include the CRC path using the chunked form, which is byte-identical on Windows, and either fix DataChunk/GameText/net packets too or list them as follow-ups. A small shared helper would avoid copying the loop into five places.

@OmniBlade

Copy link
Copy Markdown

I think waiting for ICU to land and working to make the code functional for both ICU and winapi is the better approach personally and is the approach I took for Renegade. Since we don't currently support none windows builds, the fact that on other platforms the save format is different only really affects downstream projects which are free to either wait or make their own stop gap fixes.

@alviss7 alviss7 closed this Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants