1diff --git a/src/runtime/src/native/corehost/corehost.cpp b/src/runtime/src/native/corehost/corehost.cpp
2index 5edc2fbf5d5..1b3f5b1a23a 100644
3--- a/src/runtime/src/native/corehost/corehost.cpp
4+++ b/src/runtime/src/native/corehost/corehost.cpp
5@@ -40,14 +40,27 @@
6 #define EMBED_HASH_LO_PART_UTF8 "74e592c2fa383d4a3960714caef0c4f2"
7 #define EMBED_HASH_FULL_UTF8 (EMBED_HASH_HI_PART_UTF8 EMBED_HASH_LO_PART_UTF8) // NUL terminated
8
9+// This avoids compiler optimization which cause EMBED_HASH_HI_PART_UTF8 EMBED_HASH_LO_PART_UTF8
10+// to be placed adjacent causing them to match EMBED_HASH_FULL_UTF8 when searched for replacing.
11+// See https://github.com/dotnet/runtime/issues/109611 for more details.
12+static bool compare_memory_nooptimization(volatile const char* a, volatile const char* b, size_t length)
13+{
14+ for (size_t i = 0; i < length; i++)
15+ {
16+ if (*a++ != *b++)
17+ return false;
18+ }
19+ return true;
20+}
21+
22 bool is_exe_enabled_for_execution(pal::string_t* app_dll)
23 {
24 constexpr int EMBED_SZ = sizeof(EMBED_HASH_FULL_UTF8) / sizeof(EMBED_HASH_FULL_UTF8[0]);
25 constexpr int EMBED_MAX = (EMBED_SZ > 1025 ? EMBED_SZ : 1025); // 1024 DLL name length, 1 NUL
26
27 // Contains the EMBED_HASH_FULL_UTF8 value at compile time or the managed DLL name replaced by "dotnet build".
28- // Must not be 'const' because std::string(&embed[0]) below would bind to a const string ctor plus length
29- // where length is determined at compile time (=64) instead of the actual length of the string at runtime.
30+ // Must not be 'const' because strlen below could be determined at compile time (=64) instead of the actual
31+ // length of the string at runtime.
32 static char embed[EMBED_MAX] = EMBED_HASH_FULL_UTF8; // series of NULs followed by embed hash string
33
34 static const char hi_part[] = EMBED_HASH_HI_PART_UTF8;
35@@ -64,10 +77,10 @@ bool is_exe_enabled_for_execution(pal::string_t* app_dll)
36 size_t hi_len = (sizeof(hi_part) / sizeof(hi_part[0])) - 1;
37 size_t lo_len = (sizeof(lo_part) / sizeof(lo_part[0])) - 1;
38
39- std::string binding(&embed[0]);
40- if ((binding.size() >= (hi_len + lo_len)) &&
41- binding.compare(0, hi_len, &hi_part[0]) == 0 &&
42- binding.compare(hi_len, lo_len, &lo_part[0]) == 0)
43+ size_t binding_len = strlen(&embed[0]);
44+ if ((binding_len >= (hi_len + lo_len))
45+ && compare_memory_nooptimization(&embed[0], hi_part, hi_len) == 0
46+ && compare_memory_nooptimization(&embed[hi_len], lo_part, lo_len))
47 {
48 trace::error(_X("This executable is not bound to a managed DLL to execute. The binding value is: '%s'"), app_dll->c_str());
49 return false;