Prevent adding new modules after the defaults mutator

Modules created after a mutator has run will not see the effects
of that mutator. So it's better to create modules as early as possible.

Bug: 361816274
Test: m nothing --no-skip-soong-tests
Change-Id: I21c7fae7c137ab091fd8a63f7432a6df9b474959
diff --git a/android/hooks.go b/android/hooks.go
index 2ad3b5f..bd2fa5e 100644
--- a/android/hooks.go
+++ b/android/hooks.go
@@ -95,10 +95,17 @@
 
 type createModuleContext interface {
 	Module() Module
+	HasMutatorFinished(mutatorName string) bool
 	createModule(blueprint.ModuleFactory, string, ...interface{}) blueprint.Module
 }
 
 func createModule(ctx createModuleContext, factory ModuleFactory, ext string, props ...interface{}) Module {
+	if ctx.HasMutatorFinished("defaults") {
+		// Creating modules late is oftentimes problematic, because they don't have earlier
+		// mutators run on them. Prevent making modules after the defaults mutator has run.
+		panic("Cannot create a module after the defaults mutator has finished")
+	}
+
 	inherited := []interface{}{&ctx.Module().base().commonProperties}
 
 	var typeName string