[Refactor] (P13 W6b): the data-arm predicate folds out of every backend branch; frontend-arm unit cases go, three adapted, and two GL sampling rules move to an integration scenario.

This commit is contained in:
2026-10-06 16:39:52 -04:00
parent 740dd301b9
commit 742d43aeb4
27 changed files with 1143 additions and 1914 deletions
@@ -102,59 +102,6 @@ TEST(ContextEpochTest, RawDepthSamplerOwnsANativeIdForEachContextGeneration) {
#endif
}
// P3b/P4b wave 2-D package D2, STEP 1 of the raw-depth-fetch sampler monolith cleanup: the case
// above is parameterised over the OTHER arm, so that the claim DirectGLES.cpp:334-336 makes in
// prose - "P5f fs's transport arm below uses only a native sampler with fixed values. The legacy
// pair is not constructed or consulted by the server." - is a test rather than a comment.
//
// STEP 2 OF THAT CLEANUP - deleting what the transport arm makes unreachable - IS NOT DONE HERE
// AND IS RECORDED AS P13. Every candidate (the two file-static SharedPtrs at DirectGLES.cpp:82-83,
// the monolith arm at :361-371, NeedsRawDepthFetchSampler at :393-399 and the pre-handle sampler
// pass at :8015-8024) is UNCONDITIONAL code: none of it sits behind
// `#if !MOBILEGL_BUILD_DISAGGREGATED`, the pull build (DISAGGREGATED=OFF, PIPE_PUSH=OFF) compiles
// and links all of it, and the monolith arm is the ENTIRE body GetRawDepthFetchSampler has there.
// Deleting any of it moves pull `.text` and fails G1's 0/0/0/0 - which is the rule
// ARCHITECTURE.md:340 states for exactly this class of retired-but-compiled code. The package's
// instruction was "only if it keeps the pull build's .text identical"; it does not, so the
// deletion stops here and is filed rather than attempted.
//
// What this case CAN assert without touching a line of library code is that the two arms are
// genuinely two objects, which is the observable form of "not consulted by the server": a server
// that had fallen through to the legacy pair would hand back the same pointer under both
// transports.
TEST(ContextEpochTest, RawDepthSamplerTakesADifferentObjectOnEachArmAndTheServerNeverTakesTheLegacyOne) {
#if MOBILEGL_BUILD_DISAGGREGATED
DriverScope scope; // pins InProcess and bumps the generation, so both arms start cold
samplerParameters = 0;
// --- the transport-native arm ---
SamplerImpl::BackendSamplerObject* const native = GetRawDepthFetchSampler();
ASSERT_NE(native, nullptr);
const Uint nativeId = native->GetBackendSamplerId();
EXPECT_NE(nativeId, 0u);
EXPECT_EQ(samplerParameters, 4u) << "the native arm programs its four fixed values directly";
// --- the monolith arm, same entry point, same process ---
MG_Config::Transport = MG_Config::TransportMode::Monolith;
SamplerImpl::BackendSamplerObject* const legacy = GetRawDepthFetchSampler();
ASSERT_NE(legacy, nullptr);
EXPECT_NE(legacy, native)
<< "both transports handed back the SAME BackendSamplerObject, so the server did not take "
"the transport-native arm at all - it fell through to g_rawDepthFetchSamplerBackend, "
"which DirectGLES.cpp:334-336 says it must not touch";
EXPECT_NE(legacy->GetBackendSamplerId(), nativeId)
<< "the two arms share a native sampler id";
// --- and back, to prove the selection is live rather than a first-call latch ---
MG_Config::Transport = MG_Config::TransportMode::InProcess;
EXPECT_EQ(GetRawDepthFetchSampler(), native)
<< "the transport arm's cached native sampler did not survive a round trip through the "
"monolith arm, so one of the two arms is rebuilding state the other owns";
#else
GTEST_SKIP() << "both arms exist only in the disaggregated build; the pull build compiles the "
"monolith arm alone and it is the whole function there";
#endif
}
TEST(ContextEpochTest, SameXfbNameInTwoServedContextsDoesNotAliasThePausedSpan) {
#if MOBILEGL_BUILD_DISAGGREGATED
@@ -173,87 +173,5 @@ TEST(SubsystemDepsTest, TheClientNeverEmitsAFamilyTheTableRefuses) {
RecordProperty("client_emitting_combinations", emitted);
}
// ---------------------------------------------------------------------------------------------
// 3. THE SERVER CONSUMER GATE agrees with the table at every interesting mask.
//
// The resolvers answer "did this family's handle arm come up", which is the dependency rule AND
// the family's own bit AND, for the framebuffer one, D-C3's separate wire-caps refusal. So the
// comparison is one-directional where it has to be: a resolver may say NO for a reason of its
// own, but it may never say YES at a mask the table refuses - that is the direction in which a
// disagreement is a half-run subsystem rather than an extra refusal.
// ---------------------------------------------------------------------------------------------
TEST(SubsystemDepsTest, TheServerConsumerGateNeverArmsAFamilyTheTableRefuses) {
using namespace MobileGL::MG_Backend::DirectGLES;
// THE RESOLVERS SURVIVE A SWEEP because a refused family takes the (unreachable since P13 W3b)
// legacy verdict and returns false instead of stopping; ConfigLoader refuses any such mask at
// startup, so this sweep exercises the resolvers' own logic, not a reachable configuration.
struct Resolver {
const char* Name;
Uint64 Family;
Bool (*Resolve)();
};
const Resolver resolvers[] = {
{"ResolveFramebufferSubsystemArm", kMGPipeSubsystemFramebuffer,
&ResolveFramebufferSubsystemArm},
{"ResolveTextureResourceSubsystemArm", kMGPipeSubsystemTextureResources,
&ResolveTextureResourceSubsystemArm},
{"ResolveSamplerSubsystemArm", kMGPipeSubsystemSamplers, &ResolveSamplerSubsystemArm},
{"ResolveProgramSubsystemArm", kMGPipeSubsystemPrograms, &ResolveProgramSubsystemArm},
};
for (const Uint64 mask : InterestingMasks()) {
PushMaskScope scope(mask);
for (const Resolver& resolver : resolvers) {
const Bool armed = resolver.Resolve();
if (!armed) continue;
EXPECT_TRUE(MGPipeSubsystemDependenciesAreSet(resolver.Family, mask))
<< "at MOBILEGL_PIPE_PUSH=" << Describe(mask) << " the SERVER's " << resolver.Name
<< " ARMED the handle arm for family " << Describe(resolver.Family)
<< " while MG_Pipe/SubsystemDeps.def says its dependency bits are not all set. "
"The client withholds the family at this mask, so the server is running a "
"handle arm nobody is feeding - which is the half-run subsystem D-K2 exists "
"to make impossible.";
EXPECT_NE(mask & resolver.Family, 0ull)
<< resolver.Name << " armed with its own bit clear at " << Describe(mask);
}
}
}
// ---------------------------------------------------------------------------------------------
// 4. ...and the refusal really happens at the two documented lanes, so that test 3 is not
// vacuously green because every resolver said NO for an unrelated reason.
// ---------------------------------------------------------------------------------------------
TEST(SubsystemDepsTest, TheTwoDocumentedRefusalLanesStillRefuseAndTheFullMaskStillArms) {
using namespace MobileGL::MG_Backend::DirectGLES;
{
PushMaskScope scope(kMGPipeSubsystemsMigratedAtP5e);
EXPECT_TRUE(ResolveTextureResourceSubsystemArm())
<< "the texture family's handle arm does not come up at its own phase mask, so every "
"refusal assertion in this file is vacuous";
EXPECT_TRUE(ResolveSamplerSubsystemArm());
EXPECT_TRUE(ResolveProgramSubsystemArm());
// THE FRAMEBUFFER RESOLVER IS RECORDED, NOT ASSERTED, and the asymmetry is the point:
// ResolveFramebufferSubsystemArm folds D-C3's wire-caps refusal in beside the dependency
// rule (Managers.cpp:4323-4325), and that half asks the SERVER's published caps - which a
// bare unit binary with no session and no registered backend cannot answer in the
// affirmative. So a false here says nothing about D-K2 and asserting true would pin
// whatever a test binary happens to have linked. The sweep above still covers it in the
// direction that matters (it may never ARM where the table refuses).
RecordProperty("framebuffer_resolver_at_p5e", ResolveFramebufferSubsystemArm() ? 1 : 0);
}
{
// 0x7ff: bits 0..10, i.e. the texture family WITHOUT the sampler family - D-K2's fourth
// row, and the mask CMakeLists.txt's refusal lane pins.
PushMaskScope scope(0x7ffull);
EXPECT_FALSE(ResolveTextureResourceSubsystemArm())
<< "0x7ff is the mask whose texture family Espryt refuses by name; if it now arms, "
"D-K2's fourth row has been dropped on the server side while the client and the "
".def still carry it";
}
{
// 0x5ff: bits 0..8 and bit 10, i.e. the texture family WITHOUT the framebuffer bit and
// WITHOUT bit 11 - the second refusal lane CMakeLists.txt pins.
PushMaskScope scope(0x5ffull);
EXPECT_FALSE(ResolveTextureResourceSubsystemArm())
<< "0x5ff leaves bit 11 clear too, so the fourth row refuses it for the same reason";
}
}
+3 -109
View File
@@ -1429,10 +1429,9 @@ TEST_F(GeneralBufferTest, General_PersistentExplicitFlushOnlyDirtiesFlushedRange
mapped[1] = 200;
mapped[3] = 400;
// FlushExplicit persistent maps only reach the backend via explicit flushes.
bufferObject->SyncPersistentMappedRange();
EXPECT_EQ(bufferObject->GetChangeSerial(), baseSerial);
// The explicit flush is what GL 4.6 6.2.1 promises reaches the store. (Until P13 W6 this also
// asserted that a per-draw sync moved nothing; the record arm's push publishes the map itself,
// so that was the deleted frontend arm's behaviour, not a rule.)
FlushMappedBufferRange(GL_ARRAY_BUFFER, sizeof(GLint), sizeof(GLint));
EXPECT_GT(bufferObject->GetChangeSerial(), baseSerial);
@@ -1669,112 +1668,7 @@ namespace {
};
} // namespace
TEST_F(GeneralBufferTest, General_PersistentCoherentZeroCopyStressNoPerDrawReupload) {
ZeroCopyMockBackend mock;
g_zeroCopyMock = &mock;
ScopedBackendOps scopedOps(&kZeroCopyMockOps);
GLuint buffer = 0;
GenBuffers(1, &buffer);
BindBuffer(GL_ARRAY_BUFFER, buffer);
constexpr SizeT kCount = 4096; // 16 KiB of GLint - a "large" dynamic ring buffer
Vector<GLint> initial(kCount, 0);
BufferStorage(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(kCount * sizeof(GLint)), initial.data(),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
ASSERT_EQ(GetError(), GL_NO_ERROR);
auto* mapped = static_cast<GLint*>(
MapBufferRange(GL_ARRAY_BUFFER, 0, static_cast<GLsizeiptr>(kCount * sizeof(GLint)),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT));
ASSERT_NE(mapped, nullptr);
EXPECT_EQ(mock.acquireMapCalls, 1);
auto bufferObject = MG_State::pGLContext->GetBufferObject(buffer);
ASSERT_NE(bufferObject, nullptr);
EXPECT_TRUE(bufferObject->IsBackendPersistentMapped());
// The app maps straight onto the backend's GPU storage...
EXPECT_EQ(static_cast<void*>(mapped), static_cast<void*>(mock.gpu.data()));
// ...and EVERY consumer (they all read MappedData() now) resolves to that same GPU
// memory, not a stale shadow. This is the invariant whose violation corrupted UBOs.
EXPECT_EQ(static_cast<const void*>(bufferObject->MappedData()), static_cast<const void*>(mock.gpu.data()));
// Isolate the per-draw behavior: storage creation legitimately issued one Respecify.
mock.subDataCalls = 0;
mock.flushCalls = 0;
mock.respecifyCalls = 0;
constexpr int kFrames = 240;
constexpr int kDrawsPerFrame = 64; // 15,360 draws total
for (int frame = 0; frame < kFrames; ++frame) {
for (int draw = 0; draw < kDrawsPerFrame; ++draw) {
mapped[draw] = frame * 1000 + draw; // MC writes through the coherent map
bufferObject->SyncPersistentMappedRange(); // draw-time hook
}
}
// The crux: across 15,360 draws, NOT ONE per-draw backend transfer.
EXPECT_EQ(mock.acquireMapCalls, 1);
EXPECT_EQ(mock.subDataCalls, 0);
EXPECT_EQ(mock.flushCalls, 0);
EXPECT_EQ(mock.respecifyCalls, 0);
// The app's writes are coherently visible in the backend storage (no copy), and a
// reader going through MappedData() sees them too.
const auto* gpuInts = reinterpret_cast<const GLint*>(mock.gpu.data());
const auto* viaMapped = reinterpret_cast<const GLint*>(bufferObject->MappedData());
for (int draw = 0; draw < kDrawsPerFrame; ++draw) {
EXPECT_EQ(mapped[draw], (kFrames - 1) * 1000 + draw);
EXPECT_EQ(gpuInts[draw], (kFrames - 1) * 1000 + draw);
EXPECT_EQ(viaMapped[draw], (kFrames - 1) * 1000 + draw);
}
EXPECT_TRUE(UnmapBuffer(GL_ARRAY_BUFFER));
EXPECT_EQ(mock.flushCalls, 0);
EXPECT_EQ(mock.subDataCalls, 0);
g_zeroCopyMock = nullptr;
}
TEST_F(GeneralBufferTest, General_PersistentCoherentFallbackSyncsPerDrawWhenBackendDeclines) {
// Backend cannot back the map => the legacy CPU-shadow path must still be correct,
// and this documents the behavior the fix removed (one whole-range transfer per draw),
// proving the harness above would catch a regression (non-zero per-draw count).
ZeroCopyMockBackend mock;
mock.provideMap = false;
g_zeroCopyMock = &mock;
ScopedBackendOps scopedOps(&kZeroCopyMockOps);
GLuint buffer = 0;
GenBuffers(1, &buffer);
BindBuffer(GL_ARRAY_BUFFER, buffer);
constexpr SizeT kCount = 256;
Vector<GLint> initial(kCount, 0);
BufferStorage(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(kCount * sizeof(GLint)), initial.data(),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT);
ASSERT_EQ(GetError(), GL_NO_ERROR);
auto* mapped = static_cast<GLint*>(
MapBufferRange(GL_ARRAY_BUFFER, 0, static_cast<GLsizeiptr>(kCount * sizeof(GLint)),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT));
ASSERT_NE(mapped, nullptr);
EXPECT_EQ(mock.acquireMapCalls, 0); // backend declined => shadow-backed map
auto bufferObject = MG_State::pGLContext->GetBufferObject(buffer);
ASSERT_NE(bufferObject, nullptr);
EXPECT_FALSE(bufferObject->IsBackendPersistentMapped());
constexpr int kDraws = 100;
for (int draw = 0; draw < kDraws; ++draw) {
mapped[draw % kCount] = draw;
bufferObject->SyncPersistentMappedRange();
}
// Legacy behavior: every draw pushed the whole range -> one SubData per draw.
EXPECT_EQ(mock.subDataCalls, kDraws);
EXPECT_TRUE(UnmapBuffer(GL_ARRAY_BUFFER));
g_zeroCopyMock = nullptr;
}
// ---------------------------------------------------------------------------
// MOBILEGL_COHERENT_AS_FLUSH: persistent FLUSH_EXPLICIT mapping requests are
+1 -20
View File
@@ -268,25 +268,6 @@ TEST_F(SplitBufferSet, Row5EndTransformFeedbackMarksTheCaptureTargets) {
EXPECT_EQ(MG_Record::ProducerMarkCount(GpuWriteProducer::EndTransformFeedbackCapture), 1u);
}
// THE GATE ITSELF. On the monolith path the six backend sites are still the only producers and
// a second marker would be new behaviour (D-J) - and rows 4 and 5 would remove a stall that
// monolith is entitled to keep.
TEST_F(SplitBufferSet, TheWholeSetIsInertOnTheMonolithPath) {
MG_Config::Transport = MG_Config::TransportMode::Monolith;
auto ssbo = MakeBuffer(18u, 256);
MG_State::pGLContext->GetBufferBindingPoint(BufferTarget::ShaderStorage, 0).Bind(ssbo);
MG_State::pGLContext->TouchBufferBindingPoint(BufferTarget::ShaderStorage, 0);
MG_Record::MarkGpuWritesForDraw();
MG_Record::MarkGpuWritesForDispatch();
MG_Record::MarkReadPixelsPackBuffer();
MG_Record::MarkEndTransformFeedbackCaptureTargets();
for (SizeT row = 0; row < static_cast<SizeT>(GpuWriteProducer::Count); ++row) {
EXPECT_EQ(MG_Record::ProducerMarkCount(static_cast<GpuWriteProducer>(row)), 0u)
<< "row " << row << " fired with Transport == Monolith";
}
}
// =====================================================================================
// The persistent-map push
@@ -814,7 +795,7 @@ TEST(SplitBufferSet, Row3TransformFeedbackTargetsAreOnlyMarkedWhileACaptureIsAct
}
TEST(SplitBufferSet, Row4AReadPixelsIntoAPackPboMarksThePbo) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, Row5EndTransformFeedbackMarksTheCaptureTargets) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, TheWholeSetIsInertOnTheMonolithPath) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, MembershipIsSyncPersistentMappedRangesOwnEarlyOutChain) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, ThePushCutsTheMappedSpanIntoBlocksAndMovesPmap) { MGL_SPLIT_ONLY_OR_SKIP(); }
+2 -1
View File
@@ -511,7 +511,8 @@ TEST(TextureEmit, AWholeLevelUploadCarriesZeroStrides) {
EXPECT_EQ(record.SourceIsVerbatimLevelShadow, 1)
<< "the client always declares the level shadow; the server clears it when it converts";
EXPECT_EQ(record.Blob.Seg, kMGHostSpanSegNone);
EXPECT_EQ(record.Blob.Size, 0u) << "a monolith record does not declare its blob";
EXPECT_EQ(record.Blob.Size, 64u * 64u * 4u)
<< "the record declares its blob on every arm since P13 W6 (the record arm reads it)";
EXPECT_NE(record.Blob.Offset, 0u) << "Blob.Offset is the level shadow's address in monolith";
EXPECT_EQ(Textures().SubDataPieceCount(), 1u)
<< "a level that fits one record is exactly one piece (fix A2's counter), so the "
@@ -237,7 +237,9 @@ namespace {
const auto& attrib = vao->GetAttribute(index);
const MGPVertexAttribWire& wire = Emitter().LastAttributes()[static_cast<SizeT>(i)];
SCOPED_TRACE(::testing::Message() << "attribute " << i);
EXPECT_EQ(wire.Offset, static_cast<Uint64>(attrib.Offset));
// Client addresses never cross: an attribute with no buffer carries offset 0 (its
// bytes ride an owned buffer at draw time), every arm since P13 W6.
EXPECT_EQ(wire.Offset, attrib.Buffer ? static_cast<Uint64>(attrib.Offset) : 0ull);
EXPECT_EQ(wire.Stride, static_cast<Int32>(attrib.Stride));
EXPECT_EQ(wire.Type, static_cast<Uint32>(attrib.Type));
EXPECT_EQ(wire.Size, static_cast<Uint8>(attrib.Size));
-305
View File
@@ -369,129 +369,7 @@ TEST(DirectGLESSanity, AdvertisesVoxyRequiredRenderingExtensions) {
extensions.end());
}
// A multisample texture is fetched, never filtered, so the mip-chain completeness rules never
// apply to it (GL 4.6 core 8.17). It has exactly one level and MIN_FILTER's initial value is
// NEAREST_MIPMAP_LINEAR, so asking those rules anyway calls EVERY multisample texture incomplete
// - and both backends express "incomplete" as "leave the native target unbound", which makes the
// shader's sampler2DMS read zero from a texture that was written correctly.
//
// That is KHR-GL43.compute_shader.resource-texture: it clears its 2DMS texture to 123.0 through
// an FBO (which succeeds - the ES clear is issued on a COMPLETE 4-sample framebuffer with no
// error) and then fails at the first sampler2DMS element because the texture was never bound.
TEST(DirectGLESSanity, BindsAMultisampleTextureDespiteTheDefaultMipmapFilter) {
using namespace MobileGL;
namespace DirectGLES = MG_Backend::DirectGLES;
ScopedDirectGLESTextureBindings state;
GLuint frontendTexture = 0;
MG_Impl::GLImpl::GenTextures(1, &frontendTexture);
ASSERT_NE(frontendTexture, 0u);
MG_Impl::GLImpl::BindTexture(GL_TEXTURE_2D_MULTISAMPLE, frontendTexture);
const auto& textureObject = MG_State::pGLContext->GetTextureUnitObject(0)
.GetBindingSlot(TextureTarget::Texture2DMultisample)
.GetBoundObject();
ASSERT_NE(textureObject, nullptr);
textureObject->SetInternalFormat(TextureInternalFormat::RGBA8);
textureObject->SetSamples(4);
textureObject->SetFixedSampleLocations(false);
// One level, 4x4 - the shape glTexImage2DMultisample produces, and a size whose mip chain
// would need three levels if the filter rules were (wrongly) applied.
MG_State::GLState::AsMipmapTexture(textureObject.get())
->AllocateStorage(TextureUploadTarget::Texture2DMultisample, 0, {{4, 4, 1}, 4});
// The precondition that used to poison it, asserted rather than assumed: the texture's own
// sampler still reports a mipmapping filter, because GL's initial MIN_FILTER is
// NEAREST_MIPMAP_LINEAR and a multisample texture has no way (and no reason) to change it.
// If a future default made this None the test would pass without covering anything.
const auto& sampler = textureObject->GetSamplerObject();
ASSERT_NE(sampler, nullptr);
ASSERT_NE(sampler->GetMipmapMode(), SamplerMipmapMode::None)
<< "fixture is stale: the default sampler no longer asks for mipmapping, so this test "
"would not exercise the multisample guard";
EXPECT_FALSE(MG_State::GLState::SamplesAsIncompleteTexture(textureObject.get(), sampler.get()))
<< "a multisample texture is never filter-incomplete";
auto& backendTexture = DirectGLES::TextureImpl::g_backendTextureObjects.GetOrCreate(textureObject);
backendTexture = MakeShared<DirectGLES::TextureImpl::BackendTextureObject>();
const GLuint backendTextureId = backendTexture->GetBackendTextureId();
// The symptom itself: the per-unit walk has to actually bind it. BindCurrentTextures() is
// the per-draw walk - it reads GetProgramForDraw - so the block it reads is the one a draw
// fills; without saying so, its first read is Fatal{UnmigratedPipeInput} in a push build.
MG_Test::ScopedPipeVerb draw(MG_Pipe::MGPipeVerb::DrawArrays);
DirectGLES::BindCurrentTextures();
ASSERT_EQ(state.bindCalls.size(), 1u)
<< "the multisample texture was not bound; every texelFetch against it reads zero";
EXPECT_EQ(state.bindCalls[0].target, GL_TEXTURE_2D_MULTISAMPLE);
EXPECT_EQ(state.bindCalls[0].texture, backendTextureId);
}
TEST(DirectGLESSanity, BindingZeroClearsPreviousNativeTextureBinding) {
using namespace MobileGL;
namespace DirectGLES = MG_Backend::DirectGLES;
ScopedDirectGLESTextureBindings state;
GLuint frontendTexture = 0;
MG_Impl::GLImpl::GenTextures(1, &frontendTexture);
ASSERT_NE(frontendTexture, 0u);
MG_Impl::GLImpl::BindTexture(GL_TEXTURE_2D, frontendTexture);
const auto& frontendTextureObject = MG_State::pGLContext->GetTextureUnitObject(0)
.GetBindingSlot(TextureTarget::Texture2D)
.GetBoundObject();
ASSERT_NE(frontendTextureObject, nullptr);
ASSERT_EQ(frontendTextureObject->GetExternalIndex(), frontendTexture);
// A texture with no image is incomplete, and an incomplete texture samples as (0, 0, 0, 1) -
// which DirectGLES expresses by leaving the native target unbound (see "sample a
// mipmap-incomplete texture as black"). This test is about the bind-0 clear, so the texture
// has to be complete enough to get bound in the first place: a format plus a level 0. At 1x1
// that single level is the whole mip chain, so it stays complete under any filter. The state
// is set directly rather than through glTexImage2D because the mock GLES table below wires
// only the binding entry points, not the upload path.
frontendTextureObject->SetInternalFormat(TextureInternalFormat::RGBA8);
MG_State::GLState::AsMipmapTexture(frontendTextureObject.get())
->AllocateStorage(TextureUploadTarget::Texture2D, 0, {{1, 1, 1}, 4});
ASSERT_FALSE(MG_State::GLState::SamplesAsIncompleteTexture(
frontendTextureObject.get(), frontendTextureObject->GetSamplerObject().get()));
auto& backendTexture = DirectGLES::TextureImpl::g_backendTextureObjects.GetOrCreate(frontendTextureObject);
backendTexture = MakeShared<DirectGLES::TextureImpl::BackendTextureObject>();
const GLuint backendTextureId = backendTexture->GetBackendTextureId();
// Each walk below is the texture half of one draw, so each gets its own verb (the second
// and third stand after frontend state moved, exactly as a second entry point's fill would).
MG_Test::ScopedPipeVerb draw(MG_Pipe::MGPipeVerb::DrawArrays);
DirectGLES::BindCurrentTextures();
ASSERT_EQ(state.bindCalls.size(), 1u);
EXPECT_EQ(state.bindCalls[0].target, GL_TEXTURE_2D);
EXPECT_EQ(state.bindCalls[0].texture, backendTextureId);
// The default 1D slot maps to the same native ES target as 2D. It must not clear and force a
// redundant rebind while the real 2D frontend object remains current.
draw.Renew();
DirectGLES::BindCurrentTextures();
EXPECT_EQ(state.bindCalls.size(), 1u);
MG_Impl::GLImpl::BindTexture(GL_TEXTURE_2D, 0);
ASSERT_TRUE(MG_State::GLState::IsUndefinedDefaultTexture(
MG_State::pGLContext->GetTextureUnitObject(0)
.GetBindingSlot(TextureTarget::Texture2D)
.GetBoundObject()
.get()));
draw.Renew();
DirectGLES::BindCurrentTextures();
ASSERT_EQ(state.bindCalls.size(), 2u);
EXPECT_EQ(state.bindCalls[1].target, GL_TEXTURE_2D);
EXPECT_EQ(state.bindCalls[1].texture, 0u);
EXPECT_EQ(DirectGLES::TextureImpl::g_boundTexturesCache[0][static_cast<SizeT>(TextureTarget::Texture2D)],
nullptr);
}
TEST(DirectGLESSanity, ProvidesNamedFramebufferBlitForDirectStateAccess) {
MobileGL::MG_Backend::DirectGLES::BackendObject_DirectGLES backend;
@@ -3092,103 +2970,6 @@ namespace {
}
} // namespace
// The per-unit texture sync memo BORROWS the binding slot: an entry holds a pointer to the
// slot's shared_ptr plus the backend twin of whatever was in it when the entry was built. Its
// keys (context id, bind-generation epoch, high-water mark, sampling generation) are the primary
// guard, but they are all derived state - so the memo also has to survive a slot swap that never
// reached them.
//
// It did not. The DSA by-name emulation swapped a slot silently, every key still matched, and
// the replay drove texture A's backend twin from texture B's frontend object: A's backend
// storage was re-specified with B's shape, destroying anything A only ever had on the GPU. On
// Espryt + Iris/BSL that blanked Minecraft's 16x16 lightmap the moment a 2048x2048 shadow map
// was uploaded through a by-name call, and since the text shader multiplies by the lightmap,
// `if (color.a < 0.1) discard` then threw away every glyph in the process - HUD, menus and the
// vanilla title screen alike.
TEST(DirectGLESTextureSync, UnitMemoRefusesToDriveATwinFromAnotherTexture) {
using namespace MobileGL;
// P13 W3b: PINNED TO THE P2 MASK, in its own process (ctest runs every case in one). The code
// under test - the monolith arm's borrowed-slot unit list and PairingsIntact - does not depend
// on the mask and is live at the shipping mask (UnitTexturesByHandle() is false on monolith).
// The mask only picks the twin-sync body this probe OBSERVES: at 0x3fff that body reads
// applier records, and a unit-lane process cannot create them (MGPipeApplyResourceCreate
// declines under NoP4aConsumer), so there the probe would see nothing. The hazard itself is
// not reachable through public GL any more (the by-name emulation bumps the bind generation
// and restores the slot before any draw - measured: DsaUpdateKeepsTheBoundUnitScenario stays
// green with both defences removed), so this state-level construction is its only red.
const Uint64 savedMask = MG_Config::Features.PipePush;
MG_Config::Features.PipePush = MG_Pipe::kMGPipeSubsystemsMigratedAtP2;
ASSERT_FALSE(MG_Backend::DirectGLES::TextureResourceSubsystemEnabled())
<< "the texture-resource family arm latched before this case pinned its mask; run the case "
"in its own process, as ctest does";
ScopedDirectGLESTextureBindings scoped; // fresh GLContext + registry + binding caches
Vector<TexSpecCall> specs;
ScopedTexSpecRecording recording(specs);
auto functions = MG_Backend::DirectGLES::g_GLESFuncs;
functions.glBindTexture = TS_BindTexture;
functions.glActiveTexture = TS_ActiveTexture;
functions.glTexImage2D = TS_TexImage2D;
functions.glTexParameteri = TS_TexParameteri;
functions.glTexParameterf = TS_TexParameterf;
functions.glTexParameterfv = TS_TexParameterfv;
functions.glPixelStorei = TS_PixelStorei;
functions.glBindBuffer = TS_BindBuffer;
MG_Backend::DirectGLES::SetGLESFuncsTable(functions);
GLuint names[2] = {};
MG_Impl::GLImpl::GenTextures(2, names);
// `foreign` stands in for the shadow map, `resident` for the lightmap. Both are fully
// specified BEFORE the first sync so that nothing between the two syncs can move the
// sampling-resolution generation and invalidate the memo for an unrelated reason.
const auto foreign = MakeComplete2DTexture(names[1], 32);
const auto resident = MakeComplete2DTexture(names[0], 16);
ASSERT_NE(foreign, nullptr);
ASSERT_NE(resident, nullptr);
// First sync: builds the memo with unit 0 -> `resident`, and gives `resident`'s twin its
// 16x16 backend storage. The unit walk is the per-draw one, so both syncs below stand in a
// draw - the fill is what a real glDraw* would have done before reaching this helper.
MG_Test::ScopedPipeVerb draw(MG_Pipe::MGPipeVerb::DrawArrays);
MG_Backend::DirectGLES::TextureImpl::SyncNeccessaryTextures();
auto* residentSlot = MG_Backend::DirectGLES::TextureImpl::g_backendTextureObjects.Find(resident.get());
ASSERT_NE(residentSlot, nullptr);
ASSERT_NE(*residentSlot, nullptr);
const GLuint residentBackendId = (*residentSlot)->GetBackendTextureId();
ASSERT_NE(residentBackendId, 0u);
ASSERT_FALSE(specs.empty());
EXPECT_EQ(specs.back().texture, residentBackendId);
EXPECT_EQ(specs.back().width, 16);
// The hazard, reproduced at the state level: put `foreign` on the slot the memo borrows
// WITHOUT telling the binding accounting, exactly as the by-name emulation used to.
MG_State::pGLContext->GetTextureUnitObject(0).GetBindingSlot(TextureTarget::Texture2D).Bind(foreign);
const SizeT specsBeforeReplay = specs.size();
// The second draw. Its fill re-reads the memo's keys off the live context, which is the
// premise being tested: the silent slot swap moved none of them.
draw.Renew();
MG_Backend::DirectGLES::TextureImpl::SyncNeccessaryTextures();
// Above all, nothing may have re-specified the RESIDENT texture's backend storage. That single
// call is what destroyed the lightmap. (Checked FIRST since P13 W3b, so a red names the damage
// rather than stopping at the twin assertions below.)
for (SizeT i = specsBeforeReplay; i < specs.size(); ++i) {
EXPECT_NE(specs[i].texture, residentBackendId)
<< "the stale memo entry re-specified the resident texture's backend storage with "
<< specs[i].width << "x" << specs[i].height;
}
// ...and `foreign` must have been synced through its OWN twin.
auto* foreignSlot = MG_Backend::DirectGLES::TextureImpl::g_backendTextureObjects.Find(foreign.get());
ASSERT_NE(foreignSlot, nullptr) << "the replay never reached the texture now in the slot";
ASSERT_NE(*foreignSlot, nullptr);
const GLuint foreignBackendId = (*foreignSlot)->GetBackendTextureId();
EXPECT_NE(foreignBackendId, residentBackendId);
MG_Impl::GLImpl::BindTexture(GL_TEXTURE_2D, 0);
MG_Config::Features.PipePush = savedMask;
}
// P5e (tx2), CONTRACT-P5E §4.3: THE HANDLE ARM'S SIBLING OF UnitMemoRefusesToDriveATwinFromAnotherTexture,
// WITH ABA AS THE HAZARD INSTEAD OF A SILENT SLOT SWAP. (P13 W3b retired that case: it ran only at
@@ -4473,92 +4254,6 @@ TEST(DirectGLESSlotTable, ASavedCopyOfARealRegistryDropsTheTwinOnTheSameNotice)
EXPECT_FALSE(registry.DestroyByLifetimeId(0)) << "sanity: a null id frees nothing";
}
// P3a REWORK C-1's gate, and the case that would have caught it.
//
// A persistently mapped buffer whose store was NOT adopted - under the 16 MiB threshold, or
// with DisableLargeBufferAdoption, or with no EXT_buffer_storage - is written through its
// pointer and emits NOTHING: no resource call, no serial, no mutation epoch. The only thing
// that can make the next draw carry those bytes to the GPU is the per-draw clean probe
// answering DIRTY, which is why the pre-P3a probe asks the frontend IsMapped() instead of
// asking a serial. The first cut of the handle arm replaced that question with the applier
// record's HasLiveHostWrites - a field D-A4 pins false and nothing in P3a writes - so the
// answer became CLEAN forever, EnsureBufferResourceForHandle (and with it
// SyncPersistentMappedRange, the ONLY per-draw push for a vertex/uniform/SSBO persistent map)
// was never reached again, and the frame drew the last uploaded bytes with no diagnostic.
//
// The case is built so it can go red for exactly that: every other question is arranged to
// answer clean, and the first EXPECT asserts so before the map is taken.
TEST(DirectGLESBufferDrawProbe, ALiveHostMapKeepsTheHandleArmProbeDirtyBetweenTwoDraws) {
using namespace MobileGL;
using namespace MobileGL::MG_Backend::DirectGLES;
using namespace MobileGL::MG_State::GLState;
if (!EsprytSlotTablesEnabled()) {
GTEST_SKIP() << "the handle-keyed resource table only exists on the {slot, gen} arm";
}
auto owner = MakeShared<BufferObject>(0u);
owner->Respecify(256, nullptr);
const MG_Pipe::MGPipeHandle res =
MG_Pipe::MGPipeSlots().Acquire(MG_Pipe::MGPipeKind::Buffer, owner->GetLifetimeId());
ASSERT_FALSE(MG_Pipe::MGPipeHandleIsNull(res));
// The applier's record, written straight into the state rather than through package A's
// entry points: this case is about the PROBE, and the probe reads the record.
auto& applier = MG_Pipe::MGPipeApplier();
if (applier.Resources.size() <= static_cast<SizeT>(res.Slot)) {
applier.Resources.resize(static_cast<SizeT>(res.Slot) + 1);
}
auto& record = applier.Resources[res.Slot];
record = {};
record.Gen = res.Gen;
record.Live = true;
record.Desc.Width = 256;
record.Serial = 7;
// Pinned false by D-A4 and by the MOBILEGL_PIPE_VERIFY assertion in the probe. That is
// exactly why it cannot answer the map question on its own.
record.HasLiveHostWrites = false;
auto& twin = BufferImpl::g_backendBufferResources.GetOrCreate(res);
twin = MakeShared<BufferImpl::GLESBufferResource>();
auto* const resource = twin.get();
resource->id = 1; // a name, never used: this probe issues no GL
resource->contextGeneration = BufferImpl::CurrentBufferContextGeneration();
resource->storageInitialized = true;
resource->storageSize = 256;
resource->syncedChangeSerial = record.Serial;
ASSERT_TRUE(BufferImpl::IsBufferDrawCleanByHandle(res, resource, owner.get()))
<< "the fixture is not clean before the map is taken, so this case cannot isolate the "
"live-map question it exists for";
// GL_MAP_PERSISTENT_BIT | GL_MAP_WRITE_BIT, shadow-backed (nothing adopts it: no backend
// AcquirePersistentMap is registered in this binary). This is the state the app writes
// through with no GL call at all.
void* const mapped = owner->AcquireMemoryRange(
Range1D{0, 256}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
ASSERT_NE(mapped, nullptr);
ASSERT_TRUE(owner->IsMapped());
ASSERT_FALSE(owner->IsBackendPersistentMapped())
<< "the map was adopted, so this is the zero-copy case and not the one under test";
// The write between the two draws. It moves NOTHING the record can see.
static_cast<Uint8*>(mapped)[0] = 0x5Au;
EXPECT_EQ(record.Serial, 7u) << "sanity: a write through a persistent map emits no call";
EXPECT_FALSE(BufferImpl::IsBufferDrawCleanByHandle(res, resource, owner.get()))
<< "the handle arm called a persistently mapped, non-adopted buffer draw-CLEAN, so the "
"bytes just written through its pointer would never reach the GPU: the live-map "
"question has been answered from HasLiveHostWrites, which P3a pins false";
owner->ReleaseMemory(false);
EXPECT_TRUE(BufferImpl::IsBufferDrawCleanByHandle(res, resource, owner.get()))
<< "the probe stayed dirty after the unmap, i.e. it is not the map that is being read";
BufferImpl::g_backendBufferResources.ReleaseByHandle(res);
MG_Pipe::MGPipeSlots().Free(MG_Pipe::MGPipeKind::Buffer, res);
record = {};
}
// P5 b1's half of the case above: THE PIN IS LIFTED, AND THIS IS WHAT REPLACED IT.
//