Skip to content

[Kernel/XAM/VFS] Support offline Xbox Live sign-in for DLCs and fix save renames and per-title cache: (#132, #125) - #137

Merged
phforner0 merged 5 commits into
mainfrom
fix/kernel-xam-dlc-saves
Nov 18, 2026
Merged

phforner0 merged 5 commits into
mainfrom
fix/kernel-xam-dlc-saves

Conversation

@phforner0

Copy link
Copy Markdown
Owner

O que muda e por quê

Este PR corrige bloqueio de DLCs por status de perfil offline da Xbox Live (#132), falhas de gravação/carregamento de saves e montagem de partição de cache (cache:) em Mass Effect (2007) (#125), e registra o diagnóstico técnico completo de #120 e #96 com base nos logs e no histórico do Xenia Edge.

1. Fight Night Champion (45410915) — DLCs presas mesmo com license_mask = -1 (Closes #132)

  • Causa raiz: além da máscara de licença do pacote STFS (license_mask = -1), títulos da EA como Fight Night Champion consultam XamUserGetSigninState, XamUserGetSigninInfo, UserProfile::GetUserFlags() e XamUserCheckPrivilege (0xD1..0xFF), exigindo que o perfil local reporte estado eXUserSigninState_SignedInToLive (2), flag X_USER_INFO_FLAG_LIVE_ENABLED, XUID online (0x0009...) e privilégios Live concedidos para liberar lutadores/modos de DLC. Retornar SignedInToLive globalmente para todos os jogos causaria regressão em títulos que tentam iniciar handshake real de rede na Xbox Live sem backend online.
  • Solução:
    • Porta o suporte a perfil local habilitado para Live do Xenia Edge (3b2173427, 48b318a2a, 85b839af6) em xam.h, user_profile.h, profile_manager.{h,cc} e xam_user.cc, isolando a lógica pura em user_signin_util.h.
    • Adiciona a cvar por título live_signin na categoria [Profiles] (false por padrão), sem nunca gravar ou alterar o arquivo Account em disco e preservando o XUID offline (0xE030...) usado nas pastas de save, enquanto deriva deterministicamente um XUID online (0x0009...) apenas nas consultas XAM online.
    • Ativa live_signin = true exclusivamente para Fight Night Champion (0x45410915) em commit isolado em game_quirks.cc.

2. Mass Effect (4D5307E8) — falha ao salvar/carregar e arquivos .tmp órfãos (Closes #125)

  • Causas raiz identificadas na comparação com o Xenia Edge:
    1. xe::string_key_insensitive::hash() sensível a caixa (1551bc340): operator== ignorava caixa, mas hash() usava utf8::hash_fnv1a, fazendo ContentManager::open_packages_ cair em buckets distintos ao abrir "save" e fechar/consultar "SAVE", deixando pacotes (GamerProfile / saves) presos montados.
    2. Rename atômico de .tmp (Save_player_*_00.tmp) falhando em mounts multi-componente e root_dir_handle (39aea998f, 3de73d379): Entry::Rename removia apenas 1 componente do caminho (path_parts.erase(begin())), quebrando renames resolvidos para \Device\Content\N\... com X_STATUS_OBJECT_PATH_NOT_FOUND e ignorando root_dir_handle em NtSetInformationFile(XFileRenameInformation).
    3. Sobrescrita destrutiva em HostPathEntry e espaço livre fixo (494e2ef67, f17accd63): kOverwrite/kOverwriteIf deletava e recriava o arquivo por baixo de handles abertos; agora trunca/sobrescreve in-place (HostPathEntry::Overwrite()) e HostPathDevice consulta capacidade/espaço livre reais do host.
    4. I/O assíncrono pendente no encerramento de XThread e referência de objetos XAM (896b71158, f2da83314, 6f52b23ba, 207a01cf5, 93a6be623): XThread::Exit agora drena requisições assíncronas antes de destruir a thread, SubmitRequest preserva status_block até a conclusão, e ObjectTable::LookupAllocatedBody permite que ObDereferenceObject resolva objetos kernel não-dispatcher (como enumeradores de conteúdo).
    5. Partição cache: ausente por padrão (mount_cache = false) e quebrada em remount/formatação (7f1689639, c628a23df, 4fcace370, 873672df5): CompleteLaunch passa a montar \CACHE por título (storage_root/cache/<title_id>) com links \Device\cache0 e \Device\cache1 sempre disponíveis para XMountUtilityDrive (mantendo mount_cache compatível com o schema do app para cache0:/cache1:), redirecionando \Device\Harddisk0\Cache0/Cache1 em ObCreateSymbolicLink, implementando IoDismountVolume/IoDismountVolumeByFileHandle e persistindo a tabela Partition0 (0x800..0xC00) + cluster size 'XTAF' em cache/Headers/<title_id>.header com limpeza automática (EmptyTitleCache()) ao formatar.

3. Triagem técnica documentada (#120 e #96)

  • Issue #120 (Call of Duty 4: Modern Warfare 415607E6 — "Out of memory" após "The Coup"):
    • A inspeção completa do xe.log anexado (session_20261107-150649.zip) comprova que não há falta de RAM do Android nem falha de heap do Xenia (zero erros em MmAllocatePhysicalMemoryEx ou NtAllocateVirtualMemory). O primeiro boot roda 20.407 frames normalmente (F.N.G. -> Crew Expendable -> The Coup); no frame 20407, o jogo chama XamLoaderLaunchTitle("default.xex") -> RelaunchTitle (Setup status=00000000), e 22 frames após o relaunch (f:0020429) a thread principal 01000028 dispara longjmp em 0x82167828 (Com_Error(ERR_DROP, "Out of memory") interno da engine IW3).
    • Dois bugs de estado em RelaunchTitle afetavam diretamente esse fluxo: o cache compartilhado sem isolamento/formatação por título (corrigido neste PR) e a não-limpeza de launch_data após XamLoaderGetLaunchData (portado do Edge 684293925 no PR #134). Como não temos mídia de CoD4 para reteste em dispositivo aqui, #120 permanece aberta aguardando confirmação em gameplay após ambos os PRs.
  • Issue #96 (WWE 2K14 545408B2 — crash em 0x82C79568):
    • Reportada na versão antiga v0.2.0 (80237530) sem xe.log anexado (solicitado em 27/out sem resposta) e sem commit específico para 545408B2 no Xenia Edge. Sem xe.log não é possível isolar se o fault em 0x82C79568 vinha de export kernel, VFS ou JIT/GPU; permanece aguardando log atualizado.

Como foi testado

  • XENDROID_NDK=... bash tools/test-native-logic.sh: 18/18 binários nativos aprovados, incluindo 3 novos testes de host C++:
    • xam_live_signin_test: valida estado offline padrão (SignedInLocally, privilégios Live negados) vs live_signin=true ou conta Live (SignedInToLive, X_USER_INFO_FLAG_LIVE_ENABLED, XUID 0x0009... determinístico sem alterar XUID offline, privilégios Live concedidos).
    • string_key_test: valida hash e lookup/erase case-insensitive em unordered_map para string_key_insensitive ("save" vs "SAVE") preservando sensibilidade a caixa em string_key.
    • vfs_save_cache_test: reproduz e valida renames de .tmp de saves do Mass Effect via nome simples, symlink save:\ e caminho multi-componente \Device\Content\1\..., sobrescrita in-place com truncamento no fechamento, reporte de espaço livre real do disco, persistência da tabela Partition0 e formatação 'XTAF' limpando \CACHE + remount de cache:.
  • aarch64-linux-android29-clang++ -fsyntax-only (via compile_commands.json do build Release NDK29, em HEAD e isoladamente em cada um dos 4 commits): 0 erros em todas as 22 unidades de tradução C++ de produção alteradas.
  • :app:assembleRelease -PxendroidReleaseIdSuffix=.fork.ui -PxendroidReleaseDebuggable (NDK 29 arm64-v8a + ThinLTO libe.so): BUILD SUCCESSFUL.
  • python3 tools/check-jni.py: consistente.
  • Limitação declarada: validação feita por testes unitários nativos de host e compilação Release NDK29/APK; os jogos comerciais (Fight Night Champion e Mass Effect) não foram executados localmente neste ambiente de build.

Unlocks DLCs that require an Xbox Live-enabled profile in Fight Night Champion and fixes save/load and cache drive failures in games like Mass Effect.

  • Fight Night Champion: DLC fighters and modes unlock offline without modifying your profile file on disk.
  • Mass Effect and utility-drive titles: game saves complete their temporary-file rename cleanly and per-title cache: partitions work out of the box.

🛠️ Fixed

Desbloqueia DLCs que exigem perfil com status Xbox Live em Fight Night Champion e corrige falhas ao salvar/carregar jogos e montar a partição cache: em títulos como Mass Effect.

  • Fight Night Champion: lutadores e modos de DLC são liberados offline sem modificar o arquivo do seu perfil no disco.
  • Mass Effect e jogos que usam drive de cache: gravações de save concluem a renomeação de arquivos .tmp corretamente e a partição cache: por jogo funciona automaticamente.

🛠️ Corrigido

…es, and pending thread I/O (#125)

- Hash xe::string_key_insensitive case-insensitively so ContentManager::open_packages_ finds and closes packages regardless of root name case (ports Xenia Edge 1551bc340) + validate root names in XamContentCreateEx/XamContentSetThumbnail (ports 93a6be623).
- Resolve VFS entry renames across symbolic links, multi-component mount paths (e.g. \Device\Content\N), DOS device prefixes, and root_dir_handle instead of stripping a single path component (ports 39aea998f and 3de73d379).
- Overwrite existing HostPathEntry files in place and truncate on final handle close instead of deleting/recreating over open handles (ports 494e2ef67).
- Query real host filesystem capacity and free space in HostPathDevice (ports f17accd63).
- Drain pending async file I/O before XThread::Exit tears down thread state and keep status_block untouched until completion (ports 896b71158 and f2da83314).
- Track allocated kernel object bodies in ObjectTable so ObDereferenceObject resolves non-dispatcher objects such as XAM enumerators cleanly (ports 6f52b23ba and 207a01cf5).
- Add native host unit test string_key_test in tools/test-native-logic.sh.
…nd partition formats (#125)

- Mount \CACHE per title under storage_root/cache/<title_id> during CompleteLaunch and link \Device\cache0 and \Device\cache1 to \CACHE instead of pre-registering a shared cache: symlink only when mount_cache=true (ports Xenia Edge 7f1689639).
- Redirect ObCreateSymbolicLink targets \Device\Harddisk0\Cache0 and Cache1 to \Device\cache0 and cache1, and implement IoDismountVolume and IoDismountVolumeByFileHandle so utility drive unmounts/remounts keep cache: intact (ports 7f1689639 and 4fcace370).
- Persist Partition0 cache ownership table (0x800..0xC00) and formatted FATX ('XTAF') cluster sizes in storage_root/cache/Headers/<title_id>.header via NullDevice/NullEntry/NullFile, emptying \CACHE when a title formats a cache partition (ports c628a23df, 4fcace370, and WriteAllBytes from 873672df5).
- Add native host test vfs_save_cache_test in tools/test-native-logic.sh covering Mass Effect .tmp save renames across symlinks and multi-component mount paths, in-place overwrites, host disk space reporting, cache: remounts, and Partition0/FATX formatting.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T05:17:02.025727Z 5b880d2 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5b880d24d5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

status_block->status = X_STATUS_PENDING;
status_block->information = 0;
}
// The status block is left alone until the request completes.

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 Badge Set queued I/O status blocks to pending

For requests that SubmitRequest queues, such as asynchronous reads and writes, this leaves the caller’s I/O status block untouched until the worker completes. A caller polling a reused status block can see stale success and byte-count values and consume incomplete data while the request is still pending. Set the status to X_STATUS_PENDING and information to zero before posting the request, as the previous implementation did.

Useful? React with 👍 / 👎.

@phforner0
phforner0 merged commit a4caad6 into main Nov 18, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant