forked from facebook/hhvm
/
unit.cpp
2692 lines (2480 loc) · 84.6 KB
/
unit.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-2013 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 <sys/mman.h>
#include <iostream>
#include <iomanip>
#include "tbb/concurrent_unordered_map.h"
#include <boost/algorithm/string.hpp>
#include "folly/ScopeGuard.h"
#include "hphp/util/lock.h"
#include "hphp/util/util.h"
#include "hphp/util/atomic.h"
#include "hphp/util/read_only_arena.h"
#include "hphp/util/parser/parser.h"
#include "hphp/runtime/ext/ext_variable.h"
#include "hphp/runtime/vm/bytecode.h"
#include "hphp/runtime/vm/repo.h"
#include "hphp/runtime/vm/blob_helper.h"
#include "hphp/runtime/vm/jit/target-cache.h"
#include "hphp/runtime/vm/jit/translator-inline.h"
#include "hphp/runtime/vm/jit/translator-x64.h"
#include "hphp/runtime/vm/verifier/check.h"
#include "hphp/runtime/base/strings.h"
#include "hphp/runtime/vm/func_inline.h"
#include "hphp/runtime/base/file_repository.h"
#include "hphp/runtime/base/stats.h"
#include "hphp/runtime/vm/treadmill.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
using Util::getDataRef;
TRACE_SET_MOD(hhbc);
static const StaticString s_stdin("STDIN");
static const StaticString s_stdout("STDOUT");
static const StaticString s_stderr("STDERR");
static const StaticString s___autoload("__autoload");
ReadOnlyArena& get_readonly_arena() {
static ReadOnlyArena arena(RuntimeOption::EvalHHBCArenaChunkSize);
return arena;
}
// Exports for the admin server.
size_t hhbc_arena_capacity() {
if (!RuntimeOption::RepoAuthoritative) return 0;
return get_readonly_arena().capacity();
}
static const unsigned char*
allocateBCRegion(const unsigned char* bc, size_t bclen) {
if (RuntimeOption::RepoAuthoritative) {
// In RepoAuthoritative, we assume we won't ever deallocate units
// and that this is read-only, mostly cold data. So we throw it
// in a bump-allocator that's mprotect'd to prevent writes.
return static_cast<const unsigned char*>(
get_readonly_arena().allocate(bc, bclen)
);
}
auto mem = static_cast<unsigned char*>(malloc(bclen));
std::copy(bc, bc + bclen, mem);
return mem;
}
Mutex Unit::s_classesMutex;
/*
* We hold onto references to elements of this map. If we use a different
* map, we must use one that doesnt invalidate references to its elements
* (unless they are deleted, which never happens here). Any standard
* associative container will meet this requirement.
*/
static NamedEntityMap *s_namedDataMap;
static NEVER_INLINE
NamedEntity* getNamedEntityHelper(const StringData* str) {
if (!str->isStatic()) {
str = StringData::GetStaticString(str);
}
auto res = s_namedDataMap->insert(str, NamedEntity());
return &res.first->second;
}
size_t Unit::GetNamedEntityTableSize() {
return s_namedDataMap ? s_namedDataMap->size() : 0;
}
NEVER_INLINE
static void initializeNamedDataMap() {
NamedEntityMap::Config config;
config.growthFactor = 1;
s_namedDataMap =
new NamedEntityMap(RuntimeOption::EvalInitialNamedEntityTableSize,
config);
}
NamedEntity* Unit::GetNamedEntity(const StringData* str) {
if (UNLIKELY(!s_namedDataMap)) {
initializeNamedDataMap();
}
NamedEntityMap::iterator it = s_namedDataMap->find(str);
if (LIKELY(it != s_namedDataMap->end())) return &it->second;
return getNamedEntityHelper(str);
}
void NamedEntity::setCachedFunc(Func* f) {
assert(m_cachedFuncOffset);
*(Func**)Transl::TargetCache::handleToPtr(m_cachedFuncOffset) = f;
}
Func* NamedEntity::getCachedFunc() const {
if (LIKELY(m_cachedFuncOffset != 0)) {
return *(Func**)Transl::TargetCache::handleToPtr(m_cachedFuncOffset);
}
return nullptr;
}
void NamedEntity::setCachedClass(Class* f) {
assert(m_cachedClassOffset);
*(Class**)Transl::TargetCache::handleToPtr(m_cachedClassOffset) = f;
}
Class* NamedEntity::getCachedClass() const {
if (LIKELY(m_cachedClassOffset != 0)) {
return *(Class**)Transl::TargetCache::handleToPtr(m_cachedClassOffset);
}
return nullptr;
}
void NamedEntity::setCachedTypedef(const TypedefReq& td) {
assert(m_cachedTypedefOffset);
auto& tdReq = Transl::TargetCache::handleToRef<TypedefReq>(
m_cachedTypedefOffset
);
tdReq = td;
}
const TypedefReq* NamedEntity::getCachedTypedef() const {
if (LIKELY(m_cachedTypedefOffset != 0)) {
auto ret = &Transl::TargetCache::handleToRef<const TypedefReq>(
m_cachedTypedefOffset
);
return ret->name ? ret : nullptr;
}
return nullptr;
}
void NamedEntity::pushClass(Class* cls) {
assert(!cls->m_nextClass);
cls->m_nextClass = m_clsList;
atomic_release_store(&m_clsList, cls); // TODO(#2054448): ARMv8
}
void NamedEntity::removeClass(Class* goner) {
Class** cls = &m_clsList; // TODO(#2054448): ARMv8
while (*cls != goner) {
assert(*cls);
cls = &(*cls)->m_nextClass;
}
*cls = goner->m_nextClass;
}
UnitMergeInfo* UnitMergeInfo::alloc(size_t size) {
UnitMergeInfo* mi = (UnitMergeInfo*)malloc(
sizeof(UnitMergeInfo) + size * sizeof(void*));
mi->m_firstHoistableFunc = 0;
mi->m_firstHoistablePreClass = 0;
mi->m_firstMergeablePreClass = 0;
mi->m_mergeablesSize = size;
return mi;
}
Array Unit::getUserFunctions() {
// Return an array of all defined functions. This method is used
// to support get_defined_functions().
Array a = Array::Create();
if (s_namedDataMap) {
for (NamedEntityMap::const_iterator it = s_namedDataMap->begin();
it != s_namedDataMap->end(); ++it) {
Func* func_ = it->second.getCachedFunc();
if (!func_ || func_->isBuiltin() || func_->isGenerated()) {
continue;
}
a.append(func_->nameRef());
}
}
return a;
}
AllClasses::AllClasses()
: m_next(s_namedDataMap->begin())
, m_end(s_namedDataMap->end())
, m_current(m_next != m_end ? m_next->second.clsList() : nullptr) {
if (!empty()) skip();
}
void AllClasses::skip() {
if (!m_current) {
assert(!empty());
++m_next;
while (!empty()) {
m_current = m_next->second.clsList();
if (m_current) break;
++m_next;
}
}
assert(empty() || front());
}
void AllClasses::next() {
m_current = m_current->m_nextClass;
skip();
}
bool AllClasses::empty() const {
return m_next == m_end;
}
Class* AllClasses::front() const {
assert(!empty());
assert(m_current);
return m_current;
}
Class* AllClasses::popFront() {
Class* cls = front();
next();
return cls;
}
class AllCachedClasses {
NamedEntityMap::iterator m_next, m_end;
void skip() {
Class* cls;
while (!empty()) {
cls = m_next->second.clsList();
if (cls && cls->getCached() &&
(cls->parent() != SystemLib::s_ClosureClass)) break;
++m_next;
}
}
public:
AllCachedClasses()
: m_next(s_namedDataMap->begin())
, m_end(s_namedDataMap->end())
{
skip();
}
bool empty() const {
return m_next == m_end;
}
Class* front() {
assert(!empty());
Class* c = m_next->second.clsList();
assert(c);
c = c->getCached();
assert(c);
return c;
}
Class* popFront() {
Class* c = front();
++m_next;
skip();
return c;
}
};
Array Unit::getClassesInfo() {
// Return an array of all defined class names. This method is used to
// support get_declared_classes().
Array a = Array::Create();
if (s_namedDataMap) {
for (AllCachedClasses ac; !ac.empty();) {
Class* c = ac.popFront();
if (!(c->attrs() & (AttrInterface|AttrTrait))) {
a.append(c->nameRef());
}
}
}
return a;
}
Array Unit::getInterfacesInfo() {
// Return an array of all defined interface names. This method is used to
// support get_declared_interfaces().
Array a = Array::Create();
if (s_namedDataMap) {
for (AllCachedClasses ac; !ac.empty();) {
Class* c = ac.popFront();
if (c->attrs() & AttrInterface) {
a.append(c->nameRef());
}
}
}
return a;
}
Array Unit::getTraitsInfo() {
// Returns an array with all defined trait names. This method is used to
// support get_declared_traits().
Array array = Array::Create();
if (s_namedDataMap) {
for (AllCachedClasses ac; !ac.empty(); ) {
Class* c = ac.popFront();
if (c->attrs() & AttrTrait) {
array.append(c->nameRef());
}
}
}
return array;
}
bool Unit::MetaHandle::findMeta(const Unit* unit, Offset offset) {
if (!unit->m_bc_meta_len) return false;
assert(unit->m_bc_meta);
Offset* index1 = (Offset*)unit->m_bc_meta;
Offset* index2 = index1 + *index1 + 1;
assert(index1[*index1 + 1] == INT_MAX); // sentinel
assert(offset >= 0 && (unsigned)offset < unit->m_bclen);
assert(cur == 0 || index == index1);
if (cur && offset >= index[cur]) {
while (offset >= index[cur+1]) cur++;
} else {
int hi = *index1 + 2;
int lo = 1;
while (hi - lo > 1) {
int mid = (hi + lo) >> 1;
if (offset >= index1[mid]) {
lo = mid;
} else {
hi = mid;
}
}
index = index1;
cur = lo;
}
assert(cur <= (unsigned)*index1);
assert((unsigned)index2[cur] <= unit->m_bc_meta_len);
ptr = unit->m_bc_meta + index2[cur];
return index[cur] == offset;
}
bool Unit::MetaHandle::nextArg(MetaInfo& info) {
assert(index && cur && ptr);
uint8_t* end = (uint8_t*)index + index[*index + cur + 2];
assert(ptr <= end);
if (ptr == end) return false;
info.m_kind = (Unit::MetaInfo::Kind)*ptr++;
info.m_arg = *ptr++;
info.m_data = decodeVariableSizeImm(&ptr);
return true;
}
//=============================================================================
// Unit.
Unit::Unit()
: m_sn(-1), m_bc(nullptr), m_bclen(0),
m_bc_meta(nullptr), m_bc_meta_len(0), m_filepath(nullptr),
m_dirpath(nullptr), m_md5(),
m_mergeInfo(nullptr),
m_cacheOffset(0),
m_repoId(-1),
m_mergeState(UnitMergeStateUnmerged),
m_cacheMask(0),
m_mergeOnly(false),
m_pseudoMainCache(nullptr) {
tvWriteUninit(&m_mainReturn);
}
Unit::~Unit() {
if (!RuntimeOption::RepoAuthoritative) {
if (debug) {
// poison released bytecode
memset(const_cast<unsigned char*>(m_bc), 0xff, m_bclen);
}
free(const_cast<unsigned char*>(m_bc));
free(const_cast<unsigned char*>(m_bc_meta));
}
if (m_mergeInfo) {
// Delete all Func's.
range_foreach(mutableFuncs(), Func::destroy);
}
// ExecutionContext and the TC may retain references to Class'es, so
// it is possible for Class'es to outlive their Unit.
for (int i = m_preClasses.size(); i--; ) {
PreClass* pcls = m_preClasses[i].get();
Class* cls = pcls->namedEntity()->clsList();
while (cls) {
Class* cur = cls;
cls = cls->m_nextClass;
if (cur->preClass() == pcls) {
cur->destroy();
}
}
}
free(m_mergeInfo);
if (m_pseudoMainCache) {
for (auto it = m_pseudoMainCache->begin();
it != m_pseudoMainCache->end(); ++it) {
delete it->second;
}
delete m_pseudoMainCache;
}
}
void* Unit::operator new(size_t sz) {
return Util::low_malloc(sz);
}
void Unit::operator delete(void* p, size_t sz) {
Util::low_free(p);
}
bool Unit::compileTimeFatal(const StringData*& msg, int& line) const {
// A compile-time fatal is encoded as a pseudomain that contains precisely:
//
// String <id>; Fatal;
//
// Decode enough of pseudomain to determine whether it contains a
// compile-time fatal, and if so, extract the error message and line number.
const Opcode* entry = getMain()->getEntry();
const Opcode* pc = entry;
// String <id>; Fatal;
// ^^^^^^
if (toOp(*pc) != OpString) {
return false;
}
pc++;
// String <id>; Fatal;
// ^^^^
Id id = *(Id*)pc;
pc += sizeof(Id);
// String <id>; Fatal;
// ^^^^^
if (toOp(*pc) != OpFatal) {
return false;
}
msg = lookupLitstrId(id);
line = getLineNumber(Offset(pc - entry));
return true;
}
class FrameRestore {
public:
explicit FrameRestore(const PreClass* preClass) {
VMExecutionContext* ec = g_vmContext;
ActRec* fp = ec->getFP();
PC pc = ec->getPC();
if (ec->m_stack.top() &&
(!fp || fp->m_func->unit() != preClass->unit())) {
m_top = ec->m_stack.top();
m_fp = fp;
m_pc = pc;
/*
we can be called from Unit::merge, which hasnt yet setup
the frame (because often it doesnt need to).
Set up a fake frame here, in case of errors.
But note that mergeUnit is called for systemlib etc before the
stack has been setup. So dont do anything if m_stack.top()
is NULL
*/
ActRec &tmp = *ec->m_stack.allocA();
tmp.m_savedRbp = (uint64_t)fp;
tmp.m_savedRip = 0;
tmp.m_func = preClass->unit()->getMain();
tmp.m_soff = !fp ? 0
: fp->m_func->unit()->offsetOf(pc) - fp->m_func->base();
tmp.setThis(nullptr);
tmp.m_varEnv = 0;
tmp.initNumArgs(0);
ec->m_fp = &tmp;
ec->m_pc = preClass->unit()->at(preClass->getOffset());
ec->pushLocalsAndIterators(tmp.m_func);
} else {
m_top = nullptr;
m_fp = nullptr;
m_pc = nullptr;
}
}
~FrameRestore() {
VMExecutionContext* ec = g_vmContext;
if (m_top) {
ec->m_stack.top() = m_top;
ec->m_fp = m_fp;
ec->m_pc = m_pc;
}
}
private:
Cell* m_top;
ActRec* m_fp;
PC m_pc;
};
Class* Unit::defClass(const PreClass* preClass,
bool failIsFatal /* = true */) {
NamedEntity* const nameList = preClass->namedEntity();
Class* top = nameList->clsList();
/*
* Check if there is already a name defined in this request for this
* NamedEntity.
*
* Raise a fatal unless the existing class definition is identical to the
* one this invocation would create.
*/
if (auto current = nameList->getCachedTypedef()) {
FrameRestore fr(preClass);
raise_error("Cannot declare class with the same name (%s) as an "
"existing type", current->name->data());
return nullptr;
}
// If there was already a class declared with DefClass, check if
// it's compatible.
if (Class* cls = nameList->getCachedClass()) {
if (cls->preClass() != preClass) {
if (failIsFatal) {
FrameRestore fr(preClass);
raise_error("Class already declared: %s", preClass->name()->data());
}
return nullptr;
}
return cls;
}
// Get a compatible Class, and add it to the list of defined classes.
Class* parent = nullptr;
for (;;) {
// Search for a compatible extant class. Searching from most to least
// recently created may have better locality than alternative search orders.
// In addition, its the only simple way to make this work lock free...
for (Class* class_ = top; class_ != nullptr; ) {
Class* cur = class_;
class_ = class_->m_nextClass;
if (cur->preClass() != preClass) continue;
Class::Avail avail = cur->avail(parent, failIsFatal /*tryAutoload*/);
if (LIKELY(avail == Class::Avail::True)) {
cur->setCached();
DEBUGGER_ATTACHED_ONLY(phpDebuggerDefClassHook(cur));
return cur;
}
if (avail == Class::Avail::Fail) {
if (failIsFatal) {
FrameRestore fr(preClass);
raise_error("unknown class %s", parent->name()->data());
}
return nullptr;
}
assert(avail == Class::Avail::False);
}
// Create a new class.
if (!parent && preClass->parent()->size() != 0) {
parent = Unit::getClass(preClass->parent(), failIsFatal);
if (parent == nullptr) {
if (failIsFatal) {
FrameRestore fr(preClass);
raise_error("unknown class %s", preClass->parent()->data());
}
return nullptr;
}
}
ClassPtr newClass;
{
FrameRestore fr(preClass);
newClass = Class::newClass(const_cast<PreClass*>(preClass), parent);
}
Lock l(Unit::s_classesMutex);
if (UNLIKELY(top != nameList->clsList())) {
top = nameList->clsList();
continue;
}
if (!nameList->m_cachedClassOffset) {
Transl::TargetCache::allocKnownClass(newClass.get());
}
newClass->m_cachedOffset = nameList->m_cachedClassOffset;
newClass.get()->incAtomicCount();
newClass.get()->setCached();
if (Class::s_instanceBitsInit.load(std::memory_order_acquire)) {
// If the instance bitmap has already been set up, we can just
// initialize our new class's bits and add ourselves to the class
// list normally.
newClass->setInstanceBits();
nameList->pushClass(newClass.get());
} else {
// Otherwise, we have to grab the read lock. If the map has been
// initialized since we checked, initialize the bits normally. If not,
// we must add the new class to the class list before dropping the lock
// to ensure its bits are initialized when the time comes.
ReadLock l(Class::s_instanceBitsLock);
if (Class::s_instanceBitsInit.load(std::memory_order_acquire)) {
newClass->setInstanceBits();
}
nameList->pushClass(newClass.get());
}
DEBUGGER_ATTACHED_ONLY(phpDebuggerDefClassHook(newClass.get()));
return newClass.get();
}
}
bool Unit::aliasClass(Class* original, const StringData* alias) {
auto const aliasNe = Unit::GetNamedEntity(alias);
if (!aliasNe->m_cachedClassOffset) {
Transl::TargetCache::allocKnownClass(aliasNe, false);
}
auto const aliasClass = aliasNe->getCachedClass();
if (aliasClass) {
raise_warning("Cannot redeclare class %s", alias->data());
return false;
}
aliasNe->setCachedClass(original);
return true;
}
void Unit::defTypedef(Id id) {
assert(id < m_typedefs.size());
auto thisType = &m_typedefs[id];
auto nameList = GetNamedEntity(thisType->name);
const StringData* typeName = thisType->value;
/*
* Check if this name already was defined as a type alias, and if so
* make sure it is compatible.
*/
if (auto current = nameList->getCachedTypedef()) {
if (thisType->kind != current->kind ||
thisType->nullable != current->nullable ||
Unit::lookupClass(typeName) != current->klass) {
raise_error("The type %s is already defined to an incompatible type",
thisType->name->data());
}
return;
}
// There might also be a class with this name already.
if (nameList->getCachedClass()) {
raise_error("The name %s is already defined as a class",
thisType->name->data());
return;
}
if (!nameList->m_cachedTypedefOffset) {
nameList->m_cachedTypedefOffset =
Transl::TargetCache::allocTypedef(nameList);
}
/*
* If this typedef is a KindOfObject and the name on the right hand
* side was another typedef, we will bind the name to the other side
* for this request (i.e. resolve that typedef now).
*
* We need to inspect the right hand side and figure out what it was
* first.
*
* If the right hand side was a class, we need to autoload and
* ensure it exists at this point.
*/
if (thisType->kind != KindOfObject) {
nameList->setCachedTypedef(
TypedefReq { thisType->kind,
thisType->nullable,
nullptr,
thisType->name }
);
return;
}
auto targetNameList = GetNamedEntity(typeName);
if (auto targetTd = getTypedefWithAutoload(targetNameList, typeName)) {
nameList->setCachedTypedef(
TypedefReq { targetTd->kind,
thisType->nullable || targetTd->nullable,
targetTd->klass,
thisType->name }
);
return;
}
if (auto klass = Unit::loadClass(typeName)) {
nameList->setCachedTypedef(
TypedefReq { KindOfObject,
thisType->nullable,
klass,
thisType->name }
);
return;
}
raise_error("Unknown type or class %s", typeName->data());
}
void Unit::renameFunc(const StringData* oldName, const StringData* newName) {
// renameFunc() should only be used by VMExecutionContext::createFunction.
// We do a linear scan over all the functions in the unit searching for the
// func with a given name; in practice this is okay because the units created
// by create_function() will always have the function being renamed at the
// beginning
assert(oldName && oldName->isStatic());
assert(newName && newName->isStatic());
for (MutableFuncRange fr(hoistableFuncs()); !fr.empty(); ) {
Func* func = fr.popFront();
const StringData* name = func->name();
assert(name);
if (name->same(oldName)) {
func->rename(newName);
break;
}
}
}
Class* Unit::loadClass(const NamedEntity* ne,
const StringData* name) {
Class* cls;
if (LIKELY((cls = ne->getCachedClass()) != nullptr)) {
return cls;
}
VMRegAnchor _;
String normName = normalizeNS(name);
if (normName) {
name = normName.get();
ne = GetNamedEntity(name);
if ((cls = ne->getCachedClass()) != nullptr) {
return cls;
}
}
AutoloadHandler::s_instance->invokeHandler(
StrNR(const_cast<StringData*>(name)));
return Unit::lookupClass(ne);
}
Class* Unit::loadMissingClass(const NamedEntity* ne,
const StringData *name) {
AutoloadHandler::s_instance->invokeHandler(
StrNR(const_cast<StringData*>(name)));
return Unit::lookupClass(ne);
}
Class* Unit::getClass(const NamedEntity* ne,
const StringData *name, bool tryAutoload) {
Class *cls = lookupClass(ne);
if (UNLIKELY(!cls)) {
String normName = normalizeNS(name);
if (normName) {
name = normName.get();
ne = GetNamedEntity(name);
if ((cls = lookupClass(ne)) != nullptr) {
return cls;
}
}
if (tryAutoload) {
return loadMissingClass(ne, name);
}
}
return cls;
}
bool Unit::classExists(const StringData* name, bool autoload, Attr typeAttrs) {
if(!function_exists(s___autoload)){autoload=false;}
Class* cls = Unit::getClass(name, autoload);
return cls && (cls->attrs() & (AttrInterface | AttrTrait)) == typeAttrs;
}
void Unit::loadFunc(const Func *func) {
assert(!func->isMethod());
const NamedEntity *ne = func->getNamedEntity();
if (UNLIKELY(!ne->m_cachedFuncOffset)) {
Transl::TargetCache::allocFixedFunction(
ne, func->attrs() & AttrPersistent &&
(RuntimeOption::RepoAuthoritative || !SystemLib::s_inited));
}
const_cast<Func*>(func)->m_cachedOffset = ne->m_cachedFuncOffset;
}
static void mergeCns(TypedValue& tv, TypedValue *value,
StringData *name) {
if (LIKELY(tv.m_type == KindOfUninit)) {
tv = *value;
return;
}
raise_warning(Strings::CONSTANT_ALREADY_DEFINED, name->data());
}
static SimpleMutex unitInitLock(false /* reentrant */, RankUnitInit);
void Unit::initialMerge() {
unitInitLock.assertOwnedBySelf();
if (LIKELY(m_mergeState == UnitMergeStateUnmerged)) {
int state = 0;
bool needsCompact = false;
m_mergeState = UnitMergeStateMerging;
bool allFuncsUnique = RuntimeOption::RepoAuthoritative;
for (MutableFuncRange fr(nonMainFuncs()); !fr.empty();) {
Func* f = fr.popFront();
if (allFuncsUnique) {
allFuncsUnique = (f->attrs() & AttrUnique);
}
loadFunc(f);
if (TargetCache::isPersistentHandle(f->m_cachedOffset)) {
needsCompact = true;
}
}
if (allFuncsUnique) state |= UnitMergeStateUniqueFuncs;
if (RuntimeOption::RepoAuthoritative || !SystemLib::s_inited) {
/*
* The mergeables array begins with the hoistable Func*s,
* followed by the (potenitally) hoistable Class*s.
*
* If the Unit is merge only, it then contains enough information
* to simulate executing the pseudomain. Normally, this is just
* the Class*s that might not be hoistable. In RepoAuthoritative
* mode it also includes assignments of the form:
* $GLOBALS[string-literal] = scalar;
* defines of the form:
* define(string-literal, scalar);
* and requires.
*
* These cases are differentiated using the bottom 3 bits
* of the pointer. In the case of a define or a global,
* the pointer will be followed by a TypedValue representing
* the value being defined/assigned.
*/
int ix = m_mergeInfo->m_firstHoistablePreClass;
int end = m_mergeInfo->m_firstMergeablePreClass;
while (ix < end) {
PreClass* pre = (PreClass*)m_mergeInfo->mergeableObj(ix++);
if (pre->attrs() & AttrUnique) {
needsCompact = true;
}
}
if (isMergeOnly()) {
ix = m_mergeInfo->m_firstMergeablePreClass;
end = m_mergeInfo->m_mergeablesSize;
while (ix < end) {
void *obj = m_mergeInfo->mergeableObj(ix);
UnitMergeKind k = UnitMergeKind(uintptr_t(obj) & 7);
switch (k) {
case UnitMergeKindUniqueDefinedClass:
case UnitMergeKindDone:
not_reached();
case UnitMergeKindClass:
if (((PreClass*)obj)->attrs() & AttrUnique) {
needsCompact = true;
}
break;
case UnitMergeKindReqDoc: {
StringData* s = (StringData*)((char*)obj - (int)k);
HPHP::Eval::PhpFile* efile =
g_vmContext->lookupIncludeRoot(s, InclOpDocRoot, nullptr, this);
assert(efile);
Unit* unit = efile->unit();
unit->initialMerge();
m_mergeInfo->mergeableObj(ix) = (void*)((char*)unit + (int)k);
break;
}
case UnitMergeKindPersistentDefine:
needsCompact = true;
case UnitMergeKindDefine: {
StringData* s = (StringData*)((char*)obj - (int)k);
auto* v = (TypedValueAux*) m_mergeInfo->mergeableData(ix + 1);
ix += sizeof(*v) / sizeof(void*);
v->cacheHandle() = StringData::DefCnsHandle(
s, k == UnitMergeKindPersistentDefine);
if (k == UnitMergeKindPersistentDefine) {
mergeCns(TargetCache::handleToRef<TypedValue>(v->cacheHandle()),
v, s);
}
break;
}
case UnitMergeKindGlobal: {
StringData* s = (StringData*)((char*)obj - (int)k);
auto* v = (TypedValueAux*) m_mergeInfo->mergeableData(ix + 1);
ix += sizeof(*v) / sizeof(void*);
v->cacheHandle() = TargetCache::GlobalCache::alloc(s);
break;
}
}
ix++;
}
}
if (needsCompact) state |= UnitMergeStateNeedsCompact;
}
m_mergeState = UnitMergeStateMerged | state;
}
}
TypedValue* Unit::lookupCns(const StringData* cnsName) {
TargetCache::CacheHandle handle = StringData::GetCnsHandle(cnsName);
if (LIKELY(handle != 0)) {
TypedValue& tv = TargetCache::handleToRef<TypedValue>(handle);
if (LIKELY(tv.m_type != KindOfUninit)) return &tv;
if (UNLIKELY(tv.m_data.pref != nullptr)) {
ClassInfo::ConstantInfo* ci =
(ClassInfo::ConstantInfo*)(void*)tv.m_data.pref;
return const_cast<Variant&>(ci->getDeferredValue()).asTypedValue();
}
}
if (UNLIKELY(TargetCache::s_constants != nullptr)) {
return TargetCache::s_constants->HphpArray::nvGet(cnsName);
}
return nullptr;
}
TypedValue* Unit::lookupPersistentCns(const StringData* cnsName) {
TargetCache::CacheHandle handle = StringData::GetCnsHandle(cnsName);
if (!TargetCache::isPersistentHandle(handle)) return nullptr;
return &TargetCache::handleToRef<TypedValue>(handle);
}
TypedValue* Unit::loadCns(const StringData* cnsName) {
TypedValue* tv = lookupCns(cnsName);
if (LIKELY(tv != nullptr)) return tv;
String normName = normalizeNS(cnsName);
if (normName) {
cnsName = normName.get();
tv = lookupCns(cnsName);
if (tv != nullptr) return tv;
}
if (!AutoloadHandler::s_instance->autoloadConstant(
const_cast<StringData*>(cnsName))) {
return nullptr;
}
return lookupCns(cnsName);
}
bool Unit::defCns(const StringData* cnsName, const TypedValue* value,
bool persistent /* = false */) {
TargetCache::CacheHandle handle =
StringData::DefCnsHandle(cnsName, persistent);
if (UNLIKELY(handle == 0)) {
if (UNLIKELY(!TargetCache::s_constants)) {
/*
* This only happens when we call define on a non
* static string. Not worth presizing or otherwise
* optimizing for.
*/
TargetCache::s_constants = ArrayData::Make(1);
TargetCache::s_constants->incRefCount();
}
if (TargetCache::s_constants->nvInsert(
const_cast<StringData*>(cnsName), const_cast<TypedValue*>(value))) {
return true;
}
raise_warning(Strings::CONSTANT_ALREADY_DEFINED, cnsName->data());
return false;
}
return defCnsHelper(handle, value, cnsName);
}
uint64_t Unit::defCnsHelper(uint64_t ch,
const TypedValue *value,
const StringData *cnsName) {
TypedValue* cns = &TargetCache::handleToRef<TypedValue>(ch);
if (UNLIKELY(cns->m_type != KindOfUninit) ||
UNLIKELY(cns->m_data.pref != nullptr)) {
raise_warning(Strings::CONSTANT_ALREADY_DEFINED, cnsName->data());
} else if (UNLIKELY(!tvAsCVarRef(value).isAllowedAsConstantValue())) {