是否可以在 Windows 上加载 c-dll 中的 go-dll?
Is it possible to load a go-dll in c-dll on Windows?
我想将 c-dll 注入进程。在c-dll中,它会加载另一个由golang编写的dll。这是我的 C 代码:
加载loader.dll时,会自动加载golang写的worker.dll
// loader.c
#include <windows.h>
#include <stdio.h>
#include <memory.h>
typedef void (*StartWorker)();
HMODULE hWorker = NULL;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
hWorker = LoadLibrary("D:\code\toys\worker.dll");
if (hWorker == NULL)
{
exit(1);
}
StartWorker startWorker = (StartWorker)GetProcAddress(hWorker, "StartWorker");
MessageBox(NULL, "worker starting", TEXT("Warning:"), MB_OK);
if (startWorker == NULL)
{
MessageBox(NULL, "error", TEXT("Warning:"), MB_OK);
exit(1);
}
startWorker();
MessageBox(NULL, "worker started", TEXT("Warning:"), MB_OK);
FreeLibrary(hWorker);
break;
}
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
default:
break;
}
return TRUE;
}
go 代码是:
// worker.go
package main
/*
#include <stdlib.h>
#include <windows.h>
*/
import "C"
//export StartWorker
func StartWorker {
C.MessageBox(nil, C.CString("Hello Worker"), C.CString("Warning:"), 0)
}
func main() {
}
我在MinGW-w64
中编译了它们。当 loader.dll 试图调用 worker.dll 中的 StartWorker()
时,进程没有显示 MessageBox。在我用 c 重写 worker.dll 之后,一切正常。当我通过以下代码调用 StartWorker()
时也可以:
#include <windows.h>
#include <stdio.h>
#include <memory.h>
typedef void (*StartWorker)();
int main()
{
char *dllPath = "D:\code\toys\loader.dll";
HMODULE hWorker = NULL;
hWorker = LoadLibrary(dllPath);
StartWorker startWorker = (StartWorker)GetProcAddress(hWorker, "StartWorker");
if (startWorker == NULL)
{
MessageBox(NULL, "dllPath", TEXT("Warning:"), MB_OK);
exit(1);
}
startWorker();
MessageBox(NULL, "target", TEXT("Warning:"), MB_OK);
FreeLibrary(hWorker);
return 0;
}
不知道是不是跟go-runtime有什么冲突?
测试正常,也许你调用了 Microsoft-Windows-Only
api。尝试将 MessageBox()
(它使用 win32 user32.dll
)更改为 Sum()
以测试调用 go-dll
.
的 c-dll
这是要生成的文件 go-dll
// gosum.go
package main
/*
#include <stdlib.h>
*/
import "C"
//export Sum
func Sum(a int32, b int32) int32 {
return a + b
}
func main() {
}
去构建 c-shared Windows
dll:
go build -ldflags "-s -w" -buildmode=c-shared -o gosum.dll
你可以在c/cpp中编写测试文件:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "gosum.h"
int main() {
printf("Sum(1,2)=%d\n", Sum(1,2));
return 1;
}
在 MinGW-w64 中编译
g++ -c test_gosum.cpp -o test_gosum.o -g -std=c++11
g++ test_gosum.o gosum.dll -o test_gosum.exe -g -std=c++11
.\test_gosum.exe
然后在调用 gosum.dll
的 Visual Studio
中构建 loader.dll
// 复制 go-dll
CGO gen gosum.h
文件到项目,可能你需要删除一些错误代码
// gosum.h 文件:
/* Code generated by cmd/cgo; DO NOT EDIT. */
/* package gosum */
#line 1 "cgo-builtin-export-prolog"
#include <stddef.h> /* for ptrdiff_t below */
#ifndef GO_CGO_EXPORT_PROLOGUE_H
#define GO_CGO_EXPORT_PROLOGUE_H
#ifndef GO_CGO_GOSTRING_TYPEDEF
typedef struct { const char* p; ptrdiff_t n; } _GoString_;
#endif
#endif
/* Start of preamble from import "C" comments. */
#line 3 "gosum.go"
#include <stdlib.h>
#line 1 "cgo-generated-wrapper"
/* End of preamble from import "C" comments. */
/* Start of boilerplate cgo prologue. */
#line 1 "cgo-gcc-export-header-prolog"
#ifndef GO_CGO_PROLOGUE_H
#define GO_CGO_PROLOGUE_H
typedef signed char GoInt8;
typedef unsigned char GoUint8;
typedef short GoInt16;
typedef unsigned short GoUint16;
typedef int GoInt32;
typedef unsigned int GoUint32;
typedef long long GoInt64;
typedef unsigned long long GoUint64;
typedef GoInt64 GoInt;
typedef GoUint64 GoUint;
typedef float GoFloat32;
typedef double GoFloat64;
/*
static assertion to make sure the file is being used on architecture
at least with matching size of GoInt.
*/
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*) == 64 / 8 ? 1 : -1];
#ifndef GO_CGO_GOSTRING_TYPEDEF
typedef _GoString_ GoString;
#endif
typedef void* GoMap;
typedef void* GoChan;
typedef struct { void* t; void* v; } GoInterface;
typedef struct { void* data; GoInt len; GoInt cap; } GoSlice;
#endif
/* End of boilerplate cgo prologue. */
#ifdef __cplusplus
extern "C" {
#endif
extern GoInt32 Sum(GoInt32 a, GoInt32 b);
#ifdef __cplusplus
}
#endif
// pch.h 文件(由 vs 生成,需要添加一些东西):
#define PCH_H
#include "framework.h"
#endif
// ----- added
#ifdef IMPORT_DLL
#else
#define IMPORT_DLL extern "C" _declspec(dllimport)
#endif
IMPORT_DLL int get_sum_by_another_dll(int a, int b);
// ----- added
// dllmain.cpp 文件(由 vs 生成):
#include "pch.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// loader.cpp 文件:
#include "pch.h"
#include <stdlib.h>
#include <windows.h>
#include "gosum.h" // also need add `gosum.dll` to VS project file
using namespace std;
typedef int (CALLBACK* GOSUMFUNC)(GoInt32 a, GoInt32 b);
int __stdcall get_sum_by_another_dll(int a, int b)
{
HMODULE h = LoadLibrary(TEXT("gosum.dll"));
if (NULL == h || INVALID_HANDLE_VALUE == h) {
return 0;
}
GOSUMFUNC go_dll_sum = (GOSUMFUNC)GetProcAddress(h, "Sum");
if (go_dll_sum) {
return go_dll_sum(a, b);
}
return 1;
}
然后在VS中编译,得到loader.dll
.
其中gosum.dll
是go-dll
,loader.dll
是VisualStudio编译的c-dll
,调用了gosum.dll
.
你可以尝试在 golang 或 clang 中调用它们。
// demo.go 用 golang 测试 loader.dll 和 gosum.dll,还需要在同一个目录中复制 gosum.dll
和 loader.dll
。
package main
import (
"fmt"
"log"
"syscall"
)
func main() {
h, e := syscall.LoadLibrary("loader.dll") //Make sure this DLL follows Golang machine bit architecture (64-bit in my case)
if e != nil {
log.Fatal(e)
}
defer syscall.FreeLibrary(h)
proc, e := syscall.GetProcAddress(h, "get_sum_by_another_dll") //One of the functions in the DLL
if e != nil {
log.Fatal(e)
}
var a int32 = 2
var b int32 = 5
ret, _, err := syscall.Syscall(proc, 2, uintptr(a), uintptr(b), 0) //Pay attention to the positioning of the parameter
fmt.Println(ret)
fmt.Println(err)
}
去运行它你会得到结果:get_sum_by_another_dll(2,5) = 7
// callloader.cpp test loader.dll and gosum.dll with c/cpp, also need to copy gosum.dll
and loader.dll
in same dir .
#include <iostream>
#include <Windows.h>
int main()
{
HINSTANCE hDllInst;
hDllInst = LoadLibrary(L"loader.dll");
typedef int(*SUMFUNC)(int a, int b);
SUMFUNC dll_sum_fun = (SUMFUNC)GetProcAddress(hDllInst, "get_sum_by_another_dll");
std::cout << dll_sum_fun(1, 2);
}
然后在VS中编译,运行 ./callloader.exe,你会得到结果:get_sum_by_another_dll(1,2) = 3
我找到了实现该功能的方法。我刚刚写了一些新代码如下。他们现在工作正常。
http.go
package main
import "C"
import (
"fmt"
"net/http"
)
func sayHello(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("Hello World!"))
}
//export StartHttp
func StartHttp() {
http.HandleFunc("/", sayHello)
err := http.ListenAndServe("127.0.0.1:9999", nil)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Listening: http://127.0.0.1:9000")
}
func main() {
// StartHttp();
}
loader.c
#include <windows.h>
#include <stdio.h>
// https://forum.pellesc.de/index.php?topic=4725.0
#ifdef __GNUC__
HANDLE k __attribute__((section(".shared"), shared)) = NULL;
#endif
#ifdef _MSC_VER
#pragma data_seg(".shared")
HANDLE k = NULL;
#pragma data_seg()
#pragma comment(linker, "/section:.shared,RWS")
#endif
typedef void (*StartHttp)();
HMODULE hHttp = NULL;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
hHttp = LoadLibrary("http.dll");
StartHttp startWorker = (StartHttp)GetProcAddress(hHttp, "StartHttp");
k = startWorker;
// do not execute the function here!
break;
}
case DLL_PROCESS_DETACH:
{
FreeLibrary(hHttp);
break;
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
default:
break;
}
return TRUE;
}
HANDLE GetHttpStarter()
{
return k;
}
client.c
#include <windows.h>
#include <stdio.h>
#include <memory.h>
typedef void (*StartHttp)();
typedef HMODULE (*GetHttpStarter)();
int main()
{
HMODULE hLoader = NULL;
hLoader = LoadLibrary("loader.dll");
GetHttpStarter getHttpStarter = (GetHttpStarter)GetProcAddress(hLoader, "GetHttpStarter");
StartHttp startHttp = (StartHttp)getHttpStarter();
startHttp();
printf("^^\n");
FreeLibrary(hLoader);
return 0;
}
> go build -buildmode=c-shared -o http.dll .\http.go
> gcc .\loader.c -shared -o loader.dll
> gcc .\client.c -o client.exe
> .\client.exe
我修改的最重要的是只加载loader.dll(c)
的DllMain()
中的http.dll(go)
而不执行http.dll(go)
的函数,并存储那些共享内存中的函数地址。所以我可以通过调用 loader.dll(c)
的导出函数 GetHttpStarter()
来获取 http.dll(go)
的函数地址。看起来很复杂,但确实有效:)
我也测试了 dll 注入,结果,我现在可以在 notepad.exe
上托管 http 服务了:D
我想将 c-dll 注入进程。在c-dll中,它会加载另一个由golang编写的dll。这是我的 C 代码:
加载loader.dll时,会自动加载golang写的worker.dll
// loader.c
#include <windows.h>
#include <stdio.h>
#include <memory.h>
typedef void (*StartWorker)();
HMODULE hWorker = NULL;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
hWorker = LoadLibrary("D:\code\toys\worker.dll");
if (hWorker == NULL)
{
exit(1);
}
StartWorker startWorker = (StartWorker)GetProcAddress(hWorker, "StartWorker");
MessageBox(NULL, "worker starting", TEXT("Warning:"), MB_OK);
if (startWorker == NULL)
{
MessageBox(NULL, "error", TEXT("Warning:"), MB_OK);
exit(1);
}
startWorker();
MessageBox(NULL, "worker started", TEXT("Warning:"), MB_OK);
FreeLibrary(hWorker);
break;
}
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
default:
break;
}
return TRUE;
}
go 代码是:
// worker.go
package main
/*
#include <stdlib.h>
#include <windows.h>
*/
import "C"
//export StartWorker
func StartWorker {
C.MessageBox(nil, C.CString("Hello Worker"), C.CString("Warning:"), 0)
}
func main() {
}
我在MinGW-w64
中编译了它们。当 loader.dll 试图调用 worker.dll 中的 StartWorker()
时,进程没有显示 MessageBox。在我用 c 重写 worker.dll 之后,一切正常。当我通过以下代码调用 StartWorker()
时也可以:
#include <windows.h>
#include <stdio.h>
#include <memory.h>
typedef void (*StartWorker)();
int main()
{
char *dllPath = "D:\code\toys\loader.dll";
HMODULE hWorker = NULL;
hWorker = LoadLibrary(dllPath);
StartWorker startWorker = (StartWorker)GetProcAddress(hWorker, "StartWorker");
if (startWorker == NULL)
{
MessageBox(NULL, "dllPath", TEXT("Warning:"), MB_OK);
exit(1);
}
startWorker();
MessageBox(NULL, "target", TEXT("Warning:"), MB_OK);
FreeLibrary(hWorker);
return 0;
}
不知道是不是跟go-runtime有什么冲突?
测试正常,也许你调用了 Microsoft-Windows-Only
api。尝试将 MessageBox()
(它使用 win32 user32.dll
)更改为 Sum()
以测试调用 go-dll
.
c-dll
这是要生成的文件 go-dll
// gosum.go
package main
/*
#include <stdlib.h>
*/
import "C"
//export Sum
func Sum(a int32, b int32) int32 {
return a + b
}
func main() {
}
去构建 c-shared Windows
dll:
go build -ldflags "-s -w" -buildmode=c-shared -o gosum.dll
你可以在c/cpp中编写测试文件:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "gosum.h"
int main() {
printf("Sum(1,2)=%d\n", Sum(1,2));
return 1;
}
在 MinGW-w64 中编译
g++ -c test_gosum.cpp -o test_gosum.o -g -std=c++11
g++ test_gosum.o gosum.dll -o test_gosum.exe -g -std=c++11
.\test_gosum.exe
然后在调用 gosum.dll
Visual Studio
中构建 loader.dll
// 复制 go-dll
CGO gen gosum.h
文件到项目,可能你需要删除一些错误代码
// gosum.h 文件:
/* Code generated by cmd/cgo; DO NOT EDIT. */
/* package gosum */
#line 1 "cgo-builtin-export-prolog"
#include <stddef.h> /* for ptrdiff_t below */
#ifndef GO_CGO_EXPORT_PROLOGUE_H
#define GO_CGO_EXPORT_PROLOGUE_H
#ifndef GO_CGO_GOSTRING_TYPEDEF
typedef struct { const char* p; ptrdiff_t n; } _GoString_;
#endif
#endif
/* Start of preamble from import "C" comments. */
#line 3 "gosum.go"
#include <stdlib.h>
#line 1 "cgo-generated-wrapper"
/* End of preamble from import "C" comments. */
/* Start of boilerplate cgo prologue. */
#line 1 "cgo-gcc-export-header-prolog"
#ifndef GO_CGO_PROLOGUE_H
#define GO_CGO_PROLOGUE_H
typedef signed char GoInt8;
typedef unsigned char GoUint8;
typedef short GoInt16;
typedef unsigned short GoUint16;
typedef int GoInt32;
typedef unsigned int GoUint32;
typedef long long GoInt64;
typedef unsigned long long GoUint64;
typedef GoInt64 GoInt;
typedef GoUint64 GoUint;
typedef float GoFloat32;
typedef double GoFloat64;
/*
static assertion to make sure the file is being used on architecture
at least with matching size of GoInt.
*/
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*) == 64 / 8 ? 1 : -1];
#ifndef GO_CGO_GOSTRING_TYPEDEF
typedef _GoString_ GoString;
#endif
typedef void* GoMap;
typedef void* GoChan;
typedef struct { void* t; void* v; } GoInterface;
typedef struct { void* data; GoInt len; GoInt cap; } GoSlice;
#endif
/* End of boilerplate cgo prologue. */
#ifdef __cplusplus
extern "C" {
#endif
extern GoInt32 Sum(GoInt32 a, GoInt32 b);
#ifdef __cplusplus
}
#endif
// pch.h 文件(由 vs 生成,需要添加一些东西):
#define PCH_H
#include "framework.h"
#endif
// ----- added
#ifdef IMPORT_DLL
#else
#define IMPORT_DLL extern "C" _declspec(dllimport)
#endif
IMPORT_DLL int get_sum_by_another_dll(int a, int b);
// ----- added
// dllmain.cpp 文件(由 vs 生成):
#include "pch.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// loader.cpp 文件:
#include "pch.h"
#include <stdlib.h>
#include <windows.h>
#include "gosum.h" // also need add `gosum.dll` to VS project file
using namespace std;
typedef int (CALLBACK* GOSUMFUNC)(GoInt32 a, GoInt32 b);
int __stdcall get_sum_by_another_dll(int a, int b)
{
HMODULE h = LoadLibrary(TEXT("gosum.dll"));
if (NULL == h || INVALID_HANDLE_VALUE == h) {
return 0;
}
GOSUMFUNC go_dll_sum = (GOSUMFUNC)GetProcAddress(h, "Sum");
if (go_dll_sum) {
return go_dll_sum(a, b);
}
return 1;
}
然后在VS中编译,得到loader.dll
.
其中gosum.dll
是go-dll
,loader.dll
是VisualStudio编译的c-dll
,调用了gosum.dll
.
你可以尝试在 golang 或 clang 中调用它们。
// demo.go 用 golang 测试 loader.dll 和 gosum.dll,还需要在同一个目录中复制 gosum.dll
和 loader.dll
。
package main
import (
"fmt"
"log"
"syscall"
)
func main() {
h, e := syscall.LoadLibrary("loader.dll") //Make sure this DLL follows Golang machine bit architecture (64-bit in my case)
if e != nil {
log.Fatal(e)
}
defer syscall.FreeLibrary(h)
proc, e := syscall.GetProcAddress(h, "get_sum_by_another_dll") //One of the functions in the DLL
if e != nil {
log.Fatal(e)
}
var a int32 = 2
var b int32 = 5
ret, _, err := syscall.Syscall(proc, 2, uintptr(a), uintptr(b), 0) //Pay attention to the positioning of the parameter
fmt.Println(ret)
fmt.Println(err)
}
去运行它你会得到结果:get_sum_by_another_dll(2,5) = 7
// callloader.cpp test loader.dll and gosum.dll with c/cpp, also need to copy gosum.dll
and loader.dll
in same dir .
#include <iostream>
#include <Windows.h>
int main()
{
HINSTANCE hDllInst;
hDllInst = LoadLibrary(L"loader.dll");
typedef int(*SUMFUNC)(int a, int b);
SUMFUNC dll_sum_fun = (SUMFUNC)GetProcAddress(hDllInst, "get_sum_by_another_dll");
std::cout << dll_sum_fun(1, 2);
}
然后在VS中编译,运行 ./callloader.exe,你会得到结果:get_sum_by_another_dll(1,2) = 3
我找到了实现该功能的方法。我刚刚写了一些新代码如下。他们现在工作正常。
http.go
package main
import "C"
import (
"fmt"
"net/http"
)
func sayHello(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("Hello World!"))
}
//export StartHttp
func StartHttp() {
http.HandleFunc("/", sayHello)
err := http.ListenAndServe("127.0.0.1:9999", nil)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Listening: http://127.0.0.1:9000")
}
func main() {
// StartHttp();
}
loader.c
#include <windows.h>
#include <stdio.h>
// https://forum.pellesc.de/index.php?topic=4725.0
#ifdef __GNUC__
HANDLE k __attribute__((section(".shared"), shared)) = NULL;
#endif
#ifdef _MSC_VER
#pragma data_seg(".shared")
HANDLE k = NULL;
#pragma data_seg()
#pragma comment(linker, "/section:.shared,RWS")
#endif
typedef void (*StartHttp)();
HMODULE hHttp = NULL;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
hHttp = LoadLibrary("http.dll");
StartHttp startWorker = (StartHttp)GetProcAddress(hHttp, "StartHttp");
k = startWorker;
// do not execute the function here!
break;
}
case DLL_PROCESS_DETACH:
{
FreeLibrary(hHttp);
break;
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
default:
break;
}
return TRUE;
}
HANDLE GetHttpStarter()
{
return k;
}
client.c
#include <windows.h>
#include <stdio.h>
#include <memory.h>
typedef void (*StartHttp)();
typedef HMODULE (*GetHttpStarter)();
int main()
{
HMODULE hLoader = NULL;
hLoader = LoadLibrary("loader.dll");
GetHttpStarter getHttpStarter = (GetHttpStarter)GetProcAddress(hLoader, "GetHttpStarter");
StartHttp startHttp = (StartHttp)getHttpStarter();
startHttp();
printf("^^\n");
FreeLibrary(hLoader);
return 0;
}
> go build -buildmode=c-shared -o http.dll .\http.go
> gcc .\loader.c -shared -o loader.dll
> gcc .\client.c -o client.exe
> .\client.exe
我修改的最重要的是只加载loader.dll(c)
的DllMain()
中的http.dll(go)
而不执行http.dll(go)
的函数,并存储那些共享内存中的函数地址。所以我可以通过调用 loader.dll(c)
的导出函数 GetHttpStarter()
来获取 http.dll(go)
的函数地址。看起来很复杂,但确实有效:)
我也测试了 dll 注入,结果,我现在可以在 notepad.exe
上托管 http 服务了:D