-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrsh.cpp
More file actions
1777 lines (1573 loc) · 57.3 KB
/
Copy pathrsh.cpp
File metadata and controls
1777 lines (1573 loc) · 57.3 KB
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// RunicShell26 (2.0.1 2026) Copyright (C) 2026, Roberto J Dohnert. All rights reserved.
// 2nd generation rjdsh.cpp - ksh93-compatible shell in C++17 for Windows Server 2022 + Server 2025
// based on the original rsh.cpp by rjdohnert, with extensive modifications and improvements from 2005 to 2024, now rewritten in C++17
// and added features like command history, tab completion, background job control, and better script execution.
// This file is licensed under the BSD-3 Clause License. See LICENSE.txt for details.
// Note: This implementation focuses on ksh93 compatibility and is not intended to be a full POSIX shell. It includes a subset of
// features and built-in commands, and may have limitations compared to a full ksh93 shell.
// Version 2.0.1 (2026) - 2nd generation rewrite with C++17, added features, and improved ksh93 compatibility
// Rewrite started in 2024 and completed in 2026, with ongoing maintenance and improvements expected.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <cwctype>
#include <regex>
#include <windows.h>
#include <winternl.h>
#include <io.h>
#include <fcntl.h>
#include <conio.h>
#pragma comment(lib, "Advapi32.lib")
// ksh93 Environment State & Variables Registry
struct KshEnvironment {
std::map<std::wstring, std::wstring> variables;
std::map<std::wstring, std::vector<std::wstring>> arrays;
std::map<std::wstring, bool> exported;
} ksh_env;
// Forward declarations
std::wstring evaluate_arithmetic(const std::wstring& expr);
std::wstring evaluate_command_substitutions(const std::wstring& input);
bool execute_script_file(const std::wstring& script_path, const std::vector<std::wstring>& script_args, bool& should_exit_shell);
bool execute_command_line(const std::wstring& input_line, bool& should_exit_shell);
std::wstring trim_copy(const std::wstring& value);
struct ScriptContext {
std::wstring script_name;
std::vector<std::wstring> args;
};
struct BackgroundJob {
int id;
DWORD pid;
HANDLE process_handle;
std::wstring command;
bool completed;
DWORD exit_code;
bool completion_reported;
};
std::vector<ScriptContext> g_script_context_stack;
std::vector<std::wstring> g_command_history;
std::vector<BackgroundJob> g_background_jobs;
int g_next_job_id = 1;
std::wstring g_history_file_path;
bool g_is_interactive_session = false;
std::wstring get_history_file_path() {
wchar_t appdata_path[MAX_PATH];
DWORD appdata_len = GetEnvironmentVariableW(L"APPDATA", appdata_path, MAX_PATH);
if (appdata_len > 0 && appdata_len < MAX_PATH) {
return std::wstring(appdata_path) + L"\\rsh_history.txt";
}
wchar_t userprofile_path[MAX_PATH];
DWORD userprofile_len = GetEnvironmentVariableW(L"USERPROFILE", userprofile_path, MAX_PATH);
if (userprofile_len > 0 && userprofile_len < MAX_PATH) {
return std::wstring(userprofile_path) + L"\\AppData\\Roaming\\rsh_history.txt";
}
return L"rsh_history.txt";
}
void load_command_history_from_file() {
g_history_file_path = get_history_file_path();
std::wifstream history_file(g_history_file_path.c_str());
if (!history_file.is_open()) {
return;
}
std::wstring line;
while (std::getline(history_file, line)) {
std::wstring trimmed = trim_copy(line);
if (!trimmed.empty()) {
g_command_history.push_back(trimmed);
}
}
}
void append_history_entry_to_file(const std::wstring& command_line) {
if (command_line.empty()) {
return;
}
if (g_history_file_path.empty()) {
g_history_file_path = get_history_file_path();
}
std::wofstream history_file(g_history_file_path.c_str(), std::ios::app);
if (!history_file.is_open()) {
return;
}
history_file << command_line << L"\n";
}
std::wstring format_bytes_iec(ULONGLONG bytes) {
static const wchar_t* units[] = { L"B", L"KiB", L"MiB", L"GiB", L"TiB" };
double value = static_cast<double>(bytes);
size_t unit_index = 0;
while (value >= 1024.0 && unit_index + 1 < _countof(units)) {
value /= 1024.0;
unit_index++;
}
wchar_t buffer[64];
if (unit_index == 0) {
_snwprintf_s(buffer, _countof(buffer), _TRUNCATE, L"%llu %s", bytes, units[unit_index]);
} else {
_snwprintf_s(buffer, _countof(buffer), _TRUNCATE, L"%.2f %s", value, units[unit_index]);
}
return buffer;
}
std::wstring get_registry_string(HKEY root, const wchar_t* subkey, const wchar_t* value_name) {
wchar_t buffer[256];
DWORD size = static_cast<DWORD>(sizeof(buffer));
LONG status = RegGetValueW(root, subkey, value_name, RRF_RT_REG_SZ, nullptr, buffer, &size);
if (status != ERROR_SUCCESS) {
return L"";
}
return std::wstring(buffer);
}
std::wstring get_windows_release_text() {
std::wstring product_name = get_registry_string(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"ProductName");
std::wstring display_version = get_registry_string(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"DisplayVersion");
typedef LONG(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
RtlGetVersionPtr rtl_get_version = (ntdll != nullptr)
? reinterpret_cast<RtlGetVersionPtr>(GetProcAddress(ntdll, "RtlGetVersion"))
: nullptr;
RTL_OSVERSIONINFOEXW os = {};
os.dwOSVersionInfoSize = sizeof(os);
wchar_t version_text[96] = L"unknown";
if (rtl_get_version != nullptr && rtl_get_version(reinterpret_cast<PRTL_OSVERSIONINFOW>(&os)) == 0) {
_snwprintf_s(version_text, _countof(version_text), _TRUNCATE, L"%lu.%lu.%lu", os.dwMajorVersion, os.dwMinorVersion, os.dwBuildNumber);
}
std::wstring release = product_name.empty() ? L"Windows" : product_name;
release += L" (";
release += version_text;
if (!display_version.empty()) {
release += L", ";
release += display_version;
}
release += L")";
return release;
}
void print_startup_system_info() {
std::wcout << L"OS Release: " << get_windows_release_text() << L"\n";
MEMORYSTATUSEX mem = {};
mem.dwLength = sizeof(mem);
if (GlobalMemoryStatusEx(&mem)) {
const ULONGLONG used_physical = mem.ullTotalPhys - mem.ullAvailPhys;
std::wcout << L"Memory Use: " << mem.dwMemoryLoad << L"%\n";
std::wcout << L" Physical: "
<< format_bytes_iec(used_physical)
<< L" used / "
<< format_bytes_iec(mem.ullTotalPhys)
<< L" total\n";
std::wcout << L" Available: " << format_bytes_iec(mem.ullAvailPhys) << L"\n";
} else {
std::wcout << L"Memory Use: unavailable\n";
}
}
std::wstring longest_common_prefix_case_insensitive(const std::vector<std::wstring>& values) {
if (values.empty()) {
return L"";
}
std::wstring prefix = values[0];
for (size_t i = 1; i < values.size() && !prefix.empty(); ++i) {
size_t common = 0;
size_t limit = (prefix.size() < values[i].size()) ? prefix.size() : values[i].size();
while (common < limit && std::towlower(prefix[common]) == std::towlower(values[i][common])) {
common++;
}
prefix = prefix.substr(0, common);
}
return prefix;
}
std::wstring to_lower_copy(const std::wstring& value) {
std::wstring lower;
lower.reserve(value.size());
for (wchar_t ch : value) {
lower.push_back(static_cast<wchar_t>(std::towlower(ch)));
}
return lower;
}
bool starts_with_case_insensitive(const std::wstring& value, const std::wstring& prefix) {
if (prefix.size() > value.size()) {
return false;
}
for (size_t i = 0; i < prefix.size(); ++i) {
if (std::towlower(value[i]) != std::towlower(prefix[i])) {
return false;
}
}
return true;
}
std::vector<std::wstring> builtin_commands() {
return {
L"exit", L"source", L".", L"typeset", L"[[", L"cd", L"print", L"echo", L"history", L"complete", L"math",
L"jobs", L"fg", L"kill", L"wait"
};
}
void add_completion_candidate(std::map<std::wstring, std::wstring>& candidates, const std::wstring& candidate, const std::wstring& prefix) {
if (candidate.empty()) {
return;
}
if (!prefix.empty() && !starts_with_case_insensitive(candidate, prefix)) {
return;
}
candidates[to_lower_copy(candidate)] = candidate;
}
void scan_directory_for_completions(const std::wstring& directory, const std::wstring& prefix, std::map<std::wstring, std::wstring>& candidates) {
if (directory.empty()) {
return;
}
std::wstring pattern = directory;
if (!pattern.empty() && pattern.back() != L'\\' && pattern.back() != L'/') {
pattern += L"\\";
}
pattern += L"*";
WIN32_FIND_DATAW find_data;
HANDLE handle = FindFirstFileW(pattern.c_str(), &find_data);
if (handle == INVALID_HANDLE_VALUE) {
return;
}
do {
if ((find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
continue;
}
std::wstring name = find_data.cFileName;
add_completion_candidate(candidates, name, prefix);
size_t dot = name.find_last_of(L'.');
if (dot != std::wstring::npos) {
std::wstring extension = to_lower_copy(name.substr(dot));
if (extension == L".exe" || extension == L".cmd" || extension == L".bat" || extension == L".com") {
add_completion_candidate(candidates, name.substr(0, dot), prefix);
}
}
} while (FindNextFileW(handle, &find_data));
FindClose(handle);
}
std::vector<std::wstring> collect_completion_candidates(const std::wstring& prefix) {
std::map<std::wstring, std::wstring> candidates;
for (const std::wstring& builtin : builtin_commands()) {
add_completion_candidate(candidates, builtin, prefix);
}
wchar_t cwd[MAX_PATH];
if (GetCurrentDirectoryW(MAX_PATH, cwd) > 0) {
scan_directory_for_completions(cwd, prefix, candidates);
}
wchar_t path_buf[32767];
DWORD path_len = GetEnvironmentVariableW(L"PATH", path_buf, 32767);
if (path_len > 0 && path_len < 32767) {
std::wstring path_value(path_buf);
size_t start = 0;
while (start <= path_value.size()) {
size_t sep = path_value.find(L';', start);
std::wstring entry = (sep == std::wstring::npos)
? path_value.substr(start)
: path_value.substr(start, sep - start);
entry = trim_copy(entry);
if (!entry.empty()) {
scan_directory_for_completions(entry, prefix, candidates);
}
if (sep == std::wstring::npos) {
break;
}
start = sep + 1;
}
}
std::vector<std::wstring> matches;
for (const auto& kv : candidates) {
matches.push_back(kv.second);
}
return matches;
}
void render_input_line(const std::wstring& prompt, const std::wstring& buffer, size_t cursor_pos) {
std::wcout << L"\r" << prompt << buffer << L" ";
const size_t trailing = buffer.size() - cursor_pos;
for (size_t i = 0; i <= trailing; ++i) {
std::wcout << L'\b';
}
std::wcout.flush();
}
bool read_interactive_line(const std::wstring& prompt, std::wstring& output) {
std::wstring buffer;
size_t cursor = 0;
size_t history_index = g_command_history.size();
std::wstring saved_current_line;
std::wcout << prompt;
std::wcout.flush();
while (true) {
wint_t ch = _getwch();
if (ch == 26) {
if (buffer.empty()) {
std::wcout << L"\n";
return false;
}
continue;
}
if (ch == 13) {
std::wcout << L"\n";
output = buffer;
return true;
}
if (ch == 3) {
std::wcout << L"^C\n";
output.clear();
return true;
}
if (ch == 9) {
size_t token_start = cursor;
while (token_start > 0 && !std::iswspace(buffer[token_start - 1])) {
token_start--;
}
std::wstring prefix = buffer.substr(token_start, cursor - token_start);
std::vector<std::wstring> matches = collect_completion_candidates(prefix);
if (matches.empty()) {
std::wcout << L'\a';
std::wcout.flush();
continue;
}
std::wstring replacement = matches[0];
if (matches.size() > 1) {
std::wstring common_prefix = longest_common_prefix_case_insensitive(matches);
if (common_prefix.size() > prefix.size()) {
replacement = common_prefix;
} else {
std::wcout << L"\n";
for (const std::wstring& match : matches) {
std::wcout << match << L"\n";
}
render_input_line(prompt, buffer, cursor);
continue;
}
}
buffer.replace(token_start, cursor - token_start, replacement);
cursor = token_start + replacement.size();
if (matches.size() == 1 && (cursor == buffer.size() || !std::iswspace(buffer[cursor]))) {
buffer.insert(cursor, 1, L' ');
cursor++;
}
render_input_line(prompt, buffer, cursor);
continue;
}
if (ch == 8) {
if (cursor > 0) {
buffer.erase(cursor - 1, 1);
cursor--;
render_input_line(prompt, buffer, cursor);
}
continue;
}
if (ch == 0 || ch == 224) {
wint_t key = _getwch();
if (key == 72) {
if (!g_command_history.empty()) {
if (history_index == g_command_history.size()) {
saved_current_line = buffer;
}
if (history_index > 0) {
history_index--;
buffer = g_command_history[history_index];
cursor = buffer.size();
render_input_line(prompt, buffer, cursor);
}
}
} else if (key == 80) {
if (history_index < g_command_history.size()) {
history_index++;
if (history_index == g_command_history.size()) {
buffer = saved_current_line;
} else {
buffer = g_command_history[history_index];
}
cursor = buffer.size();
render_input_line(prompt, buffer, cursor);
}
} else if (key == 75) {
if (cursor > 0) {
cursor--;
render_input_line(prompt, buffer, cursor);
}
} else if (key == 77) {
if (cursor < buffer.size()) {
cursor++;
render_input_line(prompt, buffer, cursor);
}
} else if (key == 71) {
cursor = 0;
render_input_line(prompt, buffer, cursor);
} else if (key == 79) {
cursor = buffer.size();
render_input_line(prompt, buffer, cursor);
} else if (key == 83) {
if (cursor < buffer.size()) {
buffer.erase(cursor, 1);
render_input_line(prompt, buffer, cursor);
}
}
continue;
}
if (ch >= 32) {
buffer.insert(cursor, 1, static_cast<wchar_t>(ch));
cursor++;
render_input_line(prompt, buffer, cursor);
}
}
}
bool resolve_history_recall(const std::wstring& input, std::wstring& resolved) {
resolved = input;
if (input.empty() || input[0] != L'!') {
return true;
}
if (input == L"!!") {
if (g_command_history.empty()) {
std::wcerr << L"rsh: history empty\n";
return false;
}
resolved = g_command_history.back();
return true;
}
if (input.size() > 1 && input[1] == L'-') {
try {
size_t rel = static_cast<size_t>(std::stoul(input.substr(2)));
if (rel == 0 || rel > g_command_history.size()) {
std::wcerr << L"rsh: history event not found\n";
return false;
}
resolved = g_command_history[g_command_history.size() - rel];
return true;
} catch (...) {
std::wcerr << L"rsh: invalid history reference\n";
return false;
}
}
bool numeric = input.size() > 1;
for (size_t i = 1; i < input.size(); ++i) {
if (!std::iswdigit(input[i])) {
numeric = false;
break;
}
}
if (numeric) {
try {
size_t index = static_cast<size_t>(std::stoul(input.substr(1)));
if (index == 0 || index > g_command_history.size()) {
std::wcerr << L"rsh: history event not found\n";
return false;
}
resolved = g_command_history[index - 1];
return true;
} catch (...) {
std::wcerr << L"rsh: invalid history reference\n";
return false;
}
}
std::wstring prefix = input.substr(1);
for (size_t i = g_command_history.size(); i > 0; --i) {
if (starts_with_case_insensitive(g_command_history[i - 1], prefix)) {
resolved = g_command_history[i - 1];
return true;
}
}
std::wcerr << L"rsh: history event not found\n";
return false;
}
void update_background_jobs(bool print_completions) {
for (BackgroundJob& job : g_background_jobs) {
if (job.completed) {
continue;
}
DWORD code = STILL_ACTIVE;
if (!GetExitCodeProcess(job.process_handle, &code)) {
code = 1;
}
if (code != STILL_ACTIVE) {
job.completed = true;
job.exit_code = code;
if (print_completions && !job.completion_reported) {
std::wcout << L"[" << job.id << L"] Done (exit=" << job.exit_code << L") " << job.command << L"\n";
}
job.completion_reported = true;
}
}
}
BackgroundJob* find_background_job(int job_id) {
for (BackgroundJob& job : g_background_jobs) {
if (job.id == job_id) {
return &job;
}
}
return nullptr;
}
bool parse_job_id(const std::wstring& raw, int& job_id) {
if (raw.empty()) {
return false;
}
try {
size_t consumed = 0;
int parsed = std::stoi(raw, &consumed);
if (consumed != raw.size() || parsed <= 0) {
return false;
}
job_id = parsed;
return true;
} catch (...) {
return false;
}
}
void remove_background_job(int job_id) {
for (size_t i = 0; i < g_background_jobs.size(); ++i) {
if (g_background_jobs[i].id == job_id) {
if (g_background_jobs[i].process_handle != nullptr) {
CloseHandle(g_background_jobs[i].process_handle);
g_background_jobs[i].process_handle = nullptr;
}
g_background_jobs.erase(g_background_jobs.begin() + static_cast<long long>(i));
return;
}
}
}
void cleanup_all_background_jobs() {
for (BackgroundJob& job : g_background_jobs) {
if (job.process_handle != nullptr) {
CloseHandle(job.process_handle);
job.process_handle = nullptr;
}
}
g_background_jobs.clear();
}
const std::vector<std::wstring>& current_script_args() {
static const std::vector<std::wstring> empty_args;
if (g_script_context_stack.empty()) {
return empty_args;
}
return g_script_context_stack.back().args;
}
std::wstring current_script_name() {
if (g_script_context_stack.empty()) {
return L"";
}
return g_script_context_stack.back().script_name;
}
std::wstring join_script_args(const std::vector<std::wstring>& args) {
std::wstring joined;
for (size_t i = 0; i < args.size(); ++i) {
joined += args[i];
if (i + 1 < args.size()) {
joined += L" ";
}
}
return joined;
}
std::wstring trim_copy(const std::wstring& value) {
const std::wstring whitespace = L" \t\r\n";
const size_t start = value.find_first_not_of(whitespace);
if (start == std::wstring::npos) {
return L"";
}
const size_t end = value.find_last_not_of(whitespace);
return value.substr(start, end - start + 1);
}
bool ends_with_case_insensitive(const std::wstring& value, const std::wstring& suffix) {
if (suffix.size() > value.size()) {
return false;
}
const size_t offset = value.size() - suffix.size();
for (size_t i = 0; i < suffix.size(); ++i) {
if (std::towlower(value[offset + i]) != std::towlower(suffix[i])) {
return false;
}
}
return true;
}
std::wstring quote_command_argument(const std::wstring& arg) {
if (arg.empty()) {
return L"\"\"";
}
bool needs_quotes = false;
for (wchar_t ch : arg) {
if (std::iswspace(ch) || ch == L'"') {
needs_quotes = true;
break;
}
}
if (!needs_quotes) {
return arg;
}
std::wstring escaped;
escaped.reserve(arg.size() + 2);
escaped.push_back(L'"');
for (wchar_t ch : arg) {
if (ch == L'"') {
escaped += L"\\\"";
} else {
escaped.push_back(ch);
}
}
escaped.push_back(L'"');
return escaped;
}
bool build_script_interpreter_command(const std::vector<std::wstring>& tokens, std::wstring& command_line) {
if (tokens.empty()) {
return false;
}
const std::wstring& script_path = tokens[0];
if (ends_with_case_insensitive(script_path, L".ps1")) {
command_line = L"powershell.exe -NoProfile -ExecutionPolicy Bypass -File ";
command_line += quote_command_argument(script_path);
} else if (ends_with_case_insensitive(script_path, L".sh")) {
command_line = L"bash ";
command_line += quote_command_argument(script_path);
} else {
return false;
}
for (size_t i = 1; i < tokens.size(); ++i) {
command_line += L" ";
command_line += quote_command_argument(tokens[i]);
}
return true;
}
bool is_ksh_script_path(const std::wstring& path) {
return ends_with_case_insensitive(path, L".ksh");
}
bool build_self_script_command(const std::wstring& script_path, const std::vector<std::wstring>& script_args, std::wstring& command_line) {
wchar_t exe_path[MAX_PATH];
DWORD len = GetModuleFileNameW(nullptr, exe_path, MAX_PATH);
if (len == 0 || len >= MAX_PATH) {
return false;
}
command_line = quote_command_argument(exe_path);
command_line += L" ";
command_line += quote_command_argument(script_path);
for (const std::wstring& arg : script_args) {
command_line += L" ";
command_line += quote_command_argument(arg);
}
return true;
}
std::wstring decode_multibyte(const std::string& input, UINT code_page) {
if (input.empty()) {
return L"";
}
int wide_len = MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()), nullptr, 0);
if (wide_len <= 0) {
return L"";
}
std::wstring output(static_cast<size_t>(wide_len), L'\0');
MultiByteToWideChar(code_page, 0, input.data(), static_cast<int>(input.size()), &output[0], wide_len);
return output;
}
std::wstring decode_script_text(const std::vector<char>& bytes) {
if (bytes.empty()) {
return L"";
}
if (bytes.size() >= 3 &&
static_cast<unsigned char>(bytes[0]) == 0xEF &&
static_cast<unsigned char>(bytes[1]) == 0xBB &&
static_cast<unsigned char>(bytes[2]) == 0xBF) {
return decode_multibyte(std::string(bytes.begin() + 3, bytes.end()), CP_UTF8);
}
if (bytes.size() >= 2 &&
static_cast<unsigned char>(bytes[0]) == 0xFF &&
static_cast<unsigned char>(bytes[1]) == 0xFE) {
const size_t byte_count = bytes.size() - 2;
const size_t wchar_count = byte_count / sizeof(wchar_t);
std::wstring text(wchar_count, L'\0');
if (wchar_count > 0) {
std::memcpy(&text[0], bytes.data() + 2, wchar_count * sizeof(wchar_t));
}
return text;
}
if (bytes.size() >= 2 &&
static_cast<unsigned char>(bytes[0]) == 0xFE &&
static_cast<unsigned char>(bytes[1]) == 0xFF) {
std::wstring text;
for (size_t i = 2; i + 1 < bytes.size(); i += 2) {
const unsigned char hi = static_cast<unsigned char>(bytes[i]);
const unsigned char lo = static_cast<unsigned char>(bytes[i + 1]);
wchar_t ch = static_cast<wchar_t>((hi << 8) | lo);
text.push_back(ch);
}
return text;
}
std::wstring utf8 = decode_multibyte(std::string(bytes.begin(), bytes.end()), CP_UTF8);
if (!utf8.empty()) {
return utf8;
}
return decode_multibyte(std::string(bytes.begin(), bytes.end()), CP_ACP);
}
std::vector<std::wstring> split_script_lines(const std::wstring& text) {
std::vector<std::wstring> lines;
std::wstring current;
for (wchar_t ch : text) {
if (ch == L'\r') {
continue;
}
if (ch == L'\n') {
lines.push_back(current);
current.clear();
continue;
}
current.push_back(ch);
}
if (!current.empty()) {
lines.push_back(current);
}
return lines;
}
// Evaluate ksh93 arithmetic expansion: $(( expr ))
double evaluate_math_function(const std::wstring& function_name, const std::vector<double>& args) {
std::wstring name = to_lower_copy(function_name);
if (name == L"abs" && args.size() == 1) return std::fabs(args[0]);
if (name == L"sqrt" && args.size() == 1) return std::sqrt(args[0]);
if (name == L"pow" && args.size() == 2) return std::pow(args[0], args[1]);
if (name == L"min" && args.size() == 2) return (args[0] < args[1]) ? args[0] : args[1];
if (name == L"max" && args.size() == 2) return (args[0] > args[1]) ? args[0] : args[1];
if (name == L"sin" && args.size() == 1) return std::sin(args[0]);
if (name == L"cos" && args.size() == 1) return std::cos(args[0]);
if (name == L"tan" && args.size() == 1) return std::tan(args[0]);
if (name == L"asin" && args.size() == 1) return std::asin(args[0]);
if (name == L"acos" && args.size() == 1) return std::acos(args[0]);
if (name == L"atan" && args.size() == 1) return std::atan(args[0]);
if (name == L"log" && args.size() == 1) return std::log(args[0]);
if (name == L"log10" && args.size() == 1) return std::log10(args[0]);
if (name == L"exp" && args.size() == 1) return std::exp(args[0]);
if (name == L"floor" && args.size() == 1) return std::floor(args[0]);
if (name == L"ceil" && args.size() == 1) return std::ceil(args[0]);
if (name == L"round" && args.size() == 1) return std::round(args[0]);
throw std::runtime_error("unsupported function");
}
class ArithmeticParser {
public:
explicit ArithmeticParser(const std::wstring& expression) : expr(expression), pos(0) {}
double parse() {
double value = parse_expression();
skip_spaces();
if (pos != expr.size()) {
throw std::runtime_error("unexpected trailing characters");
}
return value;
}
private:
const std::wstring& expr;
size_t pos;
void skip_spaces() {
while (pos < expr.size() && std::iswspace(expr[pos])) {
pos++;
}
}
bool consume(wchar_t token) {
skip_spaces();
if (pos < expr.size() && expr[pos] == token) {
pos++;
return true;
}
return false;
}
double parse_expression() {
double value = parse_term();
while (true) {
if (consume(L'+')) {
value += parse_term();
} else if (consume(L'-')) {
value -= parse_term();
} else {
break;
}
}
return value;
}
double parse_term() {
double value = parse_power();
while (true) {
if (consume(L'*')) {
value *= parse_power();
} else if (consume(L'/')) {
double right = parse_power();
if (right == 0.0) {
throw std::runtime_error("division by zero");
}
value /= right;
} else if (consume(L'%')) {
double right = parse_power();
if (right == 0.0) {
throw std::runtime_error("modulo by zero");
}
value = std::fmod(value, right);
} else {
break;
}
}
return value;
}
double parse_power() {
double left = parse_unary();
if (consume(L'^')) {
double right = parse_power();
return std::pow(left, right);
}
return left;
}
double parse_unary() {
if (consume(L'+')) {
return parse_unary();
}
if (consume(L'-')) {
return -parse_unary();
}
return parse_primary();
}
std::wstring parse_identifier() {
skip_spaces();
std::wstring identifier;
while (pos < expr.size() && (std::iswalnum(expr[pos]) || expr[pos] == L'_')) {
identifier.push_back(expr[pos]);
pos++;
}
return identifier;
}
double parse_number() {
skip_spaces();
size_t start = pos;
bool seen_dot = false;
while (pos < expr.size()) {
wchar_t ch = expr[pos];
if (std::iswdigit(ch)) {
pos++;
continue;
}
if (ch == L'.' && !seen_dot) {
seen_dot = true;
pos++;
continue;
}
break;
}
if (start == pos) {
throw std::runtime_error("number expected");
}
return std::stod(expr.substr(start, pos - start));
}
double parse_primary() {
skip_spaces();
if (consume(L'(')) {
double inner = parse_expression();
if (!consume(L')')) {
throw std::runtime_error("missing closing parenthesis");
}
return inner;
}
if (pos < expr.size() && (std::iswalpha(expr[pos]) || expr[pos] == L'_')) {
std::wstring identifier = parse_identifier();
std::wstring lowered = to_lower_copy(identifier);
if (lowered == L"pi") {
return std::acos(-1.0);
}
if (lowered == L"e") {
return std::exp(1.0);
}
if (consume(L'(')) {
std::vector<double> args;
skip_spaces();
if (!consume(L')')) {
while (true) {
args.push_back(parse_expression());
if (consume(L')')) {
break;
}
if (!consume(L',')) {
throw std::runtime_error("comma expected");
}
}
}
return evaluate_math_function(identifier, args);
}
if (ksh_env.variables.find(identifier) != ksh_env.variables.end()) {
return std::stod(ksh_env.variables[identifier]);
}
return 0.0;