- Notifications
You must be signed in to change notification settings - Fork 337
/
Copy pathutil_functions.cpp
832 lines (690 loc) · 22.7 KB
/
util_functions.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
/*
* Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.0,
* as published by the Free Software Foundation.
*
* This program is designed to work with certain software (including
* but not limited to OpenSSL) that is licensed under separate terms, as
* designated in a particular file or component or in included license
* documentation. The authors of MySQL hereby grant you an additional
* permission to link the program and your derivative works with the
* separately licensed software that they have either included with
* the program or referenced in the documentation.
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License, version 2.0, for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include<glib/gstdio.h>
#include<cstdio>
#include<sstream>
#include<fstream>
#include<vector>
#include"base/log.h"
#include"base/common.h"
#include"base/string_utilities.h"
#include"base/file_utilities.h"
#include"workbench/wb_version.h"
// Windows includes
#ifdef _MSC_VER
#include<windows.h>
#include<direct.h>
#include<tchar.h>
#include<strsafe.h>
#else
// unix/linux includes
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<assert.h>
#ifdef HAVE_CONFIG_H
#include"config.h"
#endif
#include<sys/time.h>
#ifdef HAVE_SYS_SELECT_H
#include<sys/select.h>
#endif
#include<errno.h>
#include<unistd.h>
#include<signal.h>
#include<sys/wait.h>
#include<sys/utsname.h>// uname()
#include<fcntl.h>
#defineSIZE_Tsize_t
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#endif
#if defined(__APPLE__) && defined(__MACH__)
#include<sys/sysctl.h>
#include<mach/machine.h>
#endif
#include"base/file_functions.h"
#include"base/util_functions.h"
DEFAULT_LOG_DOMAIN(DOMAIN_BASE)
struct hardware_info {
std::string _cpu;
std::string _clock;
unsignedint _cpu_count;
std::int64_t _memory_in_bytes;
};
//----------------------------------------------------------------------------------------------------------------------
char *auto_line_break(constchar *txt, unsignedint width, char sep) {
char *dst = (char *)g_malloc((width + 2) * 80);
unsignedint i, o = 0, p = 0, w = 0, l = (unsignedint)strlen(txt);
for (i = 0; i < l;) {
w++;
if (w > width) {
#if defined(_MSC_VER)
dst[p + o] = '\r';
dst[p + o + 1] = '\n';
o += 1;
#else
dst[p + o] = '\n';
#endif
i = p + 1;
w = 0;
} else {
dst[i + o] = txt[i];
if (txt[i] == sep)
p = i;
i++;
}
}
dst[i + o] = 0;
return dst;
}
//----------------------------------------------------------------------------------------------------------------------
intstr_is_numeric(constchar *str) {
unsignedint len = (unsignedint)strlen(str);
unsignedint i;
for (i = 0; i < len; i++)
if (g_ascii_digit_value(str[i]) == -1)
return0;
return1;
}
//----------------------------------------------------------------------------------------------------------------------
char *str_toupper(char *str) {
char *s = str;
while (*s) {
*s = (char)toupper(*s);
s++;
}
return str;
}
//----------------------------------------------------------------------------------------------------------------------
#if defined(_MSC_VER)
#defineBUFSIZE256
#defineVER_SUITE_WH_SERVER0x00008000
intget_value_from_registry(HKEY root_key, constchar *sub_key, constchar *key, constchar *def, char *value,
int target_size) {
HKEY hSubKey;
DWORD dwType;
DWORD dwSize;
LONG retval;
unsignedchar Buffer[512];
// Explicitly link to ANSI version, we are using ANSI key names only here.
if ((retval = RegOpenKeyExA(root_key, sub_key, 0, KEY_READ, &hSubKey)) == ERROR_SUCCESS) {
dwSize = 512;
if ((RegQueryValueExA(hSubKey, key, NULL, &dwType, Buffer, &dwSize)) == ERROR_SUCCESS) {
if (dwType == REG_DWORD) {
sprintf_s(value, target_size, "%d", Buffer[0] + Buffer[1] * 256 + Buffer[2] * 65536 + Buffer[3] * 16777216);
} else {
StringCchCopy((LPTSTR)value, BUFSIZE, (LPTSTR)Buffer);
}
} else {
StringCchCopy((LPTSTR)value, BUFSIZE, (LPTSTR)def);
}
return0;
} else {
StringCchCopy((LPTSTR)value, BUFSIZE, (LPTSTR) "");
return retval;
}
}
//----------------------------------------------------------------------------------------------------------------------
intset_value_to_registry(HKEY root_key, constchar *sub_key, constchar *key, constchar *value) {
HKEY hSubKey;
LONG retval;
DWORD dwDispo;
if ((retval = RegCreateKeyExA(root_key, sub_key, 0, "", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hSubKey,
&dwDispo)) == ERROR_SUCCESS) {
retval = RegSetValueExA(hSubKey, key, 0, REG_SZ, (const BYTE *)value, (DWORD)strlen(value) + 1);
if (retval != ERROR_SUCCESS) {
returnGetLastError();
} else {
return0;
}
} else {
return -1;
}
}
//----------------------------------------------------------------------------------------------------------------------
typedefvoid(WINAPI *PGNSI)(LPSYSTEM_INFO);
typedefBOOL(WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD);
std::string get_local_os_name() {
std::string result;
char buffer[BUFSIZE];
std::string product_name;
if (get_value_from_registry(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", "",
buffer, BUFSIZE) == 0)
product_name = buffer;
std::string csd_version;
if (get_value_from_registry(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "CSDVersion", "",
buffer, BUFSIZE) == 0)
csd_version = buffer;
if (!product_name.empty()) {
result = (base::hasPrefix(product_name, "Microsoft") ? "" : "Microsoft ") + product_name;
if (!csd_version.empty())
result += "" + csd_version;
}
return result;
}
//----------------------------------------------------------------------------------------------------------------------
std::string get_local_hardware_info() {
char *hardware_string;
SYSTEM_INFO sysinfo;
MEMORYSTATUSEX memstat;
char processor_name[BUFSIZE];
char processor_mhz[BUFSIZE];
char total_phys_ram[BUFSIZE];
DWORDLONG total_phys_ram_val;
int target_size;
GetSystemInfo(&sysinfo);
memstat.dwLength = sizeof(memstat);
GlobalMemoryStatusEx(&memstat);
ZeroMemory(processor_mhz, sizeof(processor_mhz));
ZeroMemory(processor_name, sizeof(processor_name));
get_value_from_registry(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "~MHz", "",
processor_mhz, BUFSIZE);
get_value_from_registry(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
"ProcessorNameString", "", processor_name, BUFSIZE);
if (!processor_name[0]) {
get_value_from_registry(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "Identifier", "",
processor_name, BUFSIZE);
sprintf_s(processor_name, BUFSIZE, "%s %s", processor_name, processor_mhz);
}
base::trim(processor_name);
total_phys_ram_val = memstat.ullTotalPhys;
if (total_phys_ram_val >= 1072410624 / 1.9) {
sprintf_s(total_phys_ram, BUFSIZE, "%1.1f GiB RAM", (double)total_phys_ram_val / 1072410624.0);
} elseif (total_phys_ram_val >= 1047276 / 1.9) {
sprintf_s(total_phys_ram, BUFSIZE, "%1.0f MiB RAM", (double)total_phys_ram_val / 1047276.0);
} else {
sprintf_s(total_phys_ram, BUFSIZE, "%lld B RAM", total_phys_ram_val);
}
target_size = 16 + (int)strlen(processor_name) + (int)strlen(total_phys_ram);
hardware_string = (char *)g_malloc(target_size);
if (sysinfo.dwNumberOfProcessors > 1) {
sprintf_s(hardware_string, target_size, "%dx %s, %s", sysinfo.dwNumberOfProcessors, processor_name, total_phys_ram);
} else {
sprintf_s(hardware_string, target_size, "%s, %s", processor_name, total_phys_ram);
}
return hardware_string;
}
#else
#if defined(__APPLE__) && defined(__MACH__)
std::string get_local_os_name() {
structutsname info;
if (uname(&info) < 0)
return"unknown";
char *dot_position = strstr(info.release, ".");
if (dot_position == NULL)
return"unknown";
*dot_position = 0;
int version = base::atoi<int>(info.release, 0);
switch (version) {
case23:
returnstd::string("macOS 14.x Sonoma ") + info.machine;
case22:
returnstd::string("macOS 13.x Ventura ") + info.machine;
case21:
returnstd::string("macOS 12.x Monterey ") + info.machine;
case20:
returnstd::string("macOS 11.x Big Sur ") + info.machine;
case19:
returnstd::string("macOS 10.15.x Catalina ") + info.machine;
}
return"unknown";
}
staticconstchar *get_cpu_type_name(int cpu_type, int cpu_subtype) {
switch (cpu_type) {
case CPU_TYPE_I386:
switch (cpu_subtype) {
case CPU_SUBTYPE_386:
return"80386";
case CPU_SUBTYPE_486:
return"80486";
case CPU_SUBTYPE_486SX:
return"80486SX";
case CPU_SUBTYPE_PENT:
return"Pentium";
case CPU_SUBTYPE_PENTPRO:
return"Pentium Pro";
case CPU_SUBTYPE_PENTII_M3:
return"Pentium II";
case CPU_SUBTYPE_PENTII_M5:
return"Pentium II";
#ifdef CPU_SUBTYPE_CELERON
case CPU_SUBTYPE_CELERON:
return"Celeron";
#endif
#ifdef CPU_SUBTYPE_CELERON_MOBILE
case CPU_SUBTYPE_CELERON_MOBILE:
return"Celeron Mobile";
#endif
#ifdef CPU_SUBTYPE_PENTIUM_3
case CPU_SUBTYPE_PENTIUM_3:
return"Pentium III";
#endif
#ifdef CPU_SUBTYPE_PENTIUM_3_M
case CPU_SUBTYPE_PENTIUM_3_M:
return"Pentium III M";
#endif
#ifdef CPU_SUBTYPE_PENTIUM_3_XEON
case CPU_SUBTYPE_PENTIUM_3_XEON:
return"Pentium III Xeon";
#endif
#ifdef CPU_SUBTYPE_PENTIUM_M
case CPU_SUBTYPE_PENTIUM_M:
return"Pentium M";
#endif
#ifdef CPU_SUBTYPE_PENTIUM_4
case CPU_SUBTYPE_PENTIUM_4:
return"Pentium 4";
#endif
#ifdef CPU_SUBTYPE_PENTIUM_4_M
case CPU_SUBTYPE_PENTIUM_4_M:
return"Pentium 4M";
#endif
#ifdef CPU_SUBTYPE_ITANIUM
case CPU_SUBTYPE_ITANIUM:
return"Itanium";
#endif
#ifdef CPU_SUBTYPE_ITANIUM_2
case CPU_SUBTYPE_ITANIUM_2:
return"Itanium 2";
#endif
#ifdef CPU_SUBTYPE_XEON
case CPU_SUBTYPE_XEON:
return"Xeon";
#endif
#ifdef CPU_SUBTYPE_XEON_MP
case CPU_SUBTYPE_XEON_MP:
return"Xeon MP";
#endif
default:
return"x86";
}
break;
case CPU_TYPE_POWERPC:
switch (cpu_subtype) {
case CPU_SUBTYPE_POWERPC_601:
return"PowerPC 601";
case CPU_SUBTYPE_POWERPC_602:
return"PowerPC 602";
case CPU_SUBTYPE_POWERPC_603:
return"PowerPC 603";
case CPU_SUBTYPE_POWERPC_603e:
return"PowerPC 603e";
case CPU_SUBTYPE_POWERPC_603ev:
return"PowerPC 603ev";
case CPU_SUBTYPE_POWERPC_604:
return"PowerPC 604";
case CPU_SUBTYPE_POWERPC_604e:
return"PowerPC 604e";
case CPU_SUBTYPE_POWERPC_620:
return"PowerPC 620";
case CPU_SUBTYPE_POWERPC_750:
return"PowerPC G3";
case CPU_SUBTYPE_POWERPC_7400:
return"PowerPC G4";
case CPU_SUBTYPE_POWERPC_7450:
return"PowerPC G4";
case CPU_SUBTYPE_POWERPC_970:
return"PowerPC G5";
default:
return"PowerPC";
}
break;
}
return"Unknown";
}
//----------------------------------------------------------------------------------------------------------------------
// macOS
staticint_get_hardware_info(hardware_info &info) {
int mib[2];
size_t length;
int tmp;
char *mclass;
int cpu_type, cpu_subtype;
if (sysctlbyname("machdep.cpu.brand_string", NULL, &length, NULL, 0) != -1) {
char *cpu = (char *)g_malloc(length + 1);
sysctlbyname("machdep.cpu.brand_string", cpu, &length, NULL, 0);
info._cpu = base::trim(cpu, "\n");
g_free(cpu);
} else {
// get machine class
mib[0] = CTL_HW;
mib[1] = HW_MACHINE;
sysctl(mib, 2, NULL, &length, NULL, 0);
mclass = (char *)g_malloc(length * sizeof(char *));
sysctl(mib, 2, mclass, &length, NULL, 0);
// get machine arch
length = sizeof(cpu_type);
sysctlbyname("hw.cputype", &cpu_type, &length, NULL, 0);
length = sizeof(cpu_subtype);
sysctlbyname("hw.cpusubtype", &cpu_subtype, &length, NULL, 0);
info._cpu = base::strfmt("%s (%s)", mclass, get_cpu_type_name(cpu_type, cpu_subtype));
g_free(mclass);
// get cpu clock
mib[0] = CTL_HW;
mib[1] = HW_CPU_FREQ;
length = sizeof(tmp);
if (sysctl(mib, 2, &tmp, &length, NULL, 0) < 0)
info._clock = base::strfmt("?");
else
info._clock = base::strfmt("%.01f", (double)tmp / 1000000.0);
}
// get cpu count
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
length = sizeof(info._cpu_count);
if (sysctl(mib, 2, &info._cpu_count, &length, NULL, 0) < 0)
info._cpu_count = 1;
// get memory size
info._memory_in_bytes = get_physical_memory_size();
return0;
}
//----------------------------------------------------------------------------------------------------------------------
#else
// Linux/Unix version
std::string get_local_os_name() {
auto is_debian_based = [](structutsname &info) -> bool {
returnstrstr(info.version, "Ubuntu") orstrstr(info.version, "Debian");
};
// get distro name and version - Debian-based systems
auto get_lsb_release_param = [](char param) -> std::string {
char cmd[] = "lsb_release -_";
cmd[sizeof(cmd) - 2] = param; // replace _ with param
int rc;
char *stdo;
std::string result;
GError *error;
if (g_spawn_command_line_sync(cmd, &stdo, NULL, &rc, &error) && stdo) {
char *d = strchr(stdo, ':');
if (d)
result = base::trim(g_strchug(d + 1));
g_free(stdo);
return result;
} else {
logError("Error executing lsb_release -%c: %s\n", param, error->message);
returnstd::string("unknown");
}
};
// get distro name and version - Red-Hat-based systems
auto cat_redhat_release = []() -> std::string {
std::ifstream is;
try {
is.open("/etc/redhat-release", std::ifstream::in);
char buf[256];
is.getline(buf, 256);
returnstd::string(buf);
} catch (const std::ios_base::failure &e) {
logError("Error reading /etc/redhat-release: %s\n", e.what());
returnstd::string("unknown");
}
};
structutsname info;
if (uname(&info) < 0)
return"unknown";
elseif (is_debian_based(info))
returnget_lsb_release_param('i') + '' + get_lsb_release_param('r') + '' + info.machine;
else
returncat_redhat_release() + '' + info.machine;
}
//----------------------------------------------------------------------------------------------------------------------
staticint_get_hardware_info(hardware_info &info) {
FILE *proc;
char line[256];
// fetch processor info from /proc/cpuinfo
proc = fopen("/proc/cpuinfo", "r");
if (!proc) {
return -1;
}
info._cpu_count = 0;
while (!feof(proc)) {
if (!fgets(line, sizeof(line), proc))
break;
if (base::hasPrefix(line, "model name")) {
info._cpu_count++;
info._cpu = base::trim(base::split(line, ":")[1], "\n");
} elseif (base::hasPrefix(line, "cpu MHz")) {
info._clock = base::trim(base::split(line, ":")[1], "\n");
}
}
fclose(proc);
info._memory_in_bytes = get_physical_memory_size();
return0;
}
#endif
//----------------------------------------------------------------------------------------------------------------------
std::string get_local_hardware_info() {
std::stringstream hardware_string;
hardware_info info;
_get_hardware_info(info);
if (info._cpu_count > 1)
hardware_string << info._cpu_count << "x ";
hardware_string << info._cpu;
if (!info._clock.empty())
hardware_string << " (" << info._clock << "MHz)";
hardware_string << " - " << base::sizefmt(info._memory_in_bytes, false) << " RAM";
return hardware_string.str();
}
#endif
//----------------------------------------------------------------------------------------------------------------------
std::int64_tget_physical_memory_size() {
#if defined(_MSC_VER)
MEMORYSTATUS memstat;
GlobalMemoryStatus(&memstat);
return memstat.dwTotalPhys;
#elif defined(__APPLE__)
std::uint64_t mem64;
int mib[2];
int mem32;
size_t length;
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
length = sizeof(mem64);
if (sysctl(mib, 2, &mem64, &length, NULL, 0) < 0) {
mib[0] = CTL_HW;
mib[1] = HW_PHYSMEM;
length = sizeof(mem32);
sysctl(mib, 2, &mem32, &length, NULL, 0);
mem64 = mem32;
}
return mem64;
#else
FILE *proc;
std::int64_t mem64;
mem64 = 0;
// fetch physical memory info from /proc/meminfo
proc = fopen("/proc/meminfo", "r");
if (proc) {
char line[1024];
char *ptr, *end;
while (fgets(line, sizeof(line), proc)) {
if (strncasecmp(line, "MemTotal:", sizeof("MemTotal:") - 1) == 0) {
char *line_end = line + strlen(line);
ptr = strchr(line, ':') + 1;
while (*ptr && *ptr == '')
ptr++;
end = strchr(ptr, '');
if (end)
*end = 0;
if (end < line_end)
end++;
if (strstr(end, "gB") || strstr(end, "GB"))
mem64 = strtoul(base::trim(ptr).c_str(), NULL, 10) * 1024 * 1024 * 1024LL;
elseif (strstr(end, "mB") || strstr(end, "MB"))
mem64 = strtoul(base::trim(ptr).c_str(), NULL, 10) * 1024 * 1024LL;
elseif (strstr(end, "kB") || strstr(end, "KB"))
mem64 = strtoul(base::trim(ptr).c_str(), NULL, 10) * 1024LL;
else
mem64 = strtoul(base::trim(ptr).c_str(), NULL, 10);
break;
}
}
fclose(proc);
}
return mem64;
#endif
}
//----------------------------------------------------------------------------------------------------------------------
std::int64_tget_file_size(constchar *filename) {
#if _MSC_VER
DWORD dwSizeLow;
DWORD dwSizeHigh = 0;
HANDLE hfile;
std::wstring name = base::string_to_wstring(filename);
hfile = CreateFile(name.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hfile != INVALID_HANDLE_VALUE) {
dwSizeLow = GetFileSize(hfile, &dwSizeHigh);
CloseHandle(hfile);
if ((dwSizeLow == INVALID_FILE_SIZE) && (GetLastError()) != NO_ERROR) {
return -1;
} else {
return (((std::int64_t)dwSizeHigh << 32) + dwSizeLow);
}
} else
return -1;
#else//! WINDOWS
structstat buf;
char *local_filename;
if (!(local_filename = g_filename_from_utf8(filename, -1, NULL, NULL, NULL)))
return -1;
if (stat(local_filename, &buf) < 0) {
g_free(local_filename);
return -1;
}
g_free(local_filename);
return buf.st_size;
#endif//! WINDOWS
}
// note, needle has to be ascii!
char *strcasestr_len(constchar *haystack, int haystack_len, constchar *needle) {
gssize needle_len = (gssize)strlen(needle);
int i;
if (needle_len > haystack_len)
returnNULL;
i = 0;
while (i <= haystack_len - needle_len) {
if (g_ascii_strncasecmp(needle, haystack + i, needle_len) == 0)
return (char *)haystack + i;
i++;
}
returnNULL;
}
//----------------------------------------------------------------------------------------------------------------------
constchar *strfindword(constchar *str, constchar *word) {
constchar *result = NULL;
constchar *ptr;
size_t wordlen = strlen(word);
ptr = str;
for (;;) {
// find match
ptr = strcasestr_len(ptr, (int)strlen(ptr), word);
if (!ptr)
break;
// check if its acceptable
if ((ptr == str || !isalnum(*(ptr - 1))) && // space or any other non-alpha-numeric before
(!isalnum(*(ptr + wordlen)) || *(ptr + wordlen) == '\0')) // space or any other non-alpha-numeric after
{
result = ptr;
break;
};
ptr += wordlen;
}
return result;
}
//--------------------------------------------------------------------------------------------------
// TODO: move to file_functions
/**
* Copies all files non-recursively from source to target. Target will be created on the fly.
*/
intcopy_folder(constchar *source_folder, constchar *target_folder) {
constchar *entry;
GDir *dir;
// Create target folder.
if (!g_file_test(target_folder, G_FILE_TEST_IS_DIR))
if (g_mkdir(target_folder, 0700) < 0)
return0;
dir = g_dir_open(source_folder, 0, NULL);
if (dir) {
while ((entry = g_dir_read_name(dir)) != NULL) {
char *source = g_build_filename(source_folder, entry, NULL);
char *target = g_build_filename(target_folder, entry, NULL);
if (!base::copyFile(source, target)) {
logWarning("Could not copy file %s to %s: %s\n", source, target, g_strerror(errno));
g_free(source);
g_free(target);
g_dir_close(dir);
return0;
}
g_free(source);
g_free(target);
}
g_dir_close(dir);
} else {
logWarning("Could not open directory %s\n", source_folder);
return0;
}
return1;
}
//--------------------------------------------------------------------------------------------------
namespacebase {
doubletimestamp() {
#if defined(_MSC_VER)
return (double)GetTickCount() / 1000.0;
#else
structtimeval tv;
gettimeofday(&tv, NULL);
double seconds = tv.tv_sec;
double fraction = tv.tv_usec / (double)(1000000);
return seconds + fraction;
#endif
}
//--------------------------------------------------------------------------------------------------
std::string fmttime(time_t t, constchar *fmt) {
char date[100];
#ifdef _MSC_VER
errno_t err;
#else
int err;
#endif
structtm newtime;
if (t == 0)
time(&t);
#ifdef _MSC_VER
err = localtime_s(&newtime, &t);
#else
localtime_r(&t, &newtime);
err = 0;
#endif
if (!err)
strftime(date, sizeof(date), fmt, &newtime);
else
date[0] = 0;
return date;
}
BASELIBRARY_PUBLIC_FUNC std::string getVersion(void) {
returnstrfmt("%u.%u.%u", APP_MAJOR_NUMBER, APP_MINOR_NUMBER, APP_RELEASE_NUMBER);
}
} // namespace base
//--------------------------------------------------------------------------------------------------