11/****************************************************************************
2- * arch/sim/src/sim/up_macho_init.c
2+ * arch/sim/src/sim/posix/sim_macho_init.c
3+ *
4+ * SPDX-License-Identifier: Apache-2.0
35 *
46 * Licensed to the Apache Software Foundation (ASF) under one or more
57 * contributor license agreements. See the NOTICE file distributed with
2224 * Included Files
2325 ****************************************************************************/
2426
27+ #include <sys/mman.h>
28+
2529#include <assert.h>
2630#include <stdlib.h>
31+ #include <unistd.h>
2732
2833/****************************************************************************
2934 * Private Data
@@ -49,21 +54,51 @@ static const char **g_saved_argv;
4954static const char * * g_saved_envp ;
5055static const char * * g_saved_apple ;
5156
57+ static void
58+ allow_write (const void * start , const void * end )
59+ {
60+ const size_t page_size = sysconf (_SC_PAGE_SIZE );
61+ const size_t page_mask = ~(page_size - 1 );
62+ void * p = (void * )((uintptr_t )start & page_mask );
63+ size_t sz = ((uintptr_t )end - (uintptr_t )p + page_size - 1 ) & ~page_mask ;
64+
65+ /* It seems that Monterey (12.1) maps the section read-only.
66+ * Make it writable as we want to patch it.
67+ * This was not necessary for Mojave.
68+ * Ignore failures as this might not be critical, depending on
69+ * the OS version.
70+ */
71+
72+ mprotect (p , sz , PROT_READ | PROT_WRITE );
73+ }
74+
5275__attribute__((constructor ))
5376static void save_and_replace_init_funcs (int argc , const char * argv [],
5477 const char * envp [],
5578 const char * apple [])
5679{
80+ init_func_t * fp ;
81+ unsigned int nfuncs = & mod_init_func_end - & mod_init_func_start ;
82+
83+ assert (nfuncs > 0 );
84+ g_num_saved_init_funcs = nfuncs - 1 ;
85+ if (g_num_saved_init_funcs == 0 )
86+ {
87+ /* This function is the only constructor in the binary.
88+ * no need to apply the following hack.
89+ */
90+
91+ return ;
92+ }
93+
5794 g_saved_argc = argc ;
5895 g_saved_argv = argv ;
5996 g_saved_envp = envp ;
6097 g_saved_apple = apple ;
61- init_func_t * fp ;
62- unsigned int nfuncs = & mod_init_func_end - & mod_init_func_start ;
63- assert (nfuncs > 1 );
64- g_num_saved_init_funcs = nfuncs - 1 ;
98+
6599 g_saved_init_funcs = malloc (g_num_saved_init_funcs *
66100 sizeof (* g_saved_init_funcs ));
101+ allow_write (& mod_init_func_start , & mod_init_func_end );
67102 int i = 0 ;
68103 for (fp = & mod_init_func_start ; fp < & mod_init_func_end ; fp ++ )
69104 {
0 commit comments