1// Licensed to the .NET Foundation under one or more agreements.
2// The .NET Foundation licenses this file to you under the MIT license.
3// See the LICENSE file in the project root for more information.
4
5#include <stdio.h>
6#include <assert.h>
7#include "dlfcn.h"
8#include "coreclrloader.h"
9#include "coreruncommon.h"
10
11using namespace std;
12void *CoreCLRLoader::LoadFunction(const char *funcName)
13{
14 void *func = nullptr;
15 if (coreclrLib == nullptr)
16 {
17 fprintf(stderr, "Error: coreclr should be loaded before loading a function: %s\n", funcName);
18 }
19 else
20 {
21 func = dlsym(coreclrLib, funcName);
22 if (func == nullptr)
23 {
24 fprintf(stderr, "Error: cannot find %s in coreclr\n", funcName);
25 }
26 }
27 return func;
28}
29
30CoreCLRLoader* CoreCLRLoader::Create(const char *exePath)
31{
32 string absolutePath, coreClrPath;
33 bool success = GetAbsolutePath(exePath, absolutePath);
34 if (!success)
35 {
36 success = GetEntrypointExecutableAbsolutePath(absolutePath);
37 assert(success);
38 }
39 GetDirectory(absolutePath.c_str(), coreClrPath);
40 coreClrPath.append("/");
41 coreClrPath.append(coreClrDll);
42
43 CoreCLRLoader *loader = new CoreCLRLoader();
44 loader->coreclrLib = dlopen(coreClrPath.c_str(), RTLD_NOW | RTLD_LOCAL);
45 if (loader->coreclrLib == nullptr)
46 {
47 fprintf(stderr, "Error: Fail to load %s\n", coreClrPath.c_str());
48 delete loader;
49 return nullptr;
50 }
51 else
52 {
53 loader->initializeCoreCLR = (InitializeCoreCLRFunction)loader->LoadFunction("coreclr_initialize");
54 loader->shutdownCoreCLR = (ShutdownCoreCLRFunction)loader->LoadFunction("coreclr_shutdown");
55 int ret = loader->initializeCoreCLR(
56 exePath,
57 "coreclrloader",
58 0,
59 0,
60 0,
61 &loader->hostHandle,
62 &loader->domainId);
63 if (ret != 0)
64 {
65 fprintf(stderr, "Error: Fail to initialize CoreCLR\n");
66 delete loader;
67 return nullptr;
68 }
69 }
70 return loader;
71}
72
73int CoreCLRLoader::Finish()
74{
75 if (hostHandle != 0)
76 {
77 shutdownCoreCLR(hostHandle, domainId);
78 delete this;
79 }
80 return 0;
81}
82