/
suneido.cpp
376 lines (332 loc) · 9.15 KB
/
suneido.cpp
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
// Copyright (c) 2000 Suneido Software Corp. All rights reserved
// Licensed under GPLv2
#include "std.h"
#include "rebuildgui.h"
#include "dbhttp.h"
#include "cmdlineoptions.h"
#include "win.h"
#include "value.h"
#include "interp.h"
#include "fibers.h"
#include "dump.h"
#include "load.h"
#include "testing.h"
#include "catstr.h"
#include "alert.h"
#include "dbms.h"
#include "dbserver.h"
#include "suobject.h"
#include "call.h"
#include "sunapp.h"
#include "dbcompact.h"
#include "recover.h"
#include "globals.h"
#include "fatal.h"
#include "sustring.h"
#include "unhandled.h"
#include "msgloop.h"
#include "port.h" // for fork_rebuild for start_check
#include "exceptimp.h"
#include "build.h"
#include "ostreamstr.h"
#include "ostreamfile.h"
#include "suservice.h"
#include <cstdio> // for remove
#include <process.h>
#include "errlog.h"
void connectToConsole(bool);
static_assert(sizeof(int) == 4, "int must be 32 bits / 4 bytes");
static_assert(sizeof(short) == 2, "short must be 16 bits / 2 bytes");
static_assert(sizeof(time_t) == 4, "time_t must be 32 bits / 4 bytes");
void builtins();
/**
* Scintilla / Suneido Integration code:
* Related: vs2017scintilla -> Scintilla.h
* Purpose:
* Allows vs2017suneido to redirect Scintilla calls
* to vs2017scintilla
*/
extern "C" int Scintilla_RegisterClasses(void* hInstance);
static void init(HINSTANCE hInstance, LPSTR lpszCmdLine);
static void init2(HINSTANCE hInstance, LPSTR lpszCmdLine);
static void logPreviousErrors();
static void repl();
const char* cmdline = "";
bool is_server = false;
bool is_client = false;
CmdLineOptions cmdlineoptions;
void free_callbacks();
static VOID CALLBACK free_callbacks_timer(
HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) {
free_callbacks();
}
int pascal WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, int) {
init(hInstance, lpszCmdLine);
RegisterHotKey(nullptr, 0, MOD_CONTROL, VK_CANCEL);
SetTimer(nullptr, 0, 50, free_callbacks_timer);
message_loop(); // doesn't return
return 0;
}
static void init(HINSTANCE hInstance, LPSTR lpszCmdLine) {
try {
init2(hInstance, lpszCmdLine);
} catch (const Except& e) {
fatal(e.str(), e.callstack());
} catch (const std::exception& e) {
fatal(e.what());
}
#ifndef _MSC_VER
// with Visual C++, this catches page faults ???
catch (...) {
fatal("unknown exception");
}
#endif
}
void close_dbms() {
Fibers::foreach_tls([](ThreadLocalStorage& tls) {
delete tls.thedbms;
tls.thedbms = nullptr;
});
}
static void init2(HINSTANCE hInstance, LPSTR lpszCmdLine) {
verify(memcmp("\xff", "\x01", 1) > 0); // ensure unsigned cmp
Fibers::init();
tls().proc = new Proc;
builtins(); // internal initialization
Scintilla_RegisterClasses(hInstance);
cmdline = cmdlineoptions.parse(lpszCmdLine);
if (!cmdlineoptions.no_exception_handling)
unhandled();
if (cmdlineoptions.install) {
InstallService(cmdlineoptions.install);
exit(EXIT_SUCCESS);
} else if (cmdlineoptions.service) {
CallServiceDispatcher(cmdlineoptions.service);
exit(EXIT_SUCCESS);
}
connectToConsole(cmdlineoptions.action == REPL);
switch (cmdlineoptions.action) {
case NONE:
break;
case DUMP:
dump(cmdlineoptions.argstr);
exit(EXIT_SUCCESS);
case LOAD:
load(cmdlineoptions.argstr);
exit(EXIT_SUCCESS);
case CHECK: {
bool ok = db_check_gui();
exit(ok ? EXIT_SUCCESS : EXIT_FAILURE);
}
case REBUILD: {
bool ok = db_rebuild_gui();
exit(ok ? EXIT_SUCCESS : EXIT_FAILURE);
}
case DBDUMP:
dbdump();
exit(EXIT_SUCCESS);
case TEST: {
bool ok = run_tests(cmdlineoptions.argstr);
exit(ok ? EXIT_SUCCESS : EXIT_FAILURE);
}
case BENCH: {
OstreamStr os;
run_benchmarks(os, cmdlineoptions.argstr);
{
OstreamFile log("bench.log", "w");
log << os.gcstr();
}
alert(os.str());
exit(EXIT_SUCCESS);
}
case SERVER:
is_server = true;
start_dbserver(cmdlineoptions.argstr);
start_dbhttp();
break;
case CLIENT: {
is_client = true;
set_dbms_server_ip(cmdlineoptions.argstr);
atexit(close_dbms);
logPreviousErrors();
break;
}
case REPL:
repl();
exit(EXIT_SUCCESS);
case COMPACT:
compact();
exit(EXIT_SUCCESS);
case UNINSTALL_SERVICE:
UnInstallService();
exit(EXIT_SUCCESS);
case VERSION:
alert("Built: " << build
<< "\n"
"Copyright (C) 2000-2020 Suneido Software Corp.\n"
"All rights reserved worldwide.\n"
"Licensed under the GNU General Public License v2\n"
"\n"
"Boehm-Demers-Weiser garbage collector\n"
"www.hpl.hp.com/personal/Hans_Boehm/gc");
exit(EXIT_SUCCESS);
default:
unreachable();
}
#ifndef __GNUC__
sunapp_register_classes();
#endif
if (cmdlineoptions.check_start)
if (0 != fork_rebuild())
fatal("Database corrupt, rebuild failed, unable to start");
if (run("Init()") == SuFalse)
exit(EXIT_FAILURE);
}
static void logPreviousErrors() {
const int limit = 1000;
char* filename = err_filename();
if (FILE* f = fopen(filename, "r")) {
char buf[1024] = "PREVIOUS: ";
buf[sizeof buf - 1] = 0;
int n = 0;
for (; n < limit && fgets(buf + 10, sizeof buf - 10, f); ++n)
dbms()->log(buf);
fclose(f);
if (buf[sizeof buf - 1] != 0)
dbms()->log("ERROR: logPreviousErrors buffer overrun");
if (n >= limit)
dbms()->log("PREVIOUS: too many errors");
remove(filename);
}
}
// called by interp
void ckinterrupt() {
MSG msg;
if (HIWORD(GetQueueStatus(QS_HOTKEY))) {
bool hotkey = false;
while (PeekMessage(&msg, NULL, WM_HOTKEY, WM_HOTKEY, PM_REMOVE))
hotkey = true;
if (hotkey)
except("interrupt");
}
}
struct St {
St(const char* s_, const char* t_, uint32_t to)
: s(s_), t(t_), timeout(to) {
}
const char* s;
const char* t;
uint32_t timeout;
};
typedef int(__stdcall* MSGBOXAPI)(IN HWND hWnd, IN LPCSTR lpText,
IN LPCSTR lpCaption, IN UINT uType, IN WORD wLanguageId,
IN DWORD dwMilliseconds);
int __stdcall fallback(IN HWND hWnd, IN LPCSTR lpText, IN LPCSTR lpCaption,
IN UINT uType, IN WORD wLanguageId, IN DWORD dwMilliseconds) {
return MessageBox(hWnd, lpText, lpCaption, uType);
}
MSGBOXAPI getMessageBoxTimeout() {
auto hUser32 = LoadLibrary("user32.dll");
if (hUser32) {
auto fn = (MSGBOXAPI) GetProcAddress(hUser32, "MessageBoxTimeoutA");
FreeLibrary(hUser32);
return fn;
}
// fallback to normal MessageBox, ignoring timeout
return fallback;
}
DWORD WINAPI message_thread(void* p) {
static auto MessageBoxTimeout = getMessageBoxTimeout();
St* st = static_cast<St*>(p);
MessageBoxTimeout(0, st->t, st->s,
MB_OK | MB_TASKMODAL | MB_TOPMOST | MB_SETFOREGROUND, 0, st->timeout);
return 0;
}
// timeout is used by fatal
void message(const char* s, const char* t, uint32_t timeout_ms = INFINITE) {
St st(s, t, timeout_ms);
HANDLE thread =
CreateThread(nullptr, 0, message_thread, (void*) &st, 0, nullptr);
if (thread)
WaitForSingleObject(thread, INFINITE);
}
void handler(const Except& x) {
if (tls().proc->in_handler) {
if (cmdlineoptions.unattended)
errlog("Error in Handler:", x.str());
else
message("Error in Handler", x.str());
return;
}
tls().proc->in_handler = true;
// TODO: use GetAncestor
// determine top level window responsible
HWND hwnd = 0; // msg.hwnd;
// while (HWND parent = GetParent(hwnd))
// hwnd = parent;
try {
call("Handler", Lisp<Value>((SuValue*) &x, (int) hwnd, x.calls()));
} catch (const Except& e) {
message("Error in Handler", e.str());
}
tls().proc->in_handler = false;
}
bool getSystemOption(const char* option, bool def_value) {
if (SuObject* suneido = val_cast<SuObject*>(globals["Suneido"]))
if (Value val = suneido->get(option))
return (val == SuTrue) ? true
: (val == SuFalse) ? false : def_value;
return def_value;
}
#include <io.h>
#include "func.h"
#include "ostreamstd.h"
#include "builtin.h"
BUILTIN(PrintStdout, "(s)") {
const int nargs = 1;
cout << ARG(0).gcstr();
return Value();
}
static void repl() {
globals["Suneido"].putdata("Print", globals["PrintStdout"]);
cerr << "Built: " << build << endl;
cerr << "Note: use start/w suneido -repl" << endl;
cerr << "Press Enter twice (i.e. blank line) to execute, q to quit" << endl;
run("Init.Repl()");
char buf[4096];
char* lim = buf + sizeof buf;
for (;;) {
cerr << "~~~" << endl;
char* dst = buf;
while (fgets(dst, lim - dst, stdin)) {
if (dst[0] == 'q' && dst[1] == '\n')
return;
if (dst[0] == '\n')
break;
dst += strlen(dst);
}
if (dst == buf)
return; // eof
try {
if (Value x = run(buf)) {
auto type = gcstring(x.type());
auto ss = val_cast<SuString*>(x);
if (ss && ss->gcstr().is_concat())
type = " <concat>";
else if (type == "String" || type == "Boolean" ||
type == "Date")
type = "";
else if (val_cast<SuNumber*>(x))
type = " <Dnum>";
else if (x.is_int())
type = " <int>";
else
type = " <" + type + ">";
cout << x << type << endl;
}
} catch (Except& e) {
cerr << e << endl;
cerr << e.callstack() << endl;
}
}
}