/
program-functions.cpp
3092 lines (2804 loc) · 100 KB
/
program-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
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
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/apc-typed-value.h"
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/backtrace.h"
#include "hphp/runtime/base/bespoke-array.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/code-coverage.h"
#include "hphp/runtime/base/config.h"
#include "hphp/runtime/base/exceptions.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/extended-logger.h"
#include "hphp/runtime/base/file-util.h"
#include "hphp/runtime/base/file-util-defs.h"
#include "hphp/runtime/base/hhprof.h"
#include "hphp/runtime/base/implicit-context.h"
#include "hphp/runtime/base/ini-setting.h"
#include "hphp/runtime/base/init-fini-node.h"
#include "hphp/runtime/base/member-reflection.h"
#include "hphp/runtime/base/memory-manager.h"
#include "hphp/runtime/base/perf-mem-event.h"
#include "hphp/runtime/base/php-globals.h"
#include "hphp/runtime/base/plain-file.h"
#include "hphp/runtime/base/runtime-error.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/base/stat-cache.h"
#include "hphp/runtime/base/stream-wrapper-registry.h"
#include "hphp/runtime/base/surprise-flags.h"
#include "hphp/runtime/base/thread-safe-setlocale.h"
#include "hphp/runtime/base/tracing.h"
#include "hphp/runtime/base/unit-cache.h"
#include "hphp/runtime/base/variable-serializer.h"
#include "hphp/runtime/debugger/debugger.h"
#include "hphp/runtime/debugger/debugger_client.h"
#include "hphp/runtime/debugger/debugger_hook_handler.h"
#include "hphp/runtime/ext/apc/ext_apc.h"
#include "hphp/runtime/ext/extension-registry.h"
#include "hphp/runtime/ext/json/ext_json.h"
#include "hphp/runtime/ext/server/ext_server.h"
#include "hphp/runtime/ext/std/ext_std_file.h"
#include "hphp/runtime/ext/std/ext_std_function.h"
#include "hphp/runtime/ext/std/ext_std_variable.h"
#include "hphp/runtime/ext/strobelight/ext_strobelight.h"
#include "hphp/runtime/ext/xenon/ext_xenon.h"
#include "hphp/runtime/ext/xhprof/ext_xhprof.h"
#include "hphp/runtime/server/admin-request-handler.h"
#include "hphp/runtime/server/cli-server.h"
#include "hphp/runtime/server/http-request-handler.h"
#include "hphp/runtime/server/http-server.h"
#include "hphp/runtime/server/log-writer.h"
#include "hphp/runtime/server/pagelet-server.h"
#include "hphp/runtime/server/replay-transport.h"
#include "hphp/runtime/server/rpc-request-handler.h"
#include "hphp/runtime/server/server-note.h"
#include "hphp/runtime/server/server-stats.h"
#include "hphp/runtime/server/warmup-request-handler.h"
#include "hphp/runtime/server/xbox-server.h"
#include "hphp/runtime/vm/builtin-symbol-map.h"
#include "hphp/runtime/vm/debug/debug.h"
#include "hphp/runtime/vm/jit/code-cache.h"
#include "hphp/runtime/vm/jit/mcgen-translate.h"
#include "hphp/runtime/vm/jit/mcgen.h"
#include "hphp/runtime/vm/jit/prof-data-serialize.h"
#include "hphp/runtime/vm/jit/prof-data.h"
#include "hphp/runtime/vm/jit/tc.h"
#include "hphp/runtime/vm/jit/translator.h"
#include "hphp/runtime/vm/repo-file.h"
#include "hphp/runtime/vm/repo-global-data.h"
#include "hphp/runtime/vm/runtime-compiler.h"
#include "hphp/runtime/vm/treadmill.h"
#include "hphp/runtime/vm/unit-parser.h"
#include "hphp/util/alloc.h"
#include "hphp/util/arch.h"
#include "hphp/util/boot-stats.h"
#include "hphp/util/build-info.h"
#include "hphp/util/capability.h"
#include "hphp/util/compatibility.h"
#include "hphp/util/embedded-data.h"
#include "hphp/util/exception.h"
#include "hphp/util/hardware-counter.h"
#include "hphp/util/kernel-version.h"
#ifndef _MSC_VER
#include "hphp/util/light-process.h"
#endif
#include "hphp/util/managed-arena.h"
#include "hphp/util/maphuge.h"
#include "hphp/util/perf-event.h"
#include "hphp/util/process-exec.h"
#include "hphp/util/process.h"
#include "hphp/util/rds-local.h"
#include "hphp/util/service-data.h"
#include "hphp/util/shm-counter.h"
#include "hphp/util/stack-trace.h"
#include "hphp/util/sync-signal.h"
#include "hphp/util/timer.h"
#include "hphp/util/type-scan.h"
#include "hphp/zend/zend-math.h"
#include "hphp/zend/zend-string.h"
#include "hphp/zend/zend-strtod.h"
#include <folly/CPortability.h>
#include <folly/Portability.h>
#include <folly/Random.h>
#include <folly/Range.h>
#include <folly/Singleton.h>
#include <folly/portability/Fcntl.h>
#include <folly/portability/Libgen.h>
#include <folly/portability/Stdlib.h>
#include <folly/portability/Unistd.h>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/variables_map.hpp>
#ifndef FACEBOOK
// Needed on libevent2
#include <event2/thread.h>
#endif
#include <oniguruma.h>
// Oniguruma defines UChar to unsigned char, but ICU4C defines it to signed
// 16-bit int. This is supposed to be resolved by ONIG_ESCAPE_UCHAR_COLLISION,
// however this isn't fully supported in 6.8.0 or 6.8.1.
//
// As of 2018-03-21, not in any release; hopefully will be in 6.8.2 - it's
// resolved by this commit:
//
// https://github.com/kkos/oniguruma/commit/e79406479b6be4a56e40ede6c1a87b51fba073a2
#undef UChar
#include <signal.h>
#include <libxml/parser.h>
#include <chrono>
#include <exception>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <map>
#include <memory>
#include <string>
#include <vector>
#ifdef _MSC_VER
#include <windows.h>
#include <winuser.h>
#endif
using namespace boost::program_options;
using std::cout;
constexpr auto MAX_INPUT_NESTING_LEVEL = 64;
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// Forward declarations.
/*
* XXX: VM process initialization is handled through a function
* pointer so libhphp_runtime.a can be linked into programs that don't
* actually initialize the VM.
*/
void (*g_vmProcessInit)();
std::string get_and_check_systemlib();
void timezone_init();
void pcre_init();
void pcre_reinit();
///////////////////////////////////////////////////////////////////////////////
// helpers
struct ProgramOptions {
std::string mode;
std::vector<std::string> config;
std::vector<std::string> confStrings;
std::vector<std::string> iniStrings;
int port;
int portfd;
int sslportfd;
int admin_port;
std::string user;
std::string file;
std::string lint;
bool isTempFile;
int count;
bool noSafeAccessCheck;
std::vector<std::string> args;
std::string buildId;
std::string instanceId;
int xhprofFlags;
std::string show;
std::string parse;
int vsDebugPort;
std::string vsDebugDomainSocket;
bool vsDebugNoWait;
Eval::DebuggerClientOptions debugger_options;
};
struct StartTime {
StartTime() : startTime(time(nullptr)) {}
time_t startTime;
};
static bool registrationComplete = false;
static StartTime s_startTime;
static std::string tempFile;
std::vector<std::string> s_config_files;
std::vector<std::string> s_ini_strings;
time_t start_time() {
return s_startTime.startTime;
}
const StaticString
s_HPHP("HPHP"),
s_HHVM("HHVM"),
s_HHVM_JIT("HHVM_JIT"),
s_HHVM_ARCH("HHVM_ARCH"),
s_REQUEST_START_TIME("REQUEST_START_TIME"),
s_REQUEST_TIME("REQUEST_TIME"),
s_REQUEST_TIME_FLOAT("REQUEST_TIME_FLOAT"),
s_DOCUMENT_ROOT("DOCUMENT_ROOT"),
s_SCRIPT_FILENAME("SCRIPT_FILENAME"),
s_SCRIPT_NAME("SCRIPT_NAME"),
s_PHP_SELF("PHP_SELF"),
s_argc("argc"),
s_argv("argv"),
s_PWD("PWD"),
s_HOSTNAME("HOSTNAME"),
s__SERVER("_SERVER"),
s__ENV("_ENV"),
s_toStringErr("(unable to call toString())");
static RDS_LOCAL(bool, s_sessionInitialized);
static void process_cmd_arguments(int argc, char **argv) {
php_global_set(s_argc, Variant(argc));
VecInit argvArray(argc);
for (int i = 0; i < argc; i++) {
argvArray.append(String(argv[i]));
}
php_global_set(s_argv, argvArray.toArray());
}
static void process_env_variables(
Array& variables,
char** envp,
const std::map<std::string, std::string>& envVariables
) {
for (auto const& kv : envVariables) {
String idx(kv.first);
auto const arrkey = variables.convertKey<IntishCast::Cast>(idx);
String str(kv.second);
variables.set(arrkey, make_tv<KindOfString>(str.get()));
}
for (char **env = envp; env && *env; env++) {
char *p = strchr(*env, '=');
if (p) {
String name(*env, p - *env, CopyString);
register_variable(variables, (char*)name.data(),
String(p + 1, CopyString));
}
}
}
void process_env_variables(Array& variables) {
process_env_variables(variables, environ, RuntimeOption::EnvVariables);
}
// Handle adding a variable to an array, supporting keys that look
// like array expressions (like 'FOO[][key1][k2]').
void register_variable(Array& variables, char *name, const Variant& value,
bool overwrite /* = true */) {
// ignore leading spaces in the variable name
char *var = name;
while (*var && *var == ' ') {
var++;
}
// ensure that we don't have spaces or dots in the variable name
// (not binary safe)
bool is_array = false;
char *ip = nullptr; // index pointer
char *p = var;
for (; *p; p++) {
if (*p == ' ' || *p == '.') {
*p = '_';
} else if (*p == '[') {
is_array = true;
ip = p;
*p = 0;
break;
}
}
int var_len = p - var;
if (var_len == 0) {
// empty variable name, or variable name with a space in it
return;
}
// The array pointer we're currently adding to. If we're doing a
// multi-dimensional set. Note that as we're essentially using this as an
// interior array pointer it's not safe to allow reentry here.
Array* symtable = &variables;
char* index = var;
int index_len = var_len;
if (is_array) {
int nest_level = 0;
while (true) {
if (++nest_level > MAX_INPUT_NESTING_LEVEL) {
Logger::Warning("Input variable nesting level exceeded");
return;
}
ip++;
char *index_s = ip;
int new_idx_len = 0;
if (isspace(*ip)) {
ip++;
}
if (*ip == ']') {
index_s = nullptr;
} else {
ip = strchr(ip, ']');
if (!ip) {
// PHP variables cannot contain '[' in their names,
// so we replace the character with a '_'
*(index_s - 1) = '_';
index_len = 0;
if (index) {
index_len = strlen(index);
}
goto plain_var;
}
*ip = 0;
new_idx_len = strlen(index_s);
}
if (!index) {
symtable->append(make_persistent_array_like_tv(ArrayData::CreateDict()));
auto const key = symtable->get()->getKey(symtable->get()->iter_last());
symtable = &asArrRef(symtable->lval(key));
} else {
String key_str(index, index_len, CopyString);
auto const key =
symtable->convertKey<IntishCast::Cast>(key_str.asTypedValue());
auto const v = symtable->lookup(key);
if (isNullType(v.type()) || !isArrayLikeType(v.type())) {
symtable->set(key, make_persistent_array_like_tv(ArrayData::CreateDict()));
}
symtable = &asArrRef(symtable->lval(key));
}
/* ip pointed to the '[' character, now obtain the key */
index = index_s;
index_len = new_idx_len;
ip++;
if (*ip == '[') {
is_array = true;
*ip = 0;
} else {
goto plain_var;
}
}
} else {
plain_var:
if (!index) {
symtable->append(value);
} else {
String key_str(index, index_len, CopyString);
auto key =
symtable->convertKey<IntishCast::Cast>(key_str.asTypedValue());
if (overwrite || !symtable->exists(key)) {
symtable->set(key, *value.asTypedValue(), true);
}
}
}
}
enum class ContextOfException {
ReqInit = 1,
Invoke,
Handler,
};
static void handle_exception_append_bt(std::string& errorMsg,
const ExtendedException& e) {
Array bt = e.getBacktrace();
if (!bt.empty()) {
errorMsg += ExtendedLogger::StringOfStackTrace(bt);
}
}
void bump_counter_and_rethrow(bool isPsp) {
try {
throw;
} catch (const RequestTimeoutException& e) {
if (isPsp) {
static auto requestTimeoutPSPCounter = ServiceData::createTimeSeries(
"requests_timed_out_psp", {ServiceData::StatsType::COUNT});
requestTimeoutPSPCounter->addValue(1);
ServerStats::Log("request.timed_out.psp", 1);
} else {
static auto requestTimeoutCounter = ServiceData::createTimeSeries(
"requests_timed_out_non_psp", {ServiceData::StatsType::COUNT});
requestTimeoutCounter->addValue(1);
ServerStats::Log("request.timed_out.non_psp", 1);
}
throw;
} catch (const RequestCPUTimeoutException& e) {
if (isPsp) {
static auto requestCPUTimeoutPSPCounter = ServiceData::createTimeSeries(
"requests_cpu_timed_out_psp", {ServiceData::StatsType::COUNT});
requestCPUTimeoutPSPCounter->addValue(1);
ServerStats::Log("request.cpu_timed_out.psp", 1);
} else {
static auto requestCPUTimeoutCounter = ServiceData::createTimeSeries(
"requests_cpu_timed_out_non_psp", {ServiceData::StatsType::COUNT});
requestCPUTimeoutCounter->addValue(1);
ServerStats::Log("request.cpu_timed_out.non_psp", 1);
}
throw;
} catch (const RequestMemoryExceededException& e) {
if (isPsp) {
static auto requestMemoryExceededPSPCounter =
ServiceData::createTimeSeries(
"requests_memory_exceeded_psp", {ServiceData::StatsType::COUNT});
requestMemoryExceededPSPCounter->addValue(1);
ServerStats::Log("request.memory_exceeded.psp", 1);
} else {
static auto requestMemoryExceededCounter = ServiceData::createTimeSeries(
"requests_memory_exceeded_non_psp", {ServiceData::StatsType::COUNT});
requestMemoryExceededCounter->addValue(1);
ServerStats::Log("request.memory_exceeded.non_psp", 1);
}
throw;
} catch (const RequestOOMKilledException& e) {
if (isPsp) {
static auto requestHostOOMPSPCounter = ServiceData::createTimeSeries(
"requests_oom_killed_psp", {ServiceData::StatsType::COUNT});
requestHostOOMPSPCounter->addValue(1);
ServerStats::Log("request.oom_killed.psp", 1);
} else {
static auto requestHostOOMCounter = ServiceData::createTimeSeries(
"requests_oom_killed_non_psp", {ServiceData::StatsType::COUNT});
requestHostOOMCounter->addValue(1);
ServerStats::Log("request.oom_killed.non_psp", 1);
}
if (RuntimeOption::EvalLogKilledRequests && StructuredLog::enabled()) {
StructuredLogEntry entry;
entry.setInt("mem_used", e.m_usedBytes);
entry.setInt("is_psp", static_cast<int>(isPsp));
if (g_context) {
entry.setStr("url", g_context->getRequestUrl());
}
StructuredLog::log("hhvm_oom_killed", entry);
}
throw;
}
}
static void handle_exception_helper(bool& ret,
ExecutionContext* context,
std::string& errorMsg,
ContextOfException where,
bool& error,
bool richErrorMsg) {
// Clear oom/timeout while handling exception and restore them afterwards.
auto& flags = stackLimitAndSurprise();
auto const origFlags = flags.fetch_and(~ResourceFlags) & ResourceFlags;
SCOPE_EXIT {
flags.fetch_or(origFlags);
};
try {
bump_counter_and_rethrow(false /* isPsp */);
} catch (const Eval::DebuggerException& e) {
throw;
} catch (const ExitException& e) {
if (where == ContextOfException::ReqInit) {
ret = false;
} else if (where != ContextOfException::Handler &&
!context->getExitCallback().isNull() &&
is_callable(context->getExitCallback())) {
Array stack = e.getBacktrace();
Array argv = make_vec_array(*rl_exit_code, stack);
vm_call_user_func(context->getExitCallback(), argv);
}
} catch (const PhpFileDoesNotExistException& e) {
ret = false;
if (where != ContextOfException::Handler) {
raise_notice(e.getMessage());
} else {
Logger::Error(e.getMessage());
}
if (richErrorMsg) {
handle_exception_append_bt(errorMsg, e);
}
} catch (const Exception& e) {
bool oldRet = ret;
bool origError = error;
std::string origErrorMsg = errorMsg;
ret = false;
error = true;
errorMsg = "";
if (where == ContextOfException::Handler) {
errorMsg = "Exception handler threw an exception: ";
}
errorMsg += e.what();
if (where == ContextOfException::Invoke) {
bool handlerRet = context->onFatalError(e);
if (handlerRet) {
ret = oldRet;
error = origError;
errorMsg = origErrorMsg;
}
} else {
Logger::Error(errorMsg);
}
if (richErrorMsg) {
auto const ee = dynamic_cast<const ExtendedException*>(&e);
if (ee) {
handle_exception_append_bt(errorMsg, *ee);
}
}
} catch (const Object& e) {
bool oldRet = ret;
bool origError = error;
auto const origErrorMsg = errorMsg;
ret = false;
error = true;
errorMsg = "";
if (where == ContextOfException::Handler) {
errorMsg = "Exception handler threw an object exception: ";
}
try {
errorMsg += throwable_to_string(e.get()).data();
} catch (...) {
errorMsg += s_toStringErr.data();
}
if (where == ContextOfException::Invoke) {
bool handlerRet = context->onUnhandledException(e);
if (handlerRet) {
ret = oldRet;
error = origError;
errorMsg = origErrorMsg;
}
} else {
Logger::Error(errorMsg);
}
} catch (...) {
ret = false;
error = true;
errorMsg = "(non-standard exception \"";
errorMsg += current_exception_name();
errorMsg += "\" was thrown)";
Logger::Error(errorMsg);
}
}
static bool hphp_chdir_file(const std::string& filename) {
bool ret = false;
String s = File::TranslatePath(filename);
char *buf = strndup(s.data(), s.size());
char *dir = dirname(buf);
assertx(dir);
if (dir) {
if (File::IsVirtualDirectory(dir)) {
g_context->setCwd(String(dir, CopyString));
ret = true;
} else {
struct stat sb;
stat(dir, &sb);
if ((sb.st_mode & S_IFMT) == S_IFDIR) {
ret = true;
if (*dir != '.') {
g_context->setCwd(String(dir, CopyString));
}
}
}
}
free(buf);
return ret;
}
static void handle_resource_exceeded_exception() {
try {
throw;
} catch (RequestTimeoutException&) {
RID().triggerTimeout(TimeoutTime);
} catch (RequestCPUTimeoutException&) {
RID().triggerTimeout(TimeoutCPUTime);
} catch (RequestMemoryExceededException&) {
setSurpriseFlag(MemExceededFlag);
RID().setRequestOOMFlag();
} catch (...) {}
}
void handle_destructor_exception(const char* situation) {
std::string errorMsg;
try {
throw;
} catch (ExitException& e) {
// ExitException is fine, no need to show a warning.
RI().setPendingException(e.clone());
return;
} catch (Object &e) {
// For user exceptions, invoke the user exception handler
errorMsg = situation;
errorMsg += " threw an object exception: ";
try {
errorMsg += throwable_to_string(e.get()).data();
} catch (...) {
handle_resource_exceeded_exception();
errorMsg += "(unable to call toString())";
}
} catch (Exception& e) {
RI().setPendingException(e.clone());
errorMsg = situation;
errorMsg += " raised a fatal error: ";
errorMsg += e.what();
} catch (...) {
errorMsg = situation;
errorMsg += " threw an unknown exception";
}
// For fatal errors and unknown exceptions, we raise a warning.
// If there is a user error handler it will be invoked, otherwise
// the default error handler will be invoked.
try {
raise_warning_unsampled(errorMsg);
} catch (...) {
handle_resource_exceeded_exception();
// The user error handler fataled or threw an exception,
// print out the error message directly to the log
Logger::Warning(errorMsg);
}
}
static RDS_LOCAL(rqtrace::Trace, tl_cmdTrace);
void init_command_line_session(int argc, char** argv) {
StackTraceNoHeap::AddExtraLogging("ThreadType", "CLI");
std::string args;
for (int i = 0; i < argc; i++) {
if (i) args += " ";
args += argv[i];
}
StackTraceNoHeap::AddExtraLogging("Arguments", args.c_str());
hphp_session_init(Treadmill::SessionKind::CLISession);
auto const context = g_context.getNoCheck();
context->obSetImplicitFlush(true);
if (RuntimeOption::EvalTraceCommandLineRequest) {
tl_cmdTrace.destroy();
context->setRequestTrace(tl_cmdTrace.getCheck());
}
}
void
init_command_line_globals(
int argc, char** argv, char** envp,
int xhprof,
const std::map<std::string, std::string>& serverVariables,
const std::map<std::string, std::string>& envVariables
) {
auto& variablesOrder = RID().getVariablesOrder();
if (variablesOrder.find('e') != std::string::npos ||
variablesOrder.find('E') != std::string::npos) {
auto envArr = Array::CreateDict();
process_env_variables(envArr, envp, envVariables);
envArr.set(s_HPHP, 1);
envArr.set(s_HHVM, 1);
if (RuntimeOption::EvalJit) {
envArr.set(s_HHVM_JIT, 1);
}
switch (arch()) {
case Arch::X64:
envArr.set(s_HHVM_ARCH, "x64");
break;
case Arch::ARM:
envArr.set(s_HHVM_ARCH, "arm");
break;
}
php_global_set(s__ENV, std::move(envArr));
}
process_cmd_arguments(argc, argv);
if (variablesOrder.find('s') != std::string::npos ||
variablesOrder.find('S') != std::string::npos) {
auto serverArr = Array::CreateDict();
process_env_variables(serverArr, envp, envVariables);
time_t now;
struct timeval tp = {0};
double now_double;
if (!gettimeofday(&tp, nullptr)) {
now_double = (double)(tp.tv_sec + tp.tv_usec / 1000000.00);
now = tp.tv_sec;
} else {
now = time(nullptr);
now_double = (double)now;
}
String file = empty_string();
if (argc > 0) {
file = String::attach(StringData::Make(argv[0], CopyString));
}
serverArr.set(s_REQUEST_START_TIME, now);
serverArr.set(s_REQUEST_TIME, now);
serverArr.set(s_REQUEST_TIME_FLOAT, now_double);
serverArr.set(s_DOCUMENT_ROOT, empty_string_tv());
serverArr.set(s_SCRIPT_FILENAME, file);
serverArr.set(s_SCRIPT_NAME, file);
serverArr.set(s_PHP_SELF, file);
serverArr.set(s_argv, php_global(s_argv));
serverArr.set(s_argc, php_global(s_argc));
serverArr.set(s_PWD, g_context->getCwd());
char hostname[1024];
if (RuntimeOption::ServerExecutionMode() &&
!is_cli_server_mode() &&
!gethostname(hostname, sizeof(hostname))) {
// gethostname may not null-terminate
hostname[sizeof(hostname) - 1] = '\0';
serverArr.set(s_HOSTNAME, String(hostname, CopyString));
}
for (auto const& kv : serverVariables) {
serverArr.set(String{kv.first}, String{kv.second});
}
php_global_set(s__SERVER, std::move(serverArr));
}
if (xhprof) {
HHVM_FN(xhprof_enable)(xhprof, null_array);
}
if (RuntimeOption::RequestTimeoutSeconds) {
RID().setTimeout(RuntimeOption::RequestTimeoutSeconds);
}
if (RuntimeOption::XenonForceAlwaysOn) {
Xenon::getInstance().surpriseAll();
}
// Initialize the debugger
DEBUGGER_ATTACHED_ONLY(phpDebuggerRequestInitHook());
}
void execute_command_line_begin(int argc, char **argv, int xhprof) {
init_command_line_session(argc, argv);
init_command_line_globals(argc, argv, environ, xhprof,
RuntimeOption::ServerVariables,
RuntimeOption::EnvVariables);
}
void execute_command_line_end(int xhprof, bool coverage, const char *program) {
if (xhprof) {
Variant profileData = HHVM_FN(xhprof_disable)();
if (!profileData.isNull()) {
HHVM_FN(var_dump)(Variant::attach(
HHVM_FN(json_encode)(HHVM_FN(xhprof_disable)())
));
}
}
auto& ti = RI();
if (coverage && ti.m_reqInjectionData.getCoverage() &&
!RuntimeOption::CodeCoverageOutputFile.empty()) {
ti.m_coverage.dumpOnExit();
}
g_context->onShutdownPostSend(); // runs more php
Eval::Debugger::InterruptPSPEnded(program);
hphp_context_exit();
hphp_session_exit();
}
#if defined(__APPLE__) || defined(_MSC_VER)
const void* __hot_start = nullptr;
const void* __hot_end = nullptr;
#define AT_END_OF_TEXT
#else
#define AT_END_OF_TEXT __attribute__((__section__(".stub")))
#endif
#define ALIGN_HUGE_PAGE __attribute__((__aligned__(2 * 1024 * 1024)))
#if defined(__has_attribute) && __has_attribute(__no_builtin__)
#define NO_BUILTIN_MEMCPY __attribute__((__no_builtin__("memcpy")))
#else
#define NO_BUILTIN_MEMCPY
#endif
#if defined(__has_attribute) && __has_attribute(__optimize__)
#define OPTIMIZE_2 __attribute__((__optimize__("2")))
#else
#define OPTIMIZE_2
#endif
static void
NEVER_INLINE AT_END_OF_TEXT NO_BUILTIN_MEMCPY OPTIMIZE_2
hugifyMemcpy(uint64_t* dst, uint64_t* src, size_t sz) {
for (size_t cnt = 0; cnt < sz; cnt += sizeof(uint64_t)) {
*dst++ = *src++;
}
}
static void
NEVER_INLINE AT_END_OF_TEXT ALIGN_HUGE_PAGE OPTIMIZE_2
EXTERNALLY_VISIBLE
hugifyText(char* from, char* to) {
#if !FOLLY_SANITIZE && defined MADV_HUGEPAGE
if (from > to || (to - from) < sizeof(uint64_t)) {
// This shouldn't happen if HHVM is behaving correctly (I think),
// but if it does then there is nothing to do and we should bail
// out early because the call to wordcpy() below can't handle
// zero size or negative sizes.
return;
}
size_t sz = to - from;
#ifdef FACEBOOK
if (RuntimeOption::EvalNewTHPHotText) {
auto const hasKernelSupport = [] () -> bool {
KernelVersion version;
if (version.m_major < 5) return false;
if (version.m_major > 5) return true;
if (version.m_minor > 2) return true;
if ((version.m_minor == 2) && (version.m_fbk >= 5)) return true;
return false;
};
if (hasKernelSupport()) {
// The new way doesn't work if the region is locked. Note that this means
// Server.LockCodeMemory won't be applied to the region--there is no
// guarantee that the region would stay in memory, especially if the
// kernel fails to find huge pages for us.
munlock(from, sz);
madvise(from, sz, MADV_HUGEPAGE);
return;
}
}
#endif
void* mem = malloc(sz);
memcpy(mem, from, sz);
// This maps out a portion of our executable
// We need to be very careful about what we do
// until we replace the original code
mmap(from, sz,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
-1, 0);
// This is in glibc, which isn't a problem, except for
// the trampoline code in .plt, which we dealt with
// in the linker script
madvise(from, sz, MADV_HUGEPAGE);
// Don't use memcpy because its probably one of the
// functions thats been mapped out.
// Needs the attribute((optimize("2")) to prevent
// g++ from turning this back into memcpy(!)
hugifyMemcpy((uint64_t*)from, (uint64_t*)mem, sz);
mprotect(from, sz, PROT_READ | PROT_EXEC);
free(mem);
mlock(from, to - from);
Debug::DebugInfo::setPidMapOverlay(from, to);
std::stringstream ss;
ss << "Mapped text section onto huge pages from " <<
std::hex << (uint64_t*)from << " to " << (uint64_t*)to;
Logger::Info(ss.str());
#endif
}
static void pagein_self(void) {
#if defined(USE_JEMALLOC) && (JEMALLOC_VERSION_MAJOR >= 5)
// jemalloc 5 has background threads, which handle purging asynchronously.
bool background_threads = false;
if (mallctlRead<bool, true>("background_thread", &background_threads)) {
background_threads = false;
Logger::Warning("Failed to determine jemalloc background thread state");
}
if (background_threads &&
mallctlWrite<bool, true>("background_thread", false)) {
Logger::Warning("Failed to disable jemalloc background threads");
}
SCOPE_EXIT {
if (background_threads &&
mallctlWrite<bool, true>("background_thread", true)) {
Logger::Warning("Failed to enable jemalloc background threads");
}
};
#endif
// Other than the jemalloc background threads, which should've been stopped by
// now, the only thread allowed here is the current one. Check that and alarm
// people when they accidentally created threads before this point.
int numTry = 0;
while (Process::GetNumThreads() > 1) {
if (numTry < 3) {
numTry++;
usleep(1000);
} else {
break;
}
}
auto nThreads = Process::GetNumThreads();
if (nThreads > 1) {
Logger::Error("%d threads running, cannot hugify text!", nThreads);
fprintf(stderr,
"HHVM is broken: %u threads running in hugifyText()!\n",
nThreads);
if (debug) {
throw std::runtime_error{
"you cannot create threads before pagein_self"
};
}
}
#ifdef __linux__
if (RO::ServerSchedPolicy >= 0 && RO::ServerSchedPolicy <= SCHED_BATCH) {
sched_param param{};
if (RO::ServerSchedPolicy == SCHED_RR) {
param.sched_priority =
std::max(0, sched_get_priority_min(RO::ServerSchedPolicy));
}
auto const ret = sched_setscheduler(0, RO::ServerSchedPolicy, ¶m);
if (ret) {
Logger::Error("failed to adjust scheduling priority: " +
folly::errnoStr(errno));
} else {
Logger::Info("successfully adjusted scheduling priority to %d",
RO::ServerSchedPolicy);
}
}
if (RO::ServerSchedPriority) {
auto const ret = setpriority(PRIO_PROCESS, 0, RO::ServerSchedPriority);
if (ret) {
Logger::FError("failed to setpriority to {}: {}", RO::ServerSchedPriority,
folly::errnoStr(errno));
}
}
#endif
auto mapped_huge = false;
#ifdef __linux__
auto const try_map_huge =
hugePagesSupported() &&
RuntimeOption::EvalMaxHotTextHugePages > 0 &&
(char*)__hot_start != nullptr && (char*)__hot_end != nullptr &&
nThreads <= 1;
SCOPE_EXIT {
if (try_map_huge != mapped_huge) {
Logger::Warning("Failed to hugify the .text section");
}
};
#else
// MacOS doesn't have transparent huge pages. It uses mmap() with
// VM_FLAGS_SUPERPAGE_SIZE_2MB, which we don't do here, so don't bother.
auto constexpr try_map_huge = false;
#endif
char mapname[PATH_MAX];
// pad due to the spaces between the inode number and the mapname
auto const bufsz =
sizeof(unsigned long) * 4 + sizeof(mapname) + sizeof(char) * 11 + 100;
auto buf = static_cast<char*>(malloc(bufsz));
if (auto fp = fopen("/proc/self/maps", "r")) {
while (!feof(fp)) {
if (fgets(buf, bufsz, fp) == 0)
break;
unsigned long begin, end, inode, pgoff;
char perm[5];
char dev[11];