/
unit.cpp
2088 lines (1853 loc) · 64 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-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/vm/unit.h"
#include <algorithm>
#include <atomic>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <map>
#include <ostream>
#include <sstream>
#include <vector>
#include <boost/container/flat_map.hpp>
#include <folly/Format.h>
#include <tbb/concurrent_hash_map.h>
#include "hphp/util/alloc.h"
#include "hphp/util/assertions.h"
#include "hphp/util/compilation-flags.h"
#include "hphp/util/functional.h"
#include "hphp/util/lock.h"
#include "hphp/util/mutex.h"
#include "hphp/util/smalllocks.h"
#include "hphp/runtime/base/attr.h"
#include "hphp/runtime/base/autoload-handler.h"
#include "hphp/runtime/base/execution-context.h"
#include "hphp/runtime/base/packed-array.h"
#include "hphp/runtime/base/rds.h"
#include "hphp/runtime/base/runtime-error.h"
#include "hphp/runtime/base/runtime-option.h"
#include "hphp/runtime/base/stats.h"
#include "hphp/runtime/base/string-data.h"
#include "hphp/runtime/base/strings.h"
#include "hphp/runtime/base/tv-mutate.h"
#include "hphp/runtime/base/tv-variant.h"
#include "hphp/runtime/base/tv-refcount.h"
#include "hphp/runtime/base/type-array.h"
#include "hphp/runtime/base/type-string.h"
#include "hphp/runtime/base/type-variant.h"
#include "hphp/runtime/base/typed-value.h"
#include "hphp/runtime/base/unit-cache.h"
#include "hphp/runtime/vm/bytecode.h"
#include "hphp/runtime/vm/class.h"
#include "hphp/runtime/vm/debug/debug.h"
#include "hphp/runtime/vm/debugger-hook.h"
#include "hphp/runtime/vm/func.h"
#include "hphp/runtime/vm/hh-utils.h"
#include "hphp/runtime/vm/hhbc-codec.h"
#include "hphp/runtime/vm/hhbc.h"
#include "hphp/runtime/vm/instance-bits.h"
#include "hphp/runtime/vm/named-entity.h"
#include "hphp/runtime/vm/named-entity-defs.h"
#include "hphp/runtime/vm/preclass.h"
#include "hphp/runtime/vm/repo.h"
#include "hphp/runtime/vm/reverse-data-map.h"
#include "hphp/runtime/vm/treadmill.h"
#include "hphp/runtime/vm/type-alias.h"
#include "hphp/runtime/vm/unit-emitter.h"
#include "hphp/runtime/vm/unit-util.h"
#include "hphp/runtime/vm/vm-regs.h"
#include "hphp/runtime/server/source-root-info.h"
#include "hphp/runtime/ext/std/ext_std_closure.h"
#include "hphp/runtime/ext/string/ext_string.h"
#include "hphp/system/systemlib.h"
namespace HPHP {
//////////////////////////////////////////////////////////////////////
namespace {
//////////////////////////////////////////////////////////////////////
const StaticString s_stdin("STDIN");
const StaticString s_stdout("STDOUT");
const StaticString s_stderr("STDERR");
//////////////////////////////////////////////////////////////////////
/*
* Read typed data from an offset relative to a base address
*/
template<class T>
T& getDataRef(void* base, unsigned offset) {
return *reinterpret_cast<T*>(static_cast<char*>(base) + offset);
}
//////////////////////////////////////////////////////////////////////
/*
* We store 'detailed' line number information on a table on the side, because
* in production modes for HHVM it's generally not useful (which keeps Unit
* smaller in that case)---this stuff is only used for the debugger, where we
* can afford the lookup here. The normal Unit m_lineMap is capable of
* producing enough line number information for things needed in production
* modes (backtraces, warnings, etc).
*/
using LineToOffsetRangeVecMap = std::map<int,OffsetRangeVec>;
struct ExtendedLineInfo {
SourceLocTable sourceLocTable;
/*
* Map from source lines to a collection of all the bytecode ranges the line
* encompasses.
*
* The value type of the map is a list of offset ranges, so a single line
* with several sub-statements may correspond to the bytecodes of all of the
* sub-statements.
*
* May not be initialized. Lookups need to check if it's empty() and if so
* compute it from sourceLocTable.
*/
LineToOffsetRangeVecMap lineToOffsetRange;
};
using ExtendedLineInfoCache = tbb::concurrent_hash_map<
const Unit*,
ExtendedLineInfo,
pointer_hash<Unit>
>;
ExtendedLineInfoCache s_extendedLineInfo;
using LineTableStash = tbb::concurrent_hash_map<
const Unit*,
LineTable,
pointer_hash<Unit>
>;
LineTableStash s_lineTables;
struct LineCacheEntry {
LineCacheEntry(const Unit* unit, LineTable&& table)
: unit{unit}
, table{std::move(table)}
{}
const Unit* unit;
LineTable table;
};
std::array<std::atomic<LineCacheEntry*>, 512> s_lineCache;
//////////////////////////////////////////////////////////////////////
}
///////////////////////////////////////////////////////////////////////////////
// MergeInfo.
Unit::MergeInfo* Unit::MergeInfo::alloc(size_t size) {
MergeInfo* mi = (MergeInfo*)malloc(
sizeof(MergeInfo) + size * sizeof(void*));
mi->m_firstHoistableFunc = 0;
mi->m_firstHoistablePreClass = 0;
mi->m_firstMergeablePreClass = 0;
mi->m_mergeablesSize = size;
return mi;
}
///////////////////////////////////////////////////////////////////////////////
// Construction and destruction.
Unit::Unit()
: m_mergeOnly(false)
, m_interpretOnly(false)
, m_isHHFile(false)
, m_extended(false)
, m_mainReturn(make_tv<KindOfUninit>())
{}
Unit::~Unit() {
if (RuntimeOption::EvalEnableReverseDataMap &&
m_mergeState != MergeState::Unmerged) {
// Units are registered to data_map in Unit::initialMerge().
data_map::deregister(this);
}
s_extendedLineInfo.erase(this);
s_lineTables.erase(this);
auto const hash = pointer_hash<Unit>{}(this) % s_lineCache.size();
auto& entry = s_lineCache[hash];
if (auto lce = entry.load(std::memory_order_acquire)) {
if (lce->unit == this &&
entry.compare_exchange_strong(lce, nullptr,
std::memory_order_release)) {
Treadmill::enqueue([lce] { delete lce; });
}
}
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));
g_hhbc_size->addValue(-int64_t(m_bclen));
}
if (m_mergeInfo) {
for (auto* func : m_mergeInfo->mutableFuncs()) Func::destroy(func);
}
// ExecutionContext and the TC may retain references to Class'es, so
// it is possible for Class'es to outlive their Unit.
for (auto const& pcls : m_preClasses) {
Class* cls = pcls->namedEntity()->clsList();
while (cls) {
Class* cur = cls;
cls = cls->m_nextClass;
if (cur->preClass() == pcls.get()) {
cur->destroy();
}
}
}
free(m_mergeInfo);
if (m_pseudoMainCache) {
for (auto& kv : *m_pseudoMainCache) {
Func::destroy(kv.second);
}
delete m_pseudoMainCache;
}
}
void* Unit::operator new(size_t sz) {
return low_malloc_data(sz);
}
void Unit::operator delete(void* p, size_t /*sz*/) {
low_free_data(p);
}
///////////////////////////////////////////////////////////////////////////////
// Code locations.
static SourceLocTable loadSourceLocTable(const Unit* unit) {
auto ret = SourceLocTable{};
if (unit->repoID() == RepoIdInvalid) return ret;
Lock lock(g_classesMutex);
auto& urp = Repo::get().urp();
urp.getSourceLocTab[unit->repoID()].get(unit->sn(), ret);
return ret;
}
/*
* Return the Unit's SourceLocTable, extracting it from the repo if
* necessary.
*/
const SourceLocTable& getSourceLocTable(const Unit* unit) {
{
ExtendedLineInfoCache::const_accessor acc;
if (s_extendedLineInfo.find(acc, unit)) {
return acc->second.sourceLocTable;
}
}
// Try to load it while we're not holding the lock.
auto newTable = loadSourceLocTable(unit);
ExtendedLineInfoCache::accessor acc;
if (s_extendedLineInfo.insert(acc, unit)) {
acc->second.sourceLocTable = std::move(newTable);
}
return acc->second.sourceLocTable;
}
/**
* Generate line->vector<OffsetRange> reverse map from SourceLocTable.
*
* Algorithm:
* We first generate the OffsetRange for each SourceLoc,
* then sort the pair<SourceLoc, OffsetRange> in most nested to outward order
* so that we can add vector<OffsetRange> for nested lines first.
* After merging continuous duplicate line ranges into one we build the final
* map by adding vector<OffsetRange> for each line in the LineRange only if
* it hasn't got any vector<OffsetRange> from inner LineRange yet.
* By doing this we ensure the outer LineRange's vector<OffsetRange> will not be
* added for inner lines.
*/
static void generateLineToOffsetRangesMap(
const Unit* unit,
LineToOffsetRangeVecMap& map
) {
// First generate an OffsetRange for each SourceLoc.
auto const& srcLocTable = getSourceLocTable(unit);
struct LineRange {
LineRange(int start, int end)
: line0(start), line1(end)
{}
int line0;
int line1;
bool operator!=(const LineRange& other) const {
return this->line0 != other.line0 || this->line1 != other.line1;
}
};
using LineRangeOffsetRangePair = std::pair<LineRange, OffsetRange>;
std::vector<LineRangeOffsetRangePair> lineRangesTable;
Offset baseOff = 0;
for (const auto& sourceLoc: srcLocTable) {
Offset pastOff = sourceLoc.pastOffset();
OffsetRange offsetRange(baseOff, pastOff);
LineRange lineRange(sourceLoc.val().line0, sourceLoc.val().line1);
lineRangesTable.emplace_back(lineRange, offsetRange);
baseOff = pastOff;
}
// Sort the line ranges in most nested to outward order:
// First sort them in ascending order by line range end;
// if range end ties, sort in descending order by line range start.
std::sort(
lineRangesTable.begin(),
lineRangesTable.end(),
[](const LineRangeOffsetRangePair& a, const LineRangeOffsetRangePair& b) {
return a.first.line1 == b.first.line1 ?
a.first.line0 > b.first.line0 :
a.first.line1 < b.first.line1;
}
);
// Merge continuous duplicate line ranges into one.
using LineRangeToOffsetRangesTable =
std::vector<std::pair<LineRange, std::vector<OffsetRange>>>;
LineRangeToOffsetRangesTable lineRangeToOffsetRangesTable;
for (auto i = 0; i < lineRangesTable.size(); ++i) {
if (i == 0 || lineRangesTable[i].first != lineRangesTable[i-1].first) {
// New line range starts.
std::vector<OffsetRange> offsetRanges;
offsetRanges.emplace_back(lineRangesTable[i].second);
const auto& lineRange = lineRangesTable[i].first;
lineRangeToOffsetRangesTable.emplace_back(lineRange, offsetRanges);
} else {
// Duplicate LineRange.
assertx(lineRangeToOffsetRangesTable.size() > 0);
auto& offsetRanges = lineRangeToOffsetRangesTable.back().second;
offsetRanges.emplace_back(lineRangesTable[i].second);
}
}
// Generate the final line to offset ranges map.
for (auto& entry: lineRangeToOffsetRangesTable) {
// Sort the offset ranges of each line range.
std::sort(
entry.second.begin(),
entry.second.end(),
[](const OffsetRange& a, const OffsetRange& b) {
return a.base == b.base ? a.past < b.past : a.base < b.base;
}
);
const auto& offsetRanges = entry.second;
auto line0 = entry.first.line0;
auto line1 = entry.first.line1;
for (auto line = line0; line <= line1; ++line) {
// Only add if not added by inner LineRange yet.
if (map.find(line) == map.end()) {
map[line] = offsetRanges;
}
}
}
}
/*
* Return a copy of the Unit's line to OffsetRangeVec table.
*/
static LineToOffsetRangeVecMap getLineToOffsetRangeVecMap(const Unit* unit) {
{
ExtendedLineInfoCache::const_accessor acc;
if (s_extendedLineInfo.find(acc, unit)) {
if (!acc->second.lineToOffsetRange.empty()) {
return acc->second.lineToOffsetRange;
}
}
}
LineToOffsetRangeVecMap map;
generateLineToOffsetRangesMap(unit, map);
ExtendedLineInfoCache::accessor acc;
if (!s_extendedLineInfo.find(acc, unit)) {
always_assert_flog(0, "ExtendedLineInfoCache was not found when it should "
"have been");
}
if (acc->second.lineToOffsetRange.empty()) {
acc->second.lineToOffsetRange = std::move(map);
}
return acc->second.lineToOffsetRange;
}
static const LineTable& loadLineTable(const Unit* unit) {
if (unit->repoID() == RepoIdInvalid) {
LineTableStash::accessor acc;
if (s_lineTables.find(acc, unit)) {
return acc->second;
}
static LineTable empty;
return empty;
}
auto const hash = pointer_hash<Unit>{}(unit) % s_lineCache.size();
auto& entry = s_lineCache[hash];
if (auto const p = entry.load(std::memory_order_acquire)) {
if (p->unit == unit) return p->table;
}
// We already hold a lock on the unit in Unit::getLineNumber below,
// so nobody else is going to be reading the line table while we are
// (this is only an efficiency concern).
auto& urp = Repo::get().urp();
auto table = LineTable{};
urp.getUnitLineTable(unit->repoID(), unit->sn(), table);
auto const p = new LineCacheEntry(unit, std::move(table));
if (auto const old = entry.exchange(p, std::memory_order_release)) {
Treadmill::enqueue([old] { delete old; });
}
return p->table;
}
static LineInfo getLineInfo(const LineTable& table, Offset pc) {
auto const it =
std::upper_bound(begin(table), end(table), LineEntry{ pc, -1 });
auto const e = end(table);
if (it != e) {
auto const line = it->val();
if (line > 0) {
auto const pastOff = it->pastOffset();
auto const baseOff = it == begin(table) ?
pc : std::prev(it)->pastOffset();
assertx(baseOff <= pc && pc < pastOff);
return { { baseOff, pastOff }, line };
}
}
return LineInfo{ { pc, pc + 1 }, -1 };
}
int getLineNumber(const LineTable& table, Offset pc) {
auto const key = LineEntry(pc, -1);
auto it = std::upper_bound(begin(table), end(table), key);
if (it != end(table)) {
assert(pc < it->pastOffset());
return it->val();
}
return -1;
}
int Unit::getLineNumber(Offset pc) const {
if (UNLIKELY(m_repoId == RepoIdInvalid)) {
auto const lineTable = [&] () -> const LineTable* {
LineTableStash::accessor acc;
if (s_lineTables.find(acc, this)) {
return &acc->second;
}
return nullptr;
}();
if (lineTable) return HPHP::getLineNumber(*lineTable, pc);
}
auto findLine = [&] {
// lineMap is an atomically acquired bitwise copy of m_lineMap,
// with no destructor
auto lineMap(m_lineMap.get());
if (lineMap->empty()) return INT_MIN;
auto const it = std::upper_bound(
lineMap->begin(), lineMap->end(),
*lineMap->begin(), // Will be the first (ignored) param to our predicate
[&] (const LineInfo&, const LineInfo& elm) {
return pc < elm.first.past;
}
);
if (it != lineMap->end() && it->first.base <= pc) return it->second;
return INT_MIN;
};
auto line = findLine();
if (line != INT_MIN) return line;
m_lineMap.lock_for_update();
try {
line = findLine();
if (line != INT_MIN) {
m_lineMap.unlock();
return line;
}
auto const info = HPHP::getLineInfo(loadLineTable(this), pc);
auto copy = m_lineMap.copy();
auto const it = std::upper_bound(
copy.begin(), copy.end(),
info,
[&] (const LineInfo& a, const LineInfo& b) {
return a.first.base < b.first.past;
}
);
assertx(it == copy.end() || (it->first.past > pc && it->first.base > pc));
copy.insert(it, info);
auto old = m_lineMap.update_and_unlock(std::move(copy));
Treadmill::enqueue([old = std::move(old)] () mutable { old.clear(); });
return info.second;
} catch (...) {
m_lineMap.unlock();
throw;
}
}
bool getSourceLoc(const SourceLocTable& table, Offset pc, SourceLoc& sLoc) {
SourceLocEntry key(pc, sLoc);
auto it = std::upper_bound(table.begin(), table.end(), key);
if (it != table.end()) {
assert(pc < it->pastOffset());
sLoc = it->val();
return true;
}
return false;
}
bool Unit::getSourceLoc(Offset pc, SourceLoc& sLoc) const {
auto const& sourceLocTable = getSourceLocTable(this);
return HPHP::getSourceLoc(sourceLocTable, pc, sLoc);
}
bool Unit::getOffsetRange(Offset pc, OffsetRange& range) const {
OffsetRangeVec offsets;
auto line = getLineNumber(pc);
getOffsetRanges(line, offsets);
for (auto offset: offsets) {
if (pc >= offset.base && pc < offset.past) {
range = offset;
return true;
}
}
return false;
}
bool Unit::getOffsetRanges(int line, OffsetRangeVec& offsets) const {
assert(offsets.size() == 0);
auto map = getLineToOffsetRangeVecMap(this);
auto it = map.find(line);
if (it == map.end()) return false;
offsets = it->second;
return true;
}
int Unit::getNearestLineWithCode(int line) const {
auto map = getLineToOffsetRangeVecMap(this);
auto it = map.lower_bound(line);
return it == map.end() ? -1 : it->first;
}
const Func* Unit::getFunc(Offset pc) const {
auto& table = getExtended()->m_funcTable;
auto it = std::upper_bound(table.begin(), table.end(), nullptr,
[&] (const Func* a, const Func* b) {
assertx(a == nullptr);
return pc < b->past();
});
if (it != table.end()) {
assert(pc < (*it)->past());
return *it;
}
return nullptr;
}
void stashLineTable(const Unit* unit, LineTable table) {
LineTableStash::accessor acc;
if (s_lineTables.insert(acc, unit)) {
acc->second = std::move(table);
}
}
void stashExtendedLineTable(const Unit* unit, SourceLocTable table) {
ExtendedLineInfoCache::accessor acc;
if (s_extendedLineInfo.insert(acc, unit)) {
acc->second.sourceLocTable = std::move(table);
}
}
///////////////////////////////////////////////////////////////////////////////
// Funcs and PreClasses.
Func* Unit::getMain(Class* cls /* = nullptr */) const {
if (!cls) return *m_mergeInfo->funcBegin();
Lock lock(g_classesMutex);
if (!m_pseudoMainCache) {
m_pseudoMainCache = new PseudoMainCacheMap;
}
auto it = m_pseudoMainCache->find(cls);
if (it != m_pseudoMainCache->end()) {
return it->second;
}
Func* f = (*m_mergeInfo->funcBegin())->clone(cls);
f->setNewFuncId();
f->setBaseCls(cls);
(*m_pseudoMainCache)[cls] = f;
return f;
}
void Unit::renameFunc(const StringData* oldName, const StringData* newName) {
// 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 (auto& func : m_mergeInfo->hoistableFuncs()) {
auto const name = func->name();
assert(name);
if (name->same(oldName)) {
func->rename(newName);
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Func lookup.
void Unit::defFunc(Func* func, bool debugger) {
assert(!func->isMethod());
auto const handle = func->funcHandle();
auto& funcAddr = rds::handleToRef<LowPtr<Func>>(handle);
if (rds::isPersistentHandle(handle)) {
auto const oldFunc = funcAddr.get();
if (oldFunc == func) return;
if (UNLIKELY(oldFunc != nullptr)) {
assertx(oldFunc->isBuiltin() && !func->isBuiltin());
raise_error(Strings::REDECLARE_BUILTIN, func->name()->data());
}
} else {
assertx(rds::isNormalHandle(handle));
if (!rds::isHandleInit(handle, rds::NormalTag{})) {
rds::initHandle(handle);
} else {
if (funcAddr.get() == func) return;
raise_error(Strings::FUNCTION_ALREADY_DEFINED, func->name()->data());
}
}
funcAddr = func;
if (func->isUnique()) func->getNamedEntity()->setUniqueFunc(func);
if (UNLIKELY(debugger)) phpDebuggerDefFuncHook(func);
}
Func* Unit::lookupFunc(const NamedEntity* ne) {
return ne->getCachedFunc();
}
Func* Unit::lookupFunc(const StringData* name) {
const NamedEntity* ne = NamedEntity::get(name);
return ne->getCachedFunc();
}
Func* Unit::lookupBuiltin(const StringData* name) {
// Builtins are either persistent (the normal case), or defined at the
// beginning of every request (if JitEnableRenameFunction or interception is
// enabled). In either case, they're unique, so they should be present in the
// NamedEntity.
auto const ne = NamedEntity::get(name);
auto const f = ne->uniqueFunc();
return (f && f->isBuiltin()) ? f : nullptr;
}
Func* Unit::loadFunc(const NamedEntity* ne, const StringData* name) {
Func* func = ne->getCachedFunc();
if (LIKELY(func != nullptr)) return func;
if (AutoloadHandler::s_instance->autoloadFunc(
const_cast<StringData*>(name))) {
func = ne->getCachedFunc();
}
return func;
}
Func* Unit::loadFunc(const StringData* name) {
String normStr;
auto ne = NamedEntity::get(name, true, &normStr);
if (normStr) {
name = normStr.get();
}
return loadFunc(ne, name);
}
void Unit::bindFunc(Func *func) {
assert(!func->isMethod());
auto const ne = func->getNamedEntity();
ne->m_cachedFunc.bind(
[&] {
auto const isPersistent =
(RuntimeOption::RepoAuthoritative || !SystemLib::s_inited) &&
(func->attrs() & AttrPersistent);
auto const link = rds::alloc<LowPtr<const Func>>(
isPersistent ? rds::Mode::Persistent : rds::Mode::Normal);
*link = func;
if (func->isUnique()) ne->setUniqueFunc(func);
if (RuntimeOption::EvalPerfDataMap) {
rds::recordRds(
link.handle(),
sizeof(void*),
"Func",
func->name()->toCppString()
);
}
return link.handle();
}
);
func->setFuncHandle(ne->m_cachedFunc);
}
///////////////////////////////////////////////////////////////////////////////
struct FrameRestore {
explicit FrameRestore(const PreClass* preClass) :
FrameRestore(preClass->unit(), preClass->getOffset()) {}
explicit FrameRestore(const Unit* unit, Op op, Id id) :
FrameRestore(unit, (static_cast<size_t>(op) << 32) | id) {}
explicit NEVER_INLINE FrameRestore(const Unit* unit, size_t offsetOrOp) {
ActRec* fp = vmfp();
if (vmsp() && (!fp || fp->m_func->unit() != unit)) {
m_top = vmsp();
m_fp = fp;
m_pc = vmpc();
/*
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 = *vmStack().allocA();
tmp.m_sfp = fp;
tmp.m_savedRip = 0;
tmp.m_func = unit->getMain(nullptr);
tmp.m_soff = !fp
? 0
: fp->m_func->unit()->offsetOf(m_pc) - fp->m_func->base();
tmp.trashThis();
tmp.m_varEnv = 0;
tmp.initNumArgs(0);
vmfp() = &tmp;
auto const offset = [&] {
if (offsetOrOp < kInvalidOffset) return static_cast<Offset>(offsetOrOp);
auto const op = Op(offsetOrOp >> 32);
auto const id = Id(offsetOrOp & 0xffffffff);
auto pc = unit->at(tmp.m_func->base());
auto const past = unit->at(tmp.m_func->past());
while (pc < past) {
if (peek_op(pc) == op) {
auto tpc = pc;
decode_op(tpc);
if (decode_iva(tpc) == id) return unit->offsetOf(pc);
}
pc += instrLen(pc);
}
return tmp.m_func->base();
}();
vmpc() = unit->at(offset);
pushFrameSlots(tmp.m_func);
} else {
m_top = nullptr;
m_fp = nullptr;
m_pc = nullptr;
}
}
~FrameRestore() {
if (m_top) {
vmsp() = m_top;
vmfp() = m_fp;
vmpc() = m_pc;
}
}
private:
Cell* m_top;
ActRec* m_fp;
PC m_pc;
};
///////////////////////////////////////////////////////////////////////////////
// Class lookup.
namespace {
void setupClass(Class* newClass, NamedEntity* nameList) {
bool const isPersistent =
(!SystemLib::s_inited || RuntimeOption::RepoAuthoritative) &&
newClass->verifyPersistent();
nameList->m_cachedClass.bind(
isPersistent ? rds::Mode::Persistent : rds::Mode::Normal);
newClass->setClassHandle(nameList->m_cachedClass);
newClass->incAtomicCount();
InstanceBits::ifInitElse(
[&] { newClass->setInstanceBits();
nameList->pushClass(newClass); },
[&] { nameList->pushClass(newClass); }
);
if (RuntimeOption::EvalEnableReverseDataMap) {
// The corresponding deregister is in NamedEntity::removeClass().
data_map::register_start(newClass);
}
}
}
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->getCachedTypeAlias()) {
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(g_classesMutex);
if (UNLIKELY(top != nameList->clsList())) {
top = nameList->clsList();
continue;
}
setupClass(newClass.get(), nameList);
/*
* call setCached after adding to the class list, otherwise the
* target-cache short circuit at the top could return a class
* which is not yet on the clsList().
*/
newClass.get()->setCached();
DEBUGGER_ATTACHED_ONLY(phpDebuggerDefClassHook(newClass.get()));
return newClass.get();
}
}
Class* Unit::defClosure(const PreClass* preClass) {
auto const nameList = preClass->namedEntity();
if (nameList->clsList()) return nameList->clsList();
auto const parent = c_Closure::classof();
assertx(preClass->parent() == parent->name());
// Create a new class.
ClassPtr newClass {
Class::newClass(const_cast<PreClass*>(preClass), parent)
};
Lock l(g_classesMutex);
if (UNLIKELY(nameList->clsList() != nullptr)) return nameList->clsList();
setupClass(newClass.get(), nameList);
if (classHasPersistentRDS(newClass.get())) newClass.get()->setCached();
return newClass.get();
}
namespace {
bool isPHP7ReservedType(const StringData* alias) {
return
!strcmp("int", alias->data()) ||
!strcmp("bool", alias->data()) ||
!strcmp("float", alias->data()) ||
!strcmp("string", alias->data());
}
}
bool Unit::aliasClass(const StringData* original, const StringData* alias,
bool autoload) {
if (RuntimeOption::PHP7_ScalarTypes && isPHP7ReservedType(alias)) {
raise_error("Fatal error: Cannot use '%s' as class name as it is reserved",
alias->data());
}
auto const origClass =
autoload ? Unit::loadClass(original)
: Unit::lookupClass(original);
if (!origClass) {
raise_warning("Class %s not found", original->data());
return false;
}
if (origClass->isBuiltin()) {
raise_warning("First argument of class_alias() must be "
"the name of a user defined class");
return false;
}
auto const aliasNe = NamedEntity::get(alias);
aliasNe->m_cachedClass.bind();
auto const aliasClass = aliasNe->getCachedClass();
if (aliasClass) {
raise_warning("Cannot redeclare class %s", alias->data());
return false;
}
aliasNe->setCachedClass(origClass);
return true;
}
Class* Unit::loadClass(const NamedEntity* ne,
const StringData* name) {