[GR-53803] Only allow Unsafe.allocateInstance for types registered explicitly in the configuration. #8869
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR tightens the rule
Unsafe.allocateInstance
in the strict reflection configuration mode (whenThrowMissingRegistrationErrors
is enabled): now only types explicitly registered for Unsafe allocation can be allocated that way, i.e., without running a constructor.The reflection configuration files always had the
unsafeAllocated
property for types, but we were not enforcing that. Instead, it was possible to allocate all types that the static analysis identified as instantiated. Since there was not a programmatic way to register a type in aFeature
, this PR addsregisterAsUnsafeAllocated
toFeature.BeforeAnalysisAccess
.The JNI method
AllocObject
does the same asUnsafe.allocateInstance
, and is actually implemented exactly like that in SVM. While the preferred way to allocate new instances is to use the JNI function that allocates a new instance and invokes the constructor in the same function, it is also possible to useAllocObject
first to allocate an uninitizalized instance, and then via a separate JNI function invoke a constructor on this already existing instance. Since JNI usage is rare, all types that have a constructor registered for JNI are automatically also registered for unsafe allocation. In addition,AllocObject
is now tracked by the tracing agent so that such types have theunsafeAllocated
property set.Why tighten the rules? The static analysis can find out which instance fields are never
null
, and remove unnecessarynull
checks. But such an optimization is only safe when we know that types are never instantiated without running a constructor, in which case all fields always remain uninitialized. With this new enforcement, the few types explicitly registered for unsafe allocation can easily be excluded from the optimization.