浅析 Android 平台 mono执行机制 by郡墙

在 Android平台中采用Mono机制编译、处理C#语言编写的逻辑代码,编译之后本地存储IL指令。在游戏运行阶段存在代码动态编译的过程,原理为:利用 Unity3D引擎的 Mono jit机制将IL指令编译为机器可识别的汇编指令。

Mono 是什么?

Sponsored by Microsoft, Mono is an open source implementation of Microsoft's .NET Framework based on the ECMA standards for C# and the Common Language Runtime. A growing family of solutions and an active and enthusiastic contributing community is helping position Mono to become the leading choice for development of cross platform applications.

引用官方的介绍,这部分不是本文的重点,有兴趣的读者可以自行前往官网了解。

Mono 的执行流程

首先我们从 mono的入口函数开始分析

大致运行流程如下

<pre class="public-DraftStyleDefault-pre" spellcheck="false" style="box-sizing: border-box; font-family: monospace, monospace; font-size: 18px; margin: 0px auto 32px; color: rgb(90, 90, 91); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;"> Main() => mono_main_with_optinos() => mono_main() => mini_init() => mono_assembly_open() => main_thread_handler() => mini_cleanup() </pre>

其中 main_thread_handler 函数主要负责编译 & 处理 IL 指令,执行流程如下
main_thread_handler()
=> mono_jit_exec()
=> mono_assembly_get_image() 得倒 image 信息
=> mono_runtime_run_main()
=> mono_thread_set_main()
=> mono_assembly_set_main()
=> mono_runtime_exec_main()
....

mono_runtime_invoke 处理将要调用的方法,例如 ClassName::Main()。default_mono_runtime_invoke 函数实际调用 mono_jit_runtime_invoke 函数。mono_jit_runtime_invoke 函数调用来 mono_jit_compile_method_with_opt 实现编译目标函数的代码,调用mono_jit_compile_method 编译目标函数的 runtime wrapper (运行时的上层封装调用)。 runtime_invoke 函数调用编译之后的目标函数,其中 info->compiled_method 参数为编译之后目标函数代码在内存中的地址信息。
通过以上分析,mono_jit_compile_method_with_opt 函数为C#函数代码编译为目标机器指令的关键函数,我们来分析以下这部分的执行流程
mono_jit_compile_method_with_opt()
mono_jit_compile_method_inner()
mini_method_compile()
....

其中 mini_method_compile 函数在内部通过 Mono的 JIT 机制实现动态编译过程。
C#函数的执行过程
mono_runtime_invoke 函数实现与 mono \ object.c中,而实际调用 mono_jit_runtime_invoke 函数代码则在 mini.c 文件中。mono_runtime_invoke 函数负责实现 C#函数的代码编译和执行。

/**
 * mono_jit_runtime_invoke:
 * \param method: the method to invoke
 * \param obj: this pointer
 * \param params: array of parameter values.
 * \param exc: Set to the exception raised in the managed method.
 * \param error: error or caught exception object
 * If \p exc is NULL, \p error is thrown instead.
 * If coop is enabled, \p exc argument is ignored -
 * all exceptions are caught and propagated through \p error
 */
static MonoObject*
mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc, MonoError *error)
{
    MonoMethod *invoke, *callee;
    MonoObject *(*runtime_invoke) (MonoObject *this_obj, void **params, MonoObject **exc, void* compiled_method);
    MonoDomain *domain = mono_domain_get ();
    MonoJitDomainInfo *domain_info;
    RuntimeInvokeInfo *info, *info2;
    MonoJitInfo *ji = NULL;
    gboolean callee_gsharedvt = FALSE;

    if (mono_use_interpreter)
        return mini_get_interp_callbacks ()->runtime_invoke (method, obj, params, exc, error);

    error_init (error);
    if (exc)
        *exc = NULL;

    if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
        g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
        return NULL;
    }

    domain_info = domain_jit_info (domain);

    info = (RuntimeInvokeInfo *)mono_conc_hashtable_lookup (domain_info->runtime_invoke_hash, method);

//mono_jit_runtime_invoke 函数会先通过查找列表,判断是否已创建对应的 info 信息,若不存在,则先进行编译并得倒 info信息

    if (!info) {
        if (mono_security_core_clr_enabled ()) {
            /*
             * This might be redundant since mono_class_vtable () already does this,
             * but keep it just in case for moonlight.
             */
            mono_class_setup_vtable (method->klass);
            if (mono_class_has_failure (method->klass)) {
                mono_error_set_for_class_failure (error, method->klass);
                if (exc)
                    *exc = (MonoObject*)mono_class_get_exception_for_failure (method->klass);
                return NULL;
            }
        }

        gpointer compiled_method;

        callee = method;
        if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
            (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
            /*
             * Array Get/Set/Address methods. The JIT implements them using inline code
             * inside the runtime invoke wrappers, so no need to compile them.
             */
            if (mono_aot_only) {
                /*
                 * Call a wrapper, since the runtime invoke wrapper was not generated.
                 */
                MonoMethod *wrapper;

                wrapper = mono_marshal_get_array_accessor_wrapper (method);
                invoke = mono_marshal_get_runtime_invoke (wrapper, FALSE);
                callee = wrapper;
            } else {
                callee = NULL;
            }
        }

        if (callee) {
            compiled_method = mono_jit_compile_method (callee, error);
            if (!compiled_method) {
                g_assert (!mono_error_ok (error));
                return NULL;
            }

            if (mono_llvm_only) {
                ji = mini_jit_info_table_find (mono_domain_get (), (char *)mono_get_addr_from_ftnptr (compiled_method), NULL);
                callee_gsharedvt = mini_jit_info_is_gsharedvt (ji);
                if (callee_gsharedvt)
                    callee_gsharedvt = mini_is_gsharedvt_variable_signature (mono_method_signature (jinfo_get_method (ji)));
            }

            if (!callee_gsharedvt)
                compiled_method = mini_add_method_trampoline (callee, compiled_method, mono_method_needs_static_rgctx_invoke (callee, TRUE), FALSE);
        } else {
            compiled_method = NULL;
        }

        info = create_runtime_invoke_info (domain, method, compiled_method, callee_gsharedvt, error);
        if (!mono_error_ok (error))
            return NULL;

        mono_domain_lock (domain);
        info2 = (RuntimeInvokeInfo *)mono_conc_hashtable_insert (domain_info->runtime_invoke_hash, method, info);
        mono_domain_unlock (domain);
        if (info2) {
            g_free (info);
            info = info2;
        }
    }

    /*
     * We need this here because mono_marshal_get_runtime_invoke can place
     * the helper method in System.Object and not the target class.
     */
    if (!mono_runtime_class_init_full (info->vtable, error)) {
        if (exc)
            *exc = (MonoObject*) mono_error_convert_to_exception (error);
        return NULL;
    }

    /* If coop is enabled, and the caller didn't ask for the exception to be caught separately,
       we always catch the exception and propagate it through the MonoError */
    gboolean catchExcInMonoError =
        (exc == NULL) && mono_threads_is_coop_enabled ();
    MonoObject *invoke_exc = NULL;
    if (catchExcInMonoError)
        exc = &invoke_exc;

    /* The wrappers expect this to be initialized to NULL */
    if (exc)
        *exc = NULL;

#ifdef MONO_ARCH_DYN_CALL_SUPPORTED
    if (info->dyn_call_info) {
        MonoMethodSignature *sig = mono_method_signature (method);
        gpointer *args;
        static RuntimeInvokeDynamicFunction dyn_runtime_invoke;
        int i, pindex, buf_size;
        guint8 *buf;
        guint8 retval [256];

        if (!dyn_runtime_invoke) {
            invoke = mono_marshal_get_runtime_invoke_dynamic ();
            dyn_runtime_invoke = (RuntimeInvokeDynamicFunction)mono_jit_compile_method (invoke, error);
            if (!mono_error_ok (error))
                return NULL;
        }

        /* Convert the arguments to the format expected by start_dyn_call () */
        args = (void **)g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
        pindex = 0;
        if (sig->hasthis)
            args [pindex ++] = &obj;
        for (i = 0; i < sig->param_count; ++i) {
            MonoType *t = sig->params [i];

            if (t->byref) {
                args [pindex ++] = &params [i];
            } else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
                args [pindex ++] = &params [i];
            } else {
                args [pindex ++] = params [i];
            }
        }

        //printf ("M: %s\n", mono_method_full_name (method, TRUE));

        buf_size = mono_arch_dyn_call_get_buf_size (info->dyn_call_info);
        buf = g_alloca (buf_size);
        g_assert (buf);

        mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf);

        dyn_runtime_invoke (buf, exc, info->compiled_method);
        mono_arch_finish_dyn_call (info->dyn_call_info, buf);

        if (catchExcInMonoError && *exc != NULL) {
            mono_error_set_exception_instance (error, (MonoException*) *exc);
            return NULL;
        }

        if (info->ret_box_class)
            return mono_value_box_checked (domain, info->ret_box_class, retval, error);
        else
            return *(MonoObject**)retval;
    }
#endif

    MonoObject *result;

    if (mono_llvm_only) {
        result = mono_llvmonly_runtime_invoke (method, info, obj, params, exc, error);
        if (!is_ok (error))
            return NULL;
    } else {
        runtime_invoke = (MonoObject *(*)(MonoObject *, void **, MonoObject **, void *))info->runtime_invoke;

        result = runtime_invoke ((MonoObject *)obj, params, exc, info->compiled_method);
    }
    if (catchExcInMonoError && *exc != NULL)
        mono_error_set_exception_instance (error, (MonoException*) *exc);
    return result;
}

编译完成(或之前已经编译相同的 info 信息)后,则调用 info 自身的 runtime_invoke 函数实现对真正函数的调用。其中 runtime_invoke 函数的指针赋值。
compiled_method 变量存储目标函数编译之后所生成代码的内存地址。在之前的代码中,mono_jit_runtime_invoke 函数的第一个参数为 MonoMethod *method,在 MonoMethod 结构体中存储来需要编译和执行的 C# 函数的详细信息,包括:方法名、方法所属类的信息等。即根据 mono_jit_runtime_invoke 入口参数 method 可获取 compiled_method 变量存储的函数名,通过结构分析可以看到,在整个编译和调用过程中, MonoMethod 函数都是相关关键的结构,其结构在 class_internal.h 文件中定义。
。。。
1)name 存储 C# 函数名信息
2)klass 为 C# 函数所属类的相关信息。
通过 mono_jit_runtime_invoke 函数可知道 C# 函数的调用过程,以及函数地址、函数名、函数所属类等。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,615评论 0 3
  • 转自长亭知乎专栏,实习时小姐姐的约稿,已经不在那边了所以版权不归我哈 笔者一直自认玩过不少游戏,无奈水平太菜,日常...
    hyrathon阅读 1,511评论 0 0
  • 一、背景和意义 Unity3D是手游领域的主要游戏引擎,熟练掌握对其的逆向方法,对我们而言十分重要。目前主流的方法...
    oraclex阅读 6,682评论 0 7
  • 一:java概述:1,JDK:Java Development Kit,java的开发和运行环境,java的开发工...
    ZaneInTheSun阅读 2,582评论 0 11
  • 继上Runtime梳理(四) 通过前面的学习,我们了解到Objective-C的动态特性:Objective-C不...
    小名一峰阅读 718评论 0 3