aboutsummaryrefslogtreecommitdiffstats
path: root/include/qdotnethost.h
blob: c2fe298b99ee278362d721b922a6e0a043b488f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/***************************************************************************************************
 Copyright (C) 2023 The Qt Company Ltd.
 SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
***************************************************************************************************/

#pragma once

#include "qdotnetfunction.h"

#ifdef __GNUC__
#   pragma GCC diagnostic push
#   pragma GCC diagnostic ignored "-Wconversion"
#endif
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QLibrary>
#include <QFile>
#include <QProcess>
#include <QRegularExpression>
#include <QString>
#include <QTemporaryFile>
#include <QVersionNumber>
#ifdef __GNUC__
#   pragma GCC diagnostic pop
#endif

class QDotNetHost
{
public:
    QDotNetHost() = default;

    ~QDotNetHost()
    {
        unload();
    }

    bool load(const QString& runtimeConfig = defaultRuntimeConfig, const QString &runtimePath = {})
    {
        if (isLoaded())
            return true;
        if (!loadRuntime(runtimePath))
            return false;
        if (!init(runtimeConfig)) {
            unloadRuntime();
            return false;
        }
        return true;
    }

    void unload()
    {
        if (!isLoaded())
            return;
        close();
        unloadRuntime();
    }

    bool isLoaded() const
    {
        return (hostContext != nullptr);
    }

    bool resolveFunction(QDotNetFunction<quint32, void *, qint32> &outFunc,
        const QString &assemblyPath, const QString &typeName, const QString &methodName)
    {
        return resolveFunction(outFunc, assemblyPath, typeName, methodName, {});
    }

    template<typename TResult, typename... TArgs>
    bool resolveFunction(QDotNetFunction<TResult, TArgs...> &outFunc, const QString &assemblyPath,
        const QString &typeName, const QString &methodName, const QString &delegateType)
    {
        if (!isLoaded() && !load())
            return false;
        outFunc = resolveFunction(assemblyPath, typeName, methodName, delegateType);
        return outFunc.isValid();
    }

    QMap<QString, QString> runtimeProperties() const
    {
        if (!isLoaded())
            return {};
        size_t queryCount = 0;
        const auto result = fnAllRuntimeProperties(hostContext, &queryCount, nullptr, nullptr);
        if (result != Success && result != HostApiBufferTooSmall) {
            qCritical() << "Error calling function: hostfxr_get_runtime_properties";
            return {};
        }
        const size_t count = queryCount;
        const char_t **keys = new const char_t * [count] { nullptr };
        const char_t **values = new const char_t * [count] { nullptr };
        if (HOSTFN_FAILED(fnAllRuntimeProperties(hostContext, &queryCount, keys, values))) {
            qCritical() << "Error calling function: hostfxr_get_runtime_properties";
            delete[] keys;
            delete[] values;
            return {};
        }
        QMap<QString, QString> properties;
        for (size_t i = 0; i < count; ++i) {
            const char_t *key = keys[i];
            const char_t *value = values[i];
            if (key && value)
                properties.insert(QSTR(key), QSTR(value));
        }
        delete[] keys;
        delete[] values;
        return properties;
    }

    QString runtimeProperty(const QString &name) const
    {
        if (!isLoaded())
            return {};
        const char_t *value = nullptr;
        if (HOSTFN_FAILED(fnRuntimeProperty(hostContext, STR(name), &value))) {
            qCritical() << "Error calling function: hostfxr_get_runtime_property_value";
            return {};
        }
        if (!value)
            return {};
        return QSTR(value);
    }

    bool setRuntimeProperty(const QString &name, const QString &value) const
    {
        if (!isLoaded())
            return false;
        if (HOSTFN_FAILED(fnSetRuntimeProperty(hostContext, STR(name), STR(value)))) {
            qCritical() << "Error calling function: hostfxr_set_runtime_property_value";
            return false;
        }
        return true;
    }

    void setErrorWriter(hostfxr_error_writer_fn errorWriter)
    {
        if (fnSetErrorWriter == nullptr || hostContext == nullptr)
            return;
        fnSetErrorWriter(errorWriter);
    }

private:
    void *resolveFunction(const QString &assemblyPath, const QString &typeName,
        const QString &methodName, const QString &delegateType) const
    {
        if (hostContext == nullptr)
            return nullptr;
        void *funcPtr = nullptr;
        auto result = fnLoadAssemblyAndGetFunctionPointer(
            STR(assemblyPath),
            STR(typeName),
            STR(methodName),
            delegateType.isEmpty() ? nullptr : STR(delegateType),
            nullptr,
            &funcPtr);
        if (HOSTFN_FAILED(result)) {
            qCritical() << "Error getting function pointer:"
                << methodName << QString::number(static_cast<unsigned>(result), 16);
            return nullptr;
        }
        return funcPtr;
    }

    QString findRuntimePath() const
    {
        QProcess procDotNetInfo;
        procDotNetInfo.start("dotnet", { "--list-runtimes" });
        if (!procDotNetInfo.waitForFinished() || procDotNetInfo.exitCode() != 0) {
            qCritical() << "Error calling dotnet";
            return {};
        }
        const QString dotNetInfo(procDotNetInfo.readAllStandardOutput());

        QString runtimeDirPath = {};
        QString hostVersion = {};
        QVersionNumber maxVersion;
        const QRegularExpression dotNetInfoParser(regexParseDotNetInfo,
            QRegularExpression::MultilineOption | QRegularExpression::DotMatchesEverythingOption);
        for (const auto &match : dotNetInfoParser.globalMatch(dotNetInfo)) {
            const auto version = QVersionNumber::fromString(match.captured("version"));
            if (version > maxVersion) {
                maxVersion = version;
                hostVersion = match.captured("version");
                runtimeDirPath = match.captured("path");
            }
        }

        if (runtimeDirPath.isEmpty()) {
            qCritical() << "Error parsing dotnet info";
            return {};
        }

        QDir runtimeDir(runtimeDirPath);
        if (!runtimeDir.exists()) {
            qCritical() << "Error dotnet runtime directory not found";
            return {};
        }

        runtimeDir.cd(QString("../../host/fxr/%1").arg(hostVersion));
        if (!runtimeDir.exists()) {
            qCritical() << "Error dotnet host fxr directory not found";
            return {};
        }
#ifdef Q_OS_WINDOWS
        QString runtimePath = runtimeDir.absoluteFilePath("hostfxr.dll");
#else
        QString runtimePath = runtimeDir.absoluteFilePath("libhostfxr.so");
#endif
        if (!QFile::exists(runtimePath)) {
            qCritical() << "Error dotnet host fxr dll not found";
            return {};
        }
        return runtimePath;
    }

    bool loadRuntime(const QString & runtimePath)
    {
        if (fnInitHost != nullptr)
            return true;

        if (!runtimePath.isEmpty()) {
            if (!QFile::exists(runtimePath))
                return false;
            runtime.setFileName(runtimePath);
        } else {
            const QString defaultRuntimePath = findRuntimePath();
            if (defaultRuntimePath.isEmpty())
                return false;
            runtime.setFileName(defaultRuntimePath);
        }

        if (!runtime.load()) {
            qCritical() << "Error loading library: hostfxr";
            return false;
        }

        fnInitHost = GET_FN(runtime, hostfxr_initialize_for_runtime_config_fn);
        if (!fnInitHost) {
            qCritical() << "Error loading function: hostfxr_initialize_for_runtime_config";
            return false;
        }

        fnGetRuntimeDelegate = GET_FN(runtime, hostfxr_get_runtime_delegate_fn);
        if (!fnGetRuntimeDelegate) {
            qCritical() << "Error loading function: hostfxr_get_runtime_delegate";
            return false;
        }

        fnCloseHost = GET_FN(runtime, hostfxr_close_fn);
        if (!fnCloseHost) {
            qCritical() << "Error loading function: hostfxr_close";
            return false;
        }

        fnSetErrorWriter = GET_FN(runtime, hostfxr_set_error_writer_fn);
        if (!fnSetErrorWriter) {
            qCritical() << "Error loading function: hostfxr_set_error_writer";
            return false;
        }

        fnAllRuntimeProperties = GET_FN(runtime, hostfxr_get_runtime_properties_fn);
        if (!fnAllRuntimeProperties) {
            qCritical() << "Error loading function: hostfxr_get_runtime_properties_fn";
            return false;
        }

        fnRuntimeProperty = GET_FN(runtime, hostfxr_get_runtime_property_value_fn);
        if (!fnRuntimeProperty) {
            qCritical() << "Error loading function: hostfxr_get_runtime_property_value_fn";
            return false;
        }

        fnSetRuntimeProperty = GET_FN(runtime, hostfxr_set_runtime_property_value_fn);
        if (!fnSetRuntimeProperty) {
            qCritical() << "Error loading function: hostfxr_set_runtime_property_value_fn";
            return false;
        }

        fnSetErrorWriter(defaultErrorWriter);
        return true;
    }

    void unloadRuntime()
    {
        runtime.unload();
        fnInitHost = nullptr;
        fnGetRuntimeDelegate = nullptr;
        fnCloseHost = nullptr;
        fnAllRuntimeProperties = nullptr;
        fnRuntimeProperty = nullptr;
        fnSetRuntimeProperty = nullptr;
    }

    bool init(const QString &runtimeConfig)
    {
        if (fnInitHost == nullptr)
            return false;

        const QString tempFileName = writeTempFile(runtimeConfig, runtimeConfigFileName);
        if (tempFileName.isEmpty()) {
            qCritical() << "Error writing runtime configuration file.";
            return false;
        }

        auto result = fnInitHost(STR(tempFileName), nullptr, &hostContext);
        if (HOSTFN_FAILED(result) || hostContext == nullptr) {
            qCritical() << "Error calling function: hostfxr_initialize_for_runtime_config";
            QFile::remove(tempFileName);
            return false;
        }

        if (!QFile::remove(tempFileName))
            qWarning() << "Error removing file:" << tempFileName;

        result = fnGetRuntimeDelegate(hostContext,
            hdt_load_assembly_and_get_function_pointer,
            reinterpret_cast<void **>(&fnLoadAssemblyAndGetFunctionPointer));
        if (HOSTFN_FAILED(result)) {
            qCritical() << "Error calling function:"
                << "hostfxr_get_runtime_delegate(hdt_load_assembly_and_get_function_pointer)";
            return false;
        }

        return true;
    }

    bool close()
    {
        if (fnCloseHost == nullptr || hostContext == nullptr)
            return false;
        if (HOSTFN_FAILED(fnCloseHost(hostContext)))
            qWarning() << "Error calling function: hostfxr_close";
        hostContext = nullptr;
        fnLoadAssemblyAndGetFunctionPointer = nullptr;
        return true;
    }

    static void defaultErrorWriter(const char_t *message)
    {
        qWarning() << "Qt/.NET: HostError:" << QSTR(message);
    }

    static QString writeTempFile(const QString &text, const QString &fileNameTemplate)
    {
        QTemporaryFile tempFile(fileNameTemplate);
        tempFile.setAutoRemove(false);
        if (!tempFile.open()) {
            qCritical() << "Error creating temp file:" << tempFile.errorString();
            return {};
        }

        QString tempFileName = tempFile.fileName();
        const QByteArray fileData = text.toUtf8();
        if (!tempFile.write(fileData)) {
            qCritical() << "Error writing file:" << tempFileName;
            return {};
        }
        tempFile.close();

        return tempFileName;
    }

    static inline const QString runtimeConfigFileName = QStringLiteral("runtimeconfig.XXXXXX.json");
    static inline const QString defaultRuntimeConfig = QStringLiteral(R"[json](
{
  "runtimeOptions": {
    "tfm": "net6.0",
    "rollForward": "LatestMinor",
    "framework": {
      "name": "Microsoft.NETCore.App",
      "version": "6.0.0"
    }
  }
}
)[json]");

    static inline const QString regexParseDotNetInfo = QStringLiteral(R"[regex](
\bMicrosoft\.NETCore\.App[^0-9]*(?<version>[0-9\.]+)[^\[]*\[(?<path>[^\]]+)\]
)[regex]").remove('\r').remove('\n');


    QLibrary runtime;
    hostfxr_initialize_for_runtime_config_fn fnInitHost = nullptr;
    hostfxr_get_runtime_delegate_fn fnGetRuntimeDelegate = nullptr;
    hostfxr_close_fn fnCloseHost = nullptr;
    hostfxr_set_error_writer_fn fnSetErrorWriter = nullptr;
    hostfxr_get_runtime_properties_fn fnAllRuntimeProperties = nullptr;
    hostfxr_get_runtime_property_value_fn fnRuntimeProperty = nullptr;
    hostfxr_set_runtime_property_value_fn fnSetRuntimeProperty = nullptr;
    hostfxr_handle hostContext = nullptr;

    load_assembly_and_get_function_pointer_fn fnLoadAssemblyAndGetFunctionPointer = nullptr;
};