File: Driver.cpp

package info (click to toggle)
storm-lang 0.7.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 52,004 kB
  • sloc: ansic: 261,462; cpp: 140,405; sh: 14,891; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (176 lines) | stat: -rw-r--r-- 4,400 bytes parent folder | download | duplicates (2)
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
#include "stdafx.h"
#include "Driver.h"
#include "Exception.h"
#include "Core/Convert.h"

#ifdef POSIX
#include <dlfcn.h>
#endif

namespace sql {

	// Note: These are globals, as loading of dynamic libraries is truly a global concern. It is not
	// tied to different Engines.

	// Lock to protect globals here.
	util::Lock driverLock;

	// Instances that are active.
	size_t instances = 0;

	// Pointer to the "mysql_init" function.
	typedef MYSQL *(STDCALL *InitFn)(MYSQL *);
	InitFn mariadbInitFn = null;

#if defined(WINDOWS)

	// MSVC "hack" to get the address of the module:
	extern "C" IMAGE_DOS_HEADER __ImageBase;

	InitFn findDriverLib(Engine &e) {
#ifdef X64
		const char *fnName = "mysql_init";
#else
		const char *fnName = "_mysql_init@4";
#endif

		const char *names[] = {
			"libmariadb.dll",
#ifdef X64
			"libmariadb_64.dll",
#else
			"libmariadb_32.dll",
#endif
		};

		HMODULE moduleHandle = (HMODULE)&__ImageBase;

#if 0
		// Try to get the current DLL handle. Only needed if we are not compiling on MSVC.
		if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
								| GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
								(LPWSTR)&findDriverLib, // ptr to some function in the modle
								&moduleHandle)) {
			throw new (e) SQLError(new (e) Str(S("Could not find the path to the SQL lib DLL file.")));
		}
#endif

		std::vector<wchar_t> buffer(MAX_PATH + 1, 0);
		do {
			GetModuleFileName(moduleHandle, &buffer[0], DWORD(buffer.size()));
			if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
				buffer.resize(buffer.size() * 2);
				continue;
			}
		} while (false);

		// Find the last backslash:
		size_t pathEnd = buffer.size();
		while (pathEnd > 0) {
			if (buffer[pathEnd - 1] == '\\' || buffer[pathEnd - 1] == '/')
				break;
			pathEnd--;
		}

		// Try all names:
		for (size_t i = 0; i < ARRAY_COUNT(names); i++) {
			buffer.resize(pathEnd + strlen(names[i]) + 1);
			for (size_t j = 0; names[i][j]; j++)
				buffer[pathEnd + j] = names[i][j];
			buffer[buffer.size() - 1] = 0;

			HMODULE lib = LoadLibrary(&buffer[0]);
			if (!lib)
				continue;

			void *fn = GetProcAddress(lib, fnName);
			if (!fn) {
				FreeLibrary(lib);
				continue;
			}

			return reinterpret_cast<InitFn>(fn);
		}

		// We failed. Generate a nice error message!
		StrBuf *msg = new (e) StrBuf();
		*msg << S("Failed to load the MariaDB library. Looked in the following locations:");

		for (size_t i = 0; i < ARRAY_COUNT(names); i++) {
			buffer.resize(pathEnd + strlen(names[i]) + 1);
			for (size_t j = 0; names[i][j]; j++)
				buffer[pathEnd + j] = names[i][j];
			buffer[buffer.size() - 1] = 0;

			*msg << S("\n") << &buffer[0];
		}
		throw new (e) SQLError(msg->toS());
	}

#elif defined(POSIX)

	InitFn findDriverLib(Engine &e) {
		const char *fnName = "mysql_init";
		const char *names[] = {
			"libmariadb.so.3",
			null
		};

		const char *libName = null;
		void *loaded = null;
		for (const char **name = names; loaded == null && *name != null; name++) {
			// Note: This respects rpath of the library if we set it.
			libName = *name;
			loaded = dlopen(libName, RTLD_NOW | RTLD_LOCAL);
		}

		if (!loaded) {
			StrBuf *msg = new (e) StrBuf();
			*msg << S("Failed to load the MariaDB library. Is it installed?\n");
			*msg << S("Searched for the following names:");
			for (const char **name = names; loaded == null && *name != null; name++) {
				*msg << S("\n") << toWChar(e, *name)->v;
			}

			throw new (e) SQLError(msg->toS());
		}

		void *symbol = dlsym(loaded, fnName);

		if (!symbol) {
			StrBuf *msg = new (e) StrBuf();
			*msg << S("Failed to find the function ") << toWChar(e, fnName)->v
				 << S(" in the shared library ") << libName << S(".");
			throw new (e) SQLError(msg->toS());
		}

		return reinterpret_cast<InitFn>(symbol);
	}

#endif

	MYSQL *createMariaDBDriver(Engine &e) {
		util::Lock::L z(driverLock);

		if (!mariadbInitFn)
			mariadbInitFn = findDriverLib(e);

		MYSQL *result = (*mariadbInitFn)(NULL);
		if (!result)
			throw new (e) SQLError(new (e) Str(S("Failed to create an instance of the MySQL/MariaDB driver.")));

		instances++;
		return result;
	}

	void destroyMariaDBDriver(MYSQL *driver) {
		// Close it.
		(*driver->methods->api->mysql_close)(driver);

		util::Lock::L z(driverLock);
		instances--;
		// TODO: We don't want to unload immediately, but might be relevant to unload after a while
		// of inactivity?
	}

}