-
Notifications
You must be signed in to change notification settings - Fork 3k
/
bytecode.cpp
7691 lines (6890 loc) · 227 KB
/
bytecode.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-2014 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 |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/bytecode.h"
#include <algorithm>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cinttypes>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <libgen.h>
#include <sys/mman.h>
#include <folly/String.h>
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/externals.h"
#include "hphp/runtime/base/tv-comparisons.h"
#include "hphp/runtime/base/tv-conversions.h"
#include "hphp/runtime/base/tv-arith.h"
#include "hphp/runtime/base/apc-stats.h"
#include "hphp/compiler/builtin_symbols.h"
#include "hphp/runtime/vm/event-hook.h"
#include "hphp/runtime/vm/repo.h"
#include "hphp/runtime/vm/repo-global-data.h"
#include "hphp/runtime/base/repo-auth-type-codec.h"
#include "hphp/runtime/vm/func-inline.h"
#include "hphp/runtime/vm/jit/mc-generator.h"
#include "hphp/runtime/vm/jit/translator.h"
#include "hphp/runtime/vm/jit/translator-runtime.h"
#include "hphp/runtime/vm/srckey.h"
#include "hphp/runtime/vm/member-operations.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/runtime/base/code-coverage.h"
#include "hphp/runtime/base/unit-cache.h"
#include "hphp/runtime/base/base-includes.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/base/mixed-array.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/strings.h"
#include "hphp/runtime/base/apc-typed-value.h"
#include "hphp/util/text-util.h"
#include "hphp/util/trace.h"
#include "hphp/util/debug.h"
#include "hphp/runtime/base/stat-cache.h"
#include "hphp/runtime/vm/debug/debug.h"
#include "hphp/runtime/vm/hhbc.h"
#include "hphp/runtime/vm/php-debug.h"
#include "hphp/runtime/vm/debugger-hook.h"
#include "hphp/runtime/vm/runtime.h"
#include "hphp/runtime/base/rds.h"
#include "hphp/runtime/vm/treadmill.h"
#include "hphp/runtime/vm/type-constraint.h"
#include "hphp/runtime/vm/unwind.h"
#include "hphp/runtime/vm/jit/translator-inline.h"
#include "hphp/runtime/vm/native.h"
#include "hphp/runtime/vm/resumable.h"
#include "hphp/runtime/ext/ext_closure.h"
#include "hphp/runtime/ext/ext_generator.h"
#include "hphp/runtime/ext/apc/ext_apc.h"
#include "hphp/runtime/ext/array/ext_array.h"
#include "hphp/runtime/ext/asio/async_function_wait_handle.h"
#include "hphp/runtime/ext/asio/async_generator.h"
#include "hphp/runtime/ext/asio/async_generator_wait_handle.h"
#include "hphp/runtime/ext/asio/static_wait_handle.h"
#include "hphp/runtime/ext/asio/wait_handle.h"
#include "hphp/runtime/ext/asio/waitable_wait_handle.h"
#include "hphp/runtime/ext/hh/ext_hh.h"
#include "hphp/runtime/ext/reflection/ext_reflection.h"
#include "hphp/runtime/ext/std/ext_std_function.h"
#include "hphp/runtime/ext/std/ext_std_math.h"
#include "hphp/runtime/ext/std/ext_std_variable.h"
#include "hphp/runtime/ext/string/ext_string.h"
#include "hphp/runtime/base/stats.h"
#include "hphp/runtime/vm/type-profile.h"
#include "hphp/runtime/server/source-root-info.h"
#include "hphp/runtime/server/rpc-request-handler.h"
#include "hphp/runtime/base/extended-logger.h"
#include "hphp/runtime/base/memory-profile.h"
#include "hphp/runtime/base/memory-manager.h"
#include "hphp/runtime/base/runtime-error.h"
#include "hphp/runtime/base/container-functions.h"
#include "hphp/system/systemlib.h"
#include "hphp/runtime/ext/ext_collections.h"
#include "hphp/runtime/vm/globals-array.h"
namespace HPHP {
// TODO: #1746957, #1756122
// we should skip the call in call_user_func_array, if
// by reference params are passed by value, or if its
// argument is not an array, but currently lots of tests
// depend on actually making the call.
const bool skipCufOnInvalidParams = false;
// RepoAuthoritative has been raptured out of runtime_option.cpp. It needs
// to be closer to other bytecode.cpp data.
bool RuntimeOption::RepoAuthoritative = false;
using std::string;
using jit::mcg;
#if DEBUG
#define OPTBLD_INLINE
#else
#define OPTBLD_INLINE ALWAYS_INLINE
#endif
TRACE_SET_MOD(bcinterp);
// Identifies the set of return helpers that we may set m_savedRip to in an
// ActRec.
static bool isReturnHelper(void* address) {
auto tcAddr = reinterpret_cast<jit::TCA>(address);
auto& u = mcg->tx().uniqueStubs;
return tcAddr == u.retHelper ||
tcAddr == u.genRetHelper ||
tcAddr == u.retInlHelper ||
tcAddr == u.callToExit;
}
ActRec* ActRec::sfp() const {
// Native frame? (used by enterTCHelper)
if (UNLIKELY(((uintptr_t)m_sfp - s_stackLimit) < s_stackSize)) {
return nullptr;
}
return m_sfp;
}
void ActRec::setReturn(ActRec* fp, PC pc, void* retAddr) {
assert(fp->func()->contains(pc));
assert(isReturnHelper(retAddr));
m_sfp = fp;
m_savedRip = reinterpret_cast<uintptr_t>(retAddr);
m_soff = Offset(pc - fp->func()->getEntry());
}
void ActRec::setReturnVMExit() {
assert(isReturnHelper(mcg->tx().uniqueStubs.callToExit));
m_sfp = nullptr;
m_savedRip = reinterpret_cast<uintptr_t>(mcg->tx().uniqueStubs.callToExit);
m_soff = 0;
}
bool
ActRec::skipFrame() const {
return m_func && m_func->isSkipFrame();
}
template <>
Class* arGetContextClassImpl<false>(const ActRec* ar) {
if (ar == nullptr) {
return nullptr;
}
return ar->m_func->cls();
}
template <>
Class* arGetContextClassImpl<true>(const ActRec* ar) {
if (ar == nullptr) {
return nullptr;
}
if (ar->m_func->isPseudoMain() || ar->m_func->isBuiltin()) {
// Pseudomains inherit the context of their caller
auto const context = g_context.getNoCheck();
ar = context->getPrevVMStateUNSAFE(ar);
while (ar != nullptr &&
(ar->m_func->isPseudoMain() || ar->m_func->isBuiltin())) {
ar = context->getPrevVMStateUNSAFE(ar);
}
if (ar == nullptr) {
return nullptr;
}
}
return ar->m_func->cls();
}
void frame_free_locals_no_hook(ActRec* fp) {
frame_free_locals_inl_no_hook<false>(fp, fp->func()->numLocals());
}
const StaticString s_call_user_func("call_user_func");
const StaticString s_call_user_func_array("call_user_func_array");
const StaticString s_stdclass("stdclass");
const StaticString s___call("__call");
const StaticString s___callStatic("__callStatic");
const StaticString s_file("file");
const StaticString s_line("line");
///////////////////////////////////////////////////////////////////////////////
//=============================================================================
// Miscellaneous macros.
#define NEXT() pc++
#define DECODE_JMP(type, var) \
type var __attribute__((__unused__)) = *(type*)pc; \
ONTRACE(2, \
Trace::trace("decode: Immediate %s %" PRIi64"\n", #type, \
(int64_t)var));
#define DECODE(type, var) \
DECODE_JMP(type, var); \
pc += sizeof(type)
#define DECODE_IVA(var) \
int32_t var UNUSED = decodeVariableSizeImm(&pc); \
ONTRACE(2, \
Trace::trace("decode: Immediate int32 %" PRIi64"\n", \
(int64_t)var));
#define DECODE_LITSTR(var) \
StringData* var; \
do { \
DECODE(Id, id); \
var = vmfp()->m_func->unit()->lookupLitstrId(id); \
} while (false)
#define DECODE_LA(var) DECODE_IVA(var)
#define DECODE_IA(var) DECODE_IVA(var)
#define DECODE_OA DECODE
#define DECODE_ITER_LIST(typeList, idList, vecLen) \
DECODE(int32_t, vecLen); \
assert(vecLen > 0); \
Id* typeList = (Id*)pc; \
Id* idList = (Id*)pc + 1; \
pc += 2 * vecLen * sizeof(Id);
#define SYNC() vmpc() = pc
//=============================================================================
// Miscellaneous helpers.
static inline Class* frameStaticClass(ActRec* fp) {
if (fp->hasThis()) {
return fp->getThis()->getVMClass();
} else if (fp->hasClass()) {
return fp->getClass();
} else {
return nullptr;
}
}
static Offset pcOff() {
return vmfp()->m_func->unit()->offsetOf(vmpc());
}
//=============================================================================
// VarEnv.
const StaticString s_GLOBALS("GLOBALS");
VarEnv::VarEnv()
: m_nvTable()
, m_extraArgs(nullptr)
, m_depth(0)
, m_global(true)
{
TRACE(3, "Creating VarEnv %p [global scope]\n", this);
assert(!g_context->m_globalVarEnv);
g_context->m_globalVarEnv = this;
auto globals = new (MM().objMalloc(sizeof(GlobalsArray)))
GlobalsArray(&m_nvTable);
auto globalArray = make_tv<KindOfArray>(globals->asArrayData());
m_nvTable.set(s_GLOBALS.get(), &globalArray);
}
VarEnv::VarEnv(ActRec* fp, ExtraArgs* eArgs)
: m_nvTable(fp)
, m_extraArgs(eArgs)
, m_depth(1)
, m_global(false)
{
TRACE(3, "Creating lazily attached VarEnv %p on stack\n", this);
}
VarEnv::VarEnv(const VarEnv* varEnv, ActRec* fp)
: m_nvTable(varEnv->m_nvTable, fp)
, m_extraArgs(varEnv->m_extraArgs ? varEnv->m_extraArgs->clone(fp) : nullptr)
, m_depth(1)
, m_global(false)
{
assert(varEnv->m_depth == 1);
assert(!varEnv->m_global);
TRACE(3, "Cloning VarEnv %p to %p\n", varEnv, this);
}
VarEnv::~VarEnv() {
TRACE(3, "Destroying VarEnv %p [%s]\n",
this,
isGlobalScope() ? "global scope" : "local scope");
assert(isGlobalScope() == (g_context->m_globalVarEnv == this));
if (isGlobalScope()) {
/*
* When detaching the global scope, we leak any live objects (and
* let the smart allocator clean them up). This is because we're
* not supposed to run destructors for objects that are live at
* the end of a request.
*/
m_nvTable.leak();
}
}
VarEnv* VarEnv::createGlobal() {
return smart_new<VarEnv>();
}
VarEnv* VarEnv::createLocal(ActRec* fp) {
return smart_new<VarEnv>(fp, fp->getExtraArgs());
}
VarEnv* VarEnv::clone(ActRec* fp) const {
return smart_new<VarEnv>(this, fp);
}
void VarEnv::suspend(const ActRec* oldFP, ActRec* newFP) {
m_nvTable.suspend(oldFP, newFP);
}
void VarEnv::enterFP(ActRec* oldFP, ActRec* newFP) {
TRACE(3, "Attaching VarEnv %p [%s] %d fp @%p\n",
this,
isGlobalScope() ? "global scope" : "local scope",
int(newFP->m_func->numNamedLocals()), newFP);
assert(newFP);
if (oldFP == nullptr) {
assert(isGlobalScope() && m_depth == 0);
} else {
assert(m_depth >= 1);
assert(g_context->getPrevVMStateUNSAFE(newFP) == oldFP);
m_nvTable.detach(oldFP);
}
m_nvTable.attach(newFP);
m_depth++;
}
void VarEnv::exitFP(ActRec* fp) {
TRACE(3, "Detaching VarEnv %p [%s] @%p\n",
this,
isGlobalScope() ? "global scope" : "local scope",
fp);
assert(fp);
assert(m_depth > 0);
m_depth--;
m_nvTable.detach(fp);
if (m_depth == 0) {
// don't free global VarEnv
if (!isGlobalScope()) {
smart_delete(this);
}
} else {
m_nvTable.attach(g_context->getPrevVMStateUNSAFE(fp));
}
}
void VarEnv::set(const StringData* name, const TypedValue* tv) {
m_nvTable.set(name, tv);
}
void VarEnv::bind(const StringData* name, TypedValue* tv) {
m_nvTable.bind(name, tv);
}
void VarEnv::setWithRef(const StringData* name, TypedValue* tv) {
if (tv->m_type == KindOfRef) {
bind(name, tv);
} else {
set(name, tv);
}
}
TypedValue* VarEnv::lookup(const StringData* name) {
return m_nvTable.lookup(name);
}
TypedValue* VarEnv::lookupAdd(const StringData* name) {
return m_nvTable.lookupAdd(name);
}
bool VarEnv::unset(const StringData* name) {
m_nvTable.unset(name);
return true;
}
static const StaticString s_closure_var("0Closure");
Array VarEnv::getDefinedVariables() const {
Array ret = Array::Create();
NameValueTable::Iterator iter(&m_nvTable);
for (; iter.valid(); iter.next()) {
auto const sd = iter.curKey();
auto const tv = iter.curVal();
// Closures have an interal 0Closure variable (see emitter.cpp:6539)
if (s_closure_var.equal(sd)) {
continue;
}
if (tvAsCVarRef(tv).isReferenced()) {
ret.setWithRef(StrNR(sd).asString(), tvAsCVarRef(tv));
} else {
ret.add(StrNR(sd).asString(), tvAsCVarRef(tv));
}
}
// ksort the array, result is independent of the hashtable implementation.
ArrayData* sorted = ret.get()->escalateForSort();
sorted->incRefCount();
sorted->ksort(0, true);
if (sorted != ret.get()) {
ret = sorted;
}
sorted->decRefCount();
return ret;
}
TypedValue* VarEnv::getExtraArg(unsigned argInd) const {
return m_extraArgs->getExtraArg(argInd);
}
//=============================================================================
ExtraArgs::ExtraArgs() {}
ExtraArgs::~ExtraArgs() {}
void* ExtraArgs::allocMem(unsigned nargs) {
assert(nargs > 0);
return smart_malloc(sizeof(TypedValue) * nargs + sizeof(ExtraArgs));
}
ExtraArgs* ExtraArgs::allocateCopy(TypedValue* args, unsigned nargs) {
void* mem = allocMem(nargs);
ExtraArgs* ea = new (mem) ExtraArgs();
/*
* The stack grows downward, so the args in memory are "backward"; i.e. the
* leftmost (in PHP) extra arg is highest in memory.
*/
std::reverse_copy(args, args + nargs, &ea->m_extraArgs[0]);
return ea;
}
ExtraArgs* ExtraArgs::allocateUninit(unsigned nargs) {
void* mem = ExtraArgs::allocMem(nargs);
return new (mem) ExtraArgs();
}
void ExtraArgs::deallocate(ExtraArgs* ea, unsigned nargs) {
assert(nargs > 0);
for (unsigned i = 0; i < nargs; ++i) {
tvRefcountedDecRef(ea->m_extraArgs + i);
}
ea->~ExtraArgs();
smart_free(ea);
}
void ExtraArgs::deallocate(ActRec* ar) {
const int numExtra = ar->numArgs() - ar->m_func->numNonVariadicParams();
deallocate(ar->getExtraArgs(), numExtra);
}
ExtraArgs* ExtraArgs::clone(ActRec* ar) const {
const int numExtra = ar->numArgs() - ar->m_func->numParams();
auto ret = allocateUninit(numExtra);
for (int i = 0; i < numExtra; ++i) {
tvDupFlattenVars(&m_extraArgs[i], &ret->m_extraArgs[i]);
}
return ret;
}
TypedValue* ExtraArgs::getExtraArg(unsigned argInd) const {
return const_cast<TypedValue*>(&m_extraArgs[argInd]);
}
//=============================================================================
// Stack.
// Store actual stack elements array in a thread-local in order to amortize the
// cost of allocation.
class StackElms {
public:
StackElms() : m_elms(nullptr) {}
~StackElms() {
flush();
}
TypedValue* elms() {
if (m_elms == nullptr) {
// RuntimeOption::EvalVMStackElms-sized and -aligned.
size_t algnSz = RuntimeOption::EvalVMStackElms * sizeof(TypedValue);
if (posix_memalign((void**)&m_elms, algnSz, algnSz) != 0) {
throw std::runtime_error(
std::string("VM stack initialization failed: ") +
folly::errnoStr(errno).c_str());
}
madvise(m_elms, algnSz, MADV_DONTNEED);
numa_bind_to(m_elms, algnSz, s_numaNode);
}
return m_elms;
}
void flush() {
if (m_elms != nullptr) {
free(m_elms);
m_elms = nullptr;
}
}
private:
TypedValue* m_elms;
};
IMPLEMENT_THREAD_LOCAL(StackElms, t_se);
const int Stack::sSurprisePageSize = sysconf(_SC_PAGESIZE);
// We reserve the bottom page of each stack for use as the surprise
// page, so the minimum useful stack size is the next power of two.
const uint Stack::sMinStackElms = 2 * sSurprisePageSize / sizeof(TypedValue);
void Stack::ValidateStackSize() {
if (RuntimeOption::EvalVMStackElms < sMinStackElms) {
throw std::runtime_error(str(
boost::format("VM stack size of 0x%llx is below the minimum of 0x%x")
% RuntimeOption::EvalVMStackElms
% sMinStackElms));
}
if (!folly::isPowTwo(RuntimeOption::EvalVMStackElms)) {
throw std::runtime_error(str(
boost::format("VM stack size of 0x%llx is not a power of 2")
% RuntimeOption::EvalVMStackElms));
}
}
Stack::Stack()
: m_elms(nullptr), m_top(nullptr), m_base(nullptr) {
}
Stack::~Stack() {
requestExit();
}
void
Stack::requestInit() {
m_elms = t_se->elms();
// Burn one element of the stack, to satisfy the constraint that
// valid m_top values always have the same high-order (>
// log(RuntimeOption::EvalVMStackElms)) bits.
m_top = m_base = m_elms + RuntimeOption::EvalVMStackElms - 1;
// Because of the surprise page at the bottom of the stack we lose an
// additional 256 elements which must be taken into account when checking for
// overflow.
UNUSED size_t maxelms =
RuntimeOption::EvalVMStackElms - sSurprisePageSize / sizeof(TypedValue);
assert(!wouldOverflow(maxelms - 1));
assert(wouldOverflow(maxelms));
}
void
Stack::requestExit() {
m_elms = nullptr;
}
void flush_evaluation_stack() {
if (vmStack().isAllocated()) {
// For RPCRequestHandler threads, the ExecutionContext can stay
// alive across requests, but its always ok to kill it between
// requests, so do so now
RPCRequestHandler::cleanupState();
}
if (!g_context.isNull()) {
/*
* It is possible to create a new thread, but then not use it
* because another thread became available and stole the job.
* If that thread becomes idle, it will have a g_context, and
* some smart allocated memory
*/
hphp_memory_cleanup();
}
MM().flush();
if (!t_se.isNull()) {
t_se->flush();
}
RDS::flush();
always_assert(MM().empty());
}
static std::string toStringElm(const TypedValue* tv) {
std::ostringstream os;
if (tv->m_type < kMinDataType || tv->m_type > kMaxDataType) {
os << " ??? type " << tv->m_type << "\n";
return os.str();
}
if (IS_REFCOUNTED_TYPE(tv->m_type) && tv->m_data.parr->getCount() <= 0 &&
!tv->m_data.parr->isStatic()) {
// OK in the invoking frame when running a destructor.
os << " ??? inner_count " << tv->m_data.parr->getCount() << " ";
return os.str();
}
auto print_count = [&] {
if (tv->m_data.parr->isStatic()) {
os << ":c(static)";
} else {
os << ":c(" << tv->m_data.parr->getCount() << ")";
}
};
switch (tv->m_type) {
case KindOfRef:
os << "V:(";
os << "@" << tv->m_data.pref;
os << toStringElm(tv->m_data.pref->tv());
os << ")";
return os.str();
case KindOfClass:
os << "A:";
break;
default:
os << "C:";
break;
}
do {
switch (tv->m_type) {
case KindOfUninit:
os << "Uninit";
continue;
case KindOfNull:
os << "Null";
continue;
case KindOfBoolean:
os << (tv->m_data.num ? "True" : "False");
continue;
case KindOfInt64:
os << "0x" << std::hex << tv->m_data.num << std::dec;
continue;
case KindOfDouble:
os << tv->m_data.dbl;
continue;
case KindOfStaticString:
case KindOfString:
{
int len = tv->m_data.pstr->size();
bool truncated = false;
if (len > 128) {
len = 128;
truncated = true;
}
os << tv->m_data.pstr;
print_count();
os << ":\""
<< escapeStringForCPP(tv->m_data.pstr->data(), len)
<< "\"" << (truncated ? "..." : "");
}
continue;
case KindOfArray:
assert(check_refcount_nz(tv->m_data.parr->getCount()));
os << tv->m_data.parr;
print_count();
os << ":Array";
continue;
case KindOfObject:
assert(check_refcount_nz(tv->m_data.pobj->getCount()));
os << tv->m_data.pobj;
print_count();
os << ":Object("
<< tv->m_data.pobj->getClassName().get()->data()
<< ")";
continue;
case KindOfResource:
assert(check_refcount_nz(tv->m_data.pres->getCount()));
os << tv->m_data.pres;
print_count();
os << ":Resource("
<< const_cast<ResourceData*>(tv->m_data.pres)
->o_getClassName().get()->data()
<< ")";
continue;
case KindOfRef:
break;
case KindOfClass:
os << tv->m_data.pcls
<< ":" << tv->m_data.pcls->name()->data();
continue;
}
not_reached();
} while (0);
return os.str();
}
static std::string toStringIter(const Iter* it, bool itRef) {
if (itRef) return "I:MutableArray";
// TODO(#2458166): it might be a CufIter, but we're just lucky that
// the bit pattern for the CufIter is going to have a 0 in
// getIterType for now.
switch (it->arr().getIterType()) {
case ArrayIter::TypeUndefined:
return "I:Undefined";
case ArrayIter::TypeArray:
return "I:Array";
case ArrayIter::TypeIterator:
return "I:Iterator";
}
assert(false);
return "I:?";
}
/*
* Return true if Offset o is inside the protected region of a fault
* funclet for iterId, otherwise false. itRef will be set to true if
* the iterator was initialized with MIterInit*, false if the iterator
* was initialized with IterInit*.
*/
static bool checkIterScope(const Func* f, Offset o, Id iterId, bool& itRef) {
assert(o >= f->base() && o < f->past());
for (auto const& eh : f->ehtab()) {
if (eh.m_type == EHEnt::Type::Fault &&
eh.m_base <= o && o < eh.m_past &&
eh.m_iterId == iterId) {
itRef = eh.m_itRef;
return true;
}
}
return false;
}
static void toStringFrame(std::ostream& os, const ActRec* fp,
int offset, const TypedValue* ftop,
const string& prefix, bool isTop = true) {
assert(fp);
// Use depth-first recursion to output the most deeply nested stack frame
// first.
{
Offset prevPc = 0;
TypedValue* prevStackTop = nullptr;
ActRec* prevFp = g_context->getPrevVMStateUNSAFE(fp, &prevPc, &prevStackTop);
if (prevFp != nullptr) {
toStringFrame(os, prevFp, prevPc, prevStackTop, prefix, false);
}
}
os << prefix;
const Func* func = fp->m_func;
assert(func);
func->validate();
string funcName(func->fullName()->data());
os << "{func:" << funcName
<< ",soff:" << fp->m_soff
<< ",this:0x" << std::hex << (fp->hasThis() ? fp->getThis() : nullptr)
<< std::dec << "}";
TypedValue* tv = (TypedValue*)fp;
tv--;
if (func->numLocals() > 0) {
// Don't print locals for parent frames on a Ret(C|V) since some of them
// may already be destructed.
if (isRet(func->unit()->getOpcode(offset)) && !isTop) {
os << "<locals destroyed>";
} else {
os << "<";
int n = func->numLocals();
for (int i = 0; i < n; i++, tv--) {
if (i > 0) {
os << " ";
}
os << toStringElm(tv);
}
os << ">";
}
}
assert(!func->methInfo() || func->numIterators() == 0);
if (func->numIterators() > 0) {
os << "|";
Iter* it = &((Iter*)&tv[1])[-1];
for (int i = 0; i < func->numIterators(); i++, it--) {
if (i > 0) {
os << " ";
}
bool itRef;
if (checkIterScope(func, offset, i, itRef)) {
os << toStringIter(it, itRef);
} else {
os << "I:Undefined";
}
}
os << "|";
}
std::vector<std::string> stackElems;
visitStackElems(
fp, ftop, offset,
[&](const ActRec* ar) {
stackElems.push_back(
folly::format("{{func:{}}}", ar->m_func->fullName()->data()).str()
);
},
[&](const TypedValue* tv) {
stackElems.push_back(toStringElm(tv));
}
);
std::reverse(stackElems.begin(), stackElems.end());
os << ' ' << folly::join(' ', stackElems);
os << '\n';
}
string Stack::toString(const ActRec* fp, int offset,
const string prefix/* = "" */) const {
// The only way to figure out which stack elements are activation records is
// to follow the frame chain. However, the goal for each stack frame is to
// print stack fragments from deepest to shallowest -- a then b in the
// following example:
//
// {func:foo,soff:51}<C:8> {func:bar} C:8 C:1 {func:biz} C:0
// aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb
//
// Use depth-first recursion to get the output order correct.
std::ostringstream os;
auto unit = fp->unit();
auto func = fp->func();
os << prefix << "=== Stack at "
<< unit->filepath()->data() << ":"
<< unit->getLineNumber(unit->offsetOf(vmpc()))
<< " func " << func->fullName()->data() << " ===\n";
toStringFrame(os, fp, offset, m_top, prefix);
return os.str();
}
bool Stack::wouldOverflow(int numCells) const {
// The funny approach here is to validate the translator's assembly
// technique. We've aligned and sized the stack so that the high order
// bits of valid cells are all the same. In the translator, numCells
// can be hardcoded, and m_top is wired into a register,
// so the expression requires no loads.
intptr_t truncatedTop = intptr_t(m_top) / sizeof(TypedValue);
truncatedTop &= RuntimeOption::EvalVMStackElms - 1;
intptr_t diff = truncatedTop - numCells -
sSurprisePageSize / sizeof(TypedValue);
return diff < 0;
}
TypedValue* Stack::frameStackBase(const ActRec* fp) {
assert(!fp->resumed());
return (TypedValue*)fp - fp->func()->numSlotsInFrame();
}
TypedValue* Stack::resumableStackBase(const ActRec* fp) {
assert(fp->resumed());
auto const sfp = fp->sfp();
if (sfp) {
// The non-reentrant case occurs when a non-async or async generator is
// resumed via ContEnter or ContRaise opcode. These opcodes leave a single
// value on the stack that becomes part of the generator's stack. So we
// find the caller's FP, compensate for its locals and iterators, and then
// we've found the base of the generator's stack.
assert(fp->func()->isGenerator());
return (TypedValue*)sfp - sfp->func()->numSlotsInFrame();
} else {
// The reentrant case occurs when asio scheduler resumes an async function
// or async generator. We simply use the top of stack of the previous VM
// frame (since the ActRec, locals, and iters for this frame do not reside
// on the VM stack).
assert(fp->func()->isAsync());
return g_context.getNoCheck()->m_nestedVMs.back().sp;
}
}
//=============================================================================
// ExecutionContext.
using namespace HPHP;
ActRec* ExecutionContext::getOuterVMFrame(const ActRec* ar) {
ActRec* sfp = ar->sfp();
if (LIKELY(sfp != nullptr)) return sfp;
return LIKELY(!m_nestedVMs.empty()) ? m_nestedVMs.back().fp : nullptr;
}
Cell ExecutionContext::lookupClsCns(const NamedEntity* ne,
const StringData* cls,
const StringData* cns) {
Class* class_ = Unit::loadClass(ne, cls);
if (class_ == nullptr) {
raise_error(Strings::UNKNOWN_CLASS, cls->data());
}
Cell clsCns = class_->clsCnsGet(cns);
if (clsCns.m_type == KindOfUninit) {
raise_error("Couldn't find constant %s::%s",
cls->data(), cns->data());
}
return clsCns;
}
Cell ExecutionContext::lookupClsCns(const StringData* cls,
const StringData* cns) {
return lookupClsCns(NamedEntity::get(cls), cls, cns);
}
// Look up the method specified by methodName from the class specified by cls
// and enforce accessibility. Accessibility checks depend on the relationship
// between the class that first declared the method (baseClass) and the context
// class (ctx).
//
// If there are multiple accessible methods with the specified name declared in
// cls and ancestors of cls, the method from the most derived class will be
// returned, except if we are doing an ObjMethod call ("$obj->foo()") and there
// is an accessible private method, in which case the accessible private method
// will be returned.
//
// Accessibility rules:
//
// | baseClass/ctx relationship | public | protected | private |
// +----------------------------+--------+-----------+---------+
// | anon/unrelated | yes | no | no |
// | baseClass == ctx | yes | yes | yes |
// | baseClass derived from ctx | yes | yes | no |
// | ctx derived from baseClass | yes | yes | no |
// +----------------------------+--------+-----------+---------+
const StaticString s_construct("__construct");
const Func* ExecutionContext::lookupMethodCtx(const Class* cls,
const StringData* methodName,
const Class* ctx,
CallType callType,
bool raise /* = false */) {
const Func* method;
if (callType == CallType::CtorMethod) {
assert(methodName == nullptr);
method = cls->getCtor();
} else {
assert(callType == CallType::ObjMethod || callType == CallType::ClsMethod);
assert(methodName != nullptr);
method = cls->lookupMethod(methodName);
while (!method) {
if (UNLIKELY(methodName->isame(s_construct.get()))) {
// We were looking up __construct and failed to find it. Fall back
// to old-style constructor: same as class name.
method = cls->getCtor();
if (!Func::isSpecial(method->name())) break;
}
// We didn't find any methods with the specified name in cls's method
// table, handle the failure as appropriate.
if (raise) {
raise_error("Call to undefined method %s::%s()",
cls->name()->data(),
methodName->data());
}
return nullptr;
}
}
assert(method);
bool accessible = true;
// If we found a protected or private method, we need to do some
// accessibility checks.
if ((method->attrs() & (AttrProtected|AttrPrivate)) &&
!g_context->debuggerSettings.bypassCheck) {
Class* baseClass = method->baseCls();
assert(baseClass);
// If ctx is the class that first declared this method, then we know we
// have the right method and we can stop here.
if (ctx == baseClass) {
return method;
}