Debian Codegraph @

js/src/jit/arm/Simulator-arm.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 // Copyright 2012 the V8 project authors. All rights reserved.
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following
11 // disclaimer in the documentation and/or other materials provided
12 // with the distribution.
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived
15 // from this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 #include "jit/arm/Simulator-arm.h"
30
31 #include "mozilla/Casting.h"
32 #include "mozilla/DebugOnly.h"
33 #include "mozilla/EndianUtils.h"
34 #include "mozilla/FloatingPoint.h"
35 #include "mozilla/Likely.h"
36 #include "mozilla/MathAlgorithms.h"
37
38 #include "jit/arm/Assembler-arm.h"
39 #include "jit/arm/disasm/Constants-arm.h"
40 #include "jit/AtomicOperations.h"
41 #include "js/UniquePtr.h"
42 #include "js/Utility.h"
43 #include "threading/LockGuard.h"
44 #include "vm/Float16.h"
45 #include "vm/JSContext.h"
46 #include "vm/Runtime.h"
47 #include "vm/SharedMem.h"
48 #include "wasm/WasmInstance.h"
49 #include "wasm/WasmSignalHandlers.h"
50
51 extern "C" {
52
53 MOZ_EXPORT int64_t __aeabi_idivmod(int x, int y) {
54 // Run-time ABI for the ARM architecture specifies that for |INT_MIN / -1|
55 // "an implementation is (sic) may return any convenient value, possibly the
56 // original numerator."
57 //
58 // |INT_MIN / -1| traps on x86, which isn't listed as an allowed behavior in
59 // the ARM docs, so instead follow LLVM and return the numerator. (And zero
60 // for the remainder.)
61
62 if (x == INT32_MIN && y == -1) {
63 return uint32_t(x);
64 }
65
66 uint32_t lo = uint32_t(x / y);
67 uint32_t hi = uint32_t(x % y);
68 return (int64_t(hi) << 32) | lo;
69 }
70
71 MOZ_EXPORT int64_t __aeabi_uidivmod(int x, int y) {
72 uint32_t lo = uint32_t(x) / uint32_t(y);
73 uint32_t hi = uint32_t(x) % uint32_t(y);
74 return (int64_t(hi) << 32) | lo;
75 }
76 }
77
78 namespace js {
79 namespace jit {
80
81 // For decoding load-exclusive and store-exclusive instructions.
82 namespace excl {
83
84 // Bit positions.
85 enum {
86 ExclusiveOpHi = 24, // Hi bit of opcode field
87 ExclusiveOpLo = 23, // Lo bit of opcode field
88 ExclusiveSizeHi = 22, // Hi bit of operand size field
89 ExclusiveSizeLo = 21, // Lo bit of operand size field
90 ExclusiveLoad = 20 // Bit indicating load
91 };
92
93 // Opcode bits for exclusive instructions.
94 enum { ExclusiveOpcode = 3 };
95
96 // Operand size, Bits(ExclusiveSizeHi,ExclusiveSizeLo).
97 enum {
98 ExclusiveWord = 0,
99 ExclusiveDouble = 1,
100 ExclusiveByte = 2,
101 ExclusiveHalf = 3
102 };
103
104 } // namespace excl
105
106 // Load/store multiple addressing mode.
107 enum BlockAddrMode {
108 // Alias modes for comparison when writeback does not matter.
109 da_x = (0 | 0 | 0) << 21, // Decrement after.
110 ia_x = (0 | 4 | 0) << 21, // Increment after.
111 db_x = (8 | 0 | 0) << 21, // Decrement before.
112 ib_x = (8 | 4 | 0) << 21, // Increment before.
113 };
114
115 // Type of VFP register. Determines register encoding.
116 enum VFPRegPrecision { kSinglePrecision = 0, kDoublePrecision = 1 };
117
118 enum NeonListType { nlt_1 = 0x7, nlt_2 = 0xA, nlt_3 = 0x6, nlt_4 = 0x2 };
119
120 // Supervisor Call (svc) specific support.
121
122 // Special Software Interrupt codes when used in the presence of the ARM
123 // simulator.
124 // svc (formerly swi) provides a 24bit immediate value. Use bits 22:0 for
125 // standard SoftwareInterrupCode. Bit 23 is reserved for the stop feature.
126 enum SoftwareInterruptCodes {
127 kCallRtRedirected = 0x10, // Transition to C code.
128 kBreakpoint = 0x20, // Breakpoint.
129 kStopCode = 1 << 23 // Stop.
130 };
131
132 const uint32_t kStopCodeMask = kStopCode - 1;
133 const uint32_t kMaxStopCode = kStopCode - 1;
134
135 // -----------------------------------------------------------------------------
136 // Instruction abstraction.
137
138 // The class Instruction enables access to individual fields defined in the ARM
139 // architecture instruction set encoding as described in figure A3-1.
140 // Note that the Assembler uses using Instr = int32_t.
141 //
142 // Example: Test whether the instruction at ptr does set the condition code
143 // bits.
144 //
145 // bool InstructionSetsConditionCodes(byte* ptr) {
146 // Instruction* instr = Instruction::At(ptr);
147 // int type = instr->TypeValue();
148 // return ((type == 0) || (type == 1)) && instr->hasS();
149 // }
150 //
151 class SimInstruction {
152 public:
153 enum { kInstrSize = 4, kPCReadOffset = 8 };
154
155 // Get the raw instruction bits.
156 inline Instr instructionBits() const {
157 return *reinterpret_cast<const Instr*>(this);
158 }
159
160 // Set the raw instruction bits to value.
161 inline void setInstructionBits(Instr value) {
162 *reinterpret_cast<Instr*>(this) = value;
163 }
164
165 // Read one particular bit out of the instruction bits.
166 inline int bit(int nr) const { return (instructionBits() >> nr) & 1; }
167
168 // Read a bit field's value out of the instruction bits.
169 inline int bits(int hi, int lo) const {
170 return (instructionBits() >> lo) & ((2 << (hi - lo)) - 1);
171 }
172
173 // Read a bit field out of the instruction bits.
174 inline int bitField(int hi, int lo) const {
175 return instructionBits() & (((2 << (hi - lo)) - 1) << lo);
176 }
177
178 // Accessors for the different named fields used in the ARM encoding.
179 // The naming of these accessor corresponds to figure A3-1.
180 //
181 // Two kind of accessors are declared:
182 // - <Name>Field() will return the raw field, i.e. the field's bits at their
183 // original place in the instruction encoding.
184 // e.g. if instr is the 'addgt r0, r1, r2' instruction, encoded as
185 // 0xC0810002 conditionField(instr) will return 0xC0000000.
186 // - <Name>Value() will return the field value, shifted back to bit 0.
187 // e.g. if instr is the 'addgt r0, r1, r2' instruction, encoded as
188 // 0xC0810002 conditionField(instr) will return 0xC.
189
190 // Generally applicable fields
191 inline Assembler::ARMCondition conditionField() const {
192 return static_cast<Assembler::ARMCondition>(bitField(31, 28));
193 }
194 inline int typeValue() const { return bits(27, 25); }
195 inline int specialValue() const { return bits(27, 23); }
196
197 inline int rnValue() const { return bits(19, 16); }
198 inline int rdValue() const { return bits(15, 12); }
199
200 inline int coprocessorValue() const { return bits(11, 8); }
201
202 // Support for VFP.
203 // Vn(19-16) | Vd(15-12) | Vm(3-0)
204 inline int vnValue() const { return bits(19, 16); }
205 inline int vmValue() const { return bits(3, 0); }
206 inline int vdValue() const { return bits(15, 12); }
207 inline int nValue() const { return bit(7); }
208 inline int mValue() const { return bit(5); }
209 inline int dValue() const { return bit(22); }
210 inline int rtValue() const { return bits(15, 12); }
211 inline int pValue() const { return bit(24); }
212 inline int uValue() const { return bit(23); }
213 inline int opc1Value() const { return (bit(23) << 2) | bits(21, 20); }
214 inline int opc2Value() const { return bits(19, 16); }
215 inline int opc3Value() const { return bits(7, 6); }
216 inline int szValue() const { return bit(8); }
217 inline int VLValue() const { return bit(20); }
218 inline int VCValue() const { return bit(8); }
219 inline int VAValue() const { return bits(23, 21); }
220 inline int VBValue() const { return bits(6, 5); }
221 inline int VFPNRegValue(VFPRegPrecision pre) {
222 return VFPGlueRegValue(pre, 16, 7);
223 }
224 inline int VFPMRegValue(VFPRegPrecision pre) {
225 return VFPGlueRegValue(pre, 0, 5);
226 }
227 inline int VFPDRegValue(VFPRegPrecision pre) {
228 return VFPGlueRegValue(pre, 12, 22);
229 }
230
231 // Fields used in Data processing instructions.
232 inline int opcodeValue() const { return static_cast<ALUOp>(bits(24, 21)); }
233 inline ALUOp opcodeField() const {
234 return static_cast<ALUOp>(bitField(24, 21));
235 }
236 inline int sValue() const { return bit(20); }
237
238 // With register.
239 inline int rmValue() const { return bits(3, 0); }
240 inline ShiftType shifttypeValue() const {
241 return static_cast<ShiftType>(bits(6, 5));
242 }
243 inline int rsValue() const { return bits(11, 8); }
244 inline int shiftAmountValue() const { return bits(11, 7); }
245
246 // With immediate.
247 inline int rotateValue() const { return bits(11, 8); }
248 inline int immed8Value() const { return bits(7, 0); }
249 inline int immed4Value() const { return bits(19, 16); }
250 inline int immedMovwMovtValue() const {
251 return immed4Value() << 12 | offset12Value();
252 }
253
254 // Fields used in Load/Store instructions.
255 inline int PUValue() const { return bits(24, 23); }
256 inline int PUField() const { return bitField(24, 23); }
257 inline int bValue() const { return bit(22); }
258 inline int wValue() const { return bit(21); }
259 inline int lValue() const { return bit(20); }
260
261 // With register uses same fields as Data processing instructions above with
262 // immediate.
263 inline int offset12Value() const { return bits(11, 0); }
264
265 // Multiple.
266 inline int rlistValue() const { return bits(15, 0); }
267
268 // Extra loads and stores.
269 inline int signValue() const { return bit(6); }
270 inline int hValue() const { return bit(5); }
271 inline int immedHValue() const { return bits(11, 8); }
272 inline int immedLValue() const { return bits(3, 0); }
273
274 // Fields used in Branch instructions.
275 inline int linkValue() const { return bit(24); }
276 inline int sImmed24Value() const { return ((instructionBits() << 8) >> 8); }
277
278 // Fields used in Software interrupt instructions.
279 inline SoftwareInterruptCodes svcValue() const {
280 return static_cast<SoftwareInterruptCodes>(bits(23, 0));
281 }
282
283 // Test for special encodings of type 0 instructions (extra loads and
284 // stores, as well as multiplications).
285 inline bool isSpecialType0() const { return (bit(7) == 1) && (bit(4) == 1); }
286
287 // Test for miscellaneous instructions encodings of type 0 instructions.
288 inline bool isMiscType0() const {
289 return bit(24) == 1 && bit(23) == 0 && bit(20) == 0 && (bit(7) == 0);
290 }
291
292 // Test for a nop instruction, which falls under type 1.
293 inline bool isNopType1() const { return bits(24, 0) == 0x0120F000; }
294
295 // Test for a yield instruction, which falls under type 1.
296 inline bool isYieldType1() const { return bits(24, 0) == 0x0120F001; }
297
298 // Test for a nop instruction, which falls under type 1.
299 inline bool isCsdbType1() const { return bits(24, 0) == 0x0120F014; }
300
301 // Test for a stop instruction.
302 inline bool isStop() const {
303 return typeValue() == 7 && bit(24) == 1 && svcValue() >= kStopCode;
304 }
305
306 // Test for a udf instruction, which falls under type 3.
307 inline bool isUDF() const {
308 return (instructionBits() & 0xfff000f0) == 0xe7f000f0;
309 }
310
311 // Special accessors that test for existence of a value.
312 inline bool hasS() const { return sValue() == 1; }
313 inline bool hasB() const { return bValue() == 1; }
314 inline bool hasW() const { return wValue() == 1; }
315 inline bool hasL() const { return lValue() == 1; }
316 inline bool hasU() const { return uValue() == 1; }
317 inline bool hasSign() const { return signValue() == 1; }
318 inline bool hasH() const { return hValue() == 1; }
319 inline bool hasLink() const { return linkValue() == 1; }
320
321 // Decoding the double immediate in the vmov instruction.
322 double doubleImmedVmov() const;
323 // Decoding the float32 immediate in the vmov.f32 instruction.
324 float float32ImmedVmov() const;
325
326 private:
327 // Join split register codes, depending on single or double precision.
328 // four_bit is the position of the least-significant bit of the four
329 // bit specifier. one_bit is the position of the additional single bit
330 // specifier.
331 inline int VFPGlueRegValue(VFPRegPrecision pre, int four_bit, int one_bit) {
332 if (pre == kSinglePrecision) {
333 return (bits(four_bit + 3, four_bit) << 1) | bit(one_bit);
334 }
335 return (bit(one_bit) << 4) | bits(four_bit + 3, four_bit);
336 }
337
338 SimInstruction() = delete;
339 SimInstruction(const SimInstruction& other) = delete;
340 void operator=(const SimInstruction& other) = delete;
341 };
342
343 double SimInstruction::doubleImmedVmov() const {
344 // Reconstruct a double from the immediate encoded in the vmov instruction.
345 //
346 // instruction: [xxxxxxxx,xxxxabcd,xxxxxxxx,xxxxefgh]
347 // double: [aBbbbbbb,bbcdefgh,00000000,00000000,
348 // 00000000,00000000,00000000,00000000]
349 //
350 // where B = ~b. Only the high 16 bits are affected.
351 uint64_t high16;
352 high16 = (bits(17, 16) << 4) | bits(3, 0); // xxxxxxxx,xxcdefgh.
353 high16 |= (0xff * bit(18)) << 6; // xxbbbbbb,bbxxxxxx.
354 high16 |= (bit(18) ^ 1) << 14; // xBxxxxxx,xxxxxxxx.
355 high16 |= bit(19) << 15; // axxxxxxx,xxxxxxxx.
356
357 uint64_t imm = high16 << 48;
358 return mozilla::BitwiseCast<double>(imm);
359 }
360
361 float SimInstruction::float32ImmedVmov() const {
362 // Reconstruct a float32 from the immediate encoded in the vmov instruction.
363 //
364 // instruction: [xxxxxxxx,xxxxabcd,xxxxxxxx,xxxxefgh]
365 // float32: [aBbbbbbc, defgh000, 00000000, 00000000]
366 //
367 // where B = ~b. Only the high 16 bits are affected.
368 uint32_t imm;
369 imm = (bits(17, 16) << 23) | (bits(3, 0) << 19); // xxxxxxxc,defgh000.0.0
370 imm |= (0x1f * bit(18)) << 25; // xxbbbbbx,xxxxxxxx.0.0
371 imm |= (bit(18) ^ 1) << 30; // xBxxxxxx,xxxxxxxx.0.0
372 imm |= bit(19) << 31; // axxxxxxx,xxxxxxxx.0.0
373
374 return mozilla::BitwiseCast<float>(imm);
375 }
376
377 class CachePage {
378 public:
379 static const int LINE_VALID = 0;
380 static const int LINE_INVALID = 1;
381 static const int kPageShift = 12;
382 static const int kPageSize = 1 << kPageShift;
383 static const int kPageMask = kPageSize - 1;
384 static const int kLineShift = 2; // The cache line is only 4 bytes right now.
385 static const int kLineLength = 1 << kLineShift;
386 static const int kLineMask = kLineLength - 1;
387
388 CachePage() { memset(&validity_map_, LINE_INVALID, sizeof(validity_map_)); }
389 char* validityByte(int offset) {
390 return &validity_map_[offset >> kLineShift];
391 }
392 char* cachedData(int offset) { return &data_[offset]; }
393
394 private:
395 char data_[kPageSize]; // The cached data.
396 static const int kValidityMapSize = kPageSize >> kLineShift;
397 char validity_map_[kValidityMapSize]; // One byte per line.
398 };
399
400 // Protects the icache() and redirection() properties of the
401 // Simulator.
402 class AutoLockSimulatorCache : public LockGuard<Mutex> {
403 using Base = LockGuard<Mutex>;
404
405 public:
406 explicit AutoLockSimulatorCache()
407 : Base(SimulatorProcess::singleton_->cacheLock_) {}
408 };
409
410 mozilla::Atomic<size_t, mozilla::ReleaseAcquire>
411 SimulatorProcess::ICacheCheckingDisableCount(
412 1); // Checking is disabled by default.
413 SimulatorProcess* SimulatorProcess::singleton_ = nullptr;
414
415 int64_t Simulator::StopSimAt = -1L;
416
417 Simulator* Simulator::Create() {
418 auto sim = MakeUnique<Simulator>();
419 if (!sim) {
420 return nullptr;
421 }
422
423 if (!sim->init()) {
424 return nullptr;
425 }
426
427 char* stopAtStr = getenv("ARM_SIM_STOP_AT");
428 int64_t stopAt;
429 if (stopAtStr && sscanf(stopAtStr, "%lld", &stopAt) == 1) {
430 fprintf(stderr, "\nStopping simulation at icount %lld\n", stopAt);
431 Simulator::StopSimAt = stopAt;
432 }
433
434 return sim.release();
435 }
436
437 void Simulator::Destroy(Simulator* sim) { js_delete(sim); }
438
439 void Simulator::disassemble(SimInstruction* instr, size_t n) {
440 #ifdef JS_DISASM_ARM
441 disasm::NameConverter converter;
442 disasm::Disassembler dasm(converter);
443 disasm::EmbeddedVector<char, disasm::ReasonableBufferSize> buffer;
444 while (n-- > 0) {
445 dasm.InstructionDecode(buffer, reinterpret_cast<uint8_t*>(instr));
446 fprintf(stderr, " 0x%08x %s\n", uint32_t(instr), buffer.start());
447 instr = reinterpret_cast<SimInstruction*>(
448 reinterpret_cast<uint8_t*>(instr) + 4);
449 }
450 #endif
451 }
452
453 void Simulator::disasm(SimInstruction* instr) { disassemble(instr, 1); }
454
455 void Simulator::disasm(SimInstruction* instr, size_t n) {
456 disassemble(instr, n);
457 }
458
459 void Simulator::disasm(SimInstruction* instr, size_t m, size_t n) {
460 disassemble(reinterpret_cast<SimInstruction*>(
461 reinterpret_cast<uint8_t*>(instr) - m * 4),
462 n);
463 }
464
465 // The ArmDebugger class is used by the simulator while debugging simulated ARM
466 // code.
467 class ArmDebugger {
468 public:
469 explicit ArmDebugger(Simulator* sim) : sim_(sim) {}
470
471 void stop(SimInstruction* instr);
472 void debug();
473
474 private:
475 static const Instr kBreakpointInstr =
476 (Assembler::AL | (7 * (1 << 25)) | (1 * (1 << 24)) | kBreakpoint);
477 static const Instr kNopInstr = (Assembler::AL | (13 * (1 << 21)));
478
479 Simulator* sim_;
480
481 int32_t getRegisterValue(int regnum);
482 double getRegisterPairDoubleValue(int regnum);
483 void getVFPDoubleRegisterValue(int regnum, double* value);
484 bool getValue(const char* desc, int32_t* value);
485 bool getVFPDoubleValue(const char* desc, double* value);
486
487 // Set or delete a breakpoint. Returns true if successful.
488 bool setBreakpoint(SimInstruction* breakpc);
489 bool deleteBreakpoint(SimInstruction* breakpc);
490
491 // Undo and redo all breakpoints. This is needed to bracket disassembly and
492 // execution to skip past breakpoints when run from the debugger.
493 void undoBreakpoints();
494 void redoBreakpoints();
495 };
496
497 void ArmDebugger::stop(SimInstruction* instr) {
498 // Get the stop code.
499 uint32_t code = instr->svcValue() & kStopCodeMask;
500 // Retrieve the encoded address, which comes just after this stop.
501 char* msg =
502 *reinterpret_cast<char**>(sim_->get_pc() + SimInstruction::kInstrSize);
503 // Update this stop description.
504 if (sim_->isWatchedStop(code) && !sim_->watched_stops_[code].desc) {
505 sim_->watched_stops_[code].desc = msg;
506 }
507 // Print the stop message and code if it is not the default code.
508 if (code != kMaxStopCode) {
509 printf("Simulator hit stop %u: %s\n", code, msg);
510 } else {
511 printf("Simulator hit %s\n", msg);
512 }
513 sim_->set_pc(sim_->get_pc() + 2 * SimInstruction::kInstrSize);
514 debug();
515 }
516
517 int32_t ArmDebugger::getRegisterValue(int regnum) {
518 if (regnum == Registers::pc) {
519 return sim_->get_pc();
520 }
521 return sim_->get_register(regnum);
522 }
523
524 double ArmDebugger::getRegisterPairDoubleValue(int regnum) {
525 return sim_->get_double_from_register_pair(regnum);
526 }
527
528 void ArmDebugger::getVFPDoubleRegisterValue(int regnum, double* out) {
529 sim_->get_double_from_d_register(regnum, out);
530 }
531
532 bool ArmDebugger::getValue(const char* desc, int32_t* value) {
533 Register reg = Register::FromName(desc);
534 if (reg != InvalidReg) {
535 *value = getRegisterValue(reg.code());
536 return true;
537 }
538 if (strncmp(desc, "0x", 2) == 0) {
539 return sscanf(desc + 2, "%x", reinterpret_cast<uint32_t*>(value)) == 1;
540 }
541 return sscanf(desc, "%u", reinterpret_cast<uint32_t*>(value)) == 1;
542 }
543
544 bool ArmDebugger::getVFPDoubleValue(const char* desc, double* value) {
545 FloatRegister reg = FloatRegister::FromCode(FloatRegister::FromName(desc));
546 if (reg.isInvalid()) {
547 return false;
548 }
549
550 if (reg.isSingle()) {
551 float fval;
552 sim_->get_float_from_s_register(reg.id(), &fval);
553 *value = fval;
554 return true;
555 }
556
557 sim_->get_double_from_d_register(reg.id(), value);
558 return true;
559 }
560
561 bool ArmDebugger::setBreakpoint(SimInstruction* breakpc) {
562 // Check if a breakpoint can be set. If not return without any side-effects.
563 if (sim_->break_pc_) {
564 return false;
565 }
566
567 // Set the breakpoint.
568 sim_->break_pc_ = breakpc;
569 sim_->break_instr_ = breakpc->instructionBits();
570 // Not setting the breakpoint instruction in the code itself. It will be set
571 // when the debugger shell continues.
572 return true;
573 }
574
575 bool ArmDebugger::deleteBreakpoint(SimInstruction* breakpc) {
576 if (sim_->break_pc_ != nullptr) {
577 sim_->break_pc_->setInstructionBits(sim_->break_instr_);
578 }
579
580 sim_->break_pc_ = nullptr;
581 sim_->break_instr_ = 0;
582 return true;
583 }
584
585 void ArmDebugger::undoBreakpoints() {
586 if (sim_->break_pc_) {
587 sim_->break_pc_->setInstructionBits(sim_->break_instr_);
588 }
589 }
590
591 void ArmDebugger::redoBreakpoints() {
592 if (sim_->break_pc_) {
593 sim_->break_pc_->setInstructionBits(kBreakpointInstr);
594 }
595 }
596
597 static char* ReadLine(const char* prompt) {
598 UniqueChars result;
599 char line_buf[256];
600 int offset = 0;
601 bool keep_going = true;
602 fprintf(stdout, "%s", prompt);
603 fflush(stdout);
604 while (keep_going) {
605 if (fgets(line_buf, sizeof(line_buf), stdin) == nullptr) {
606 // fgets got an error. Just give up.
607 return nullptr;
608 }
609 int len = strlen(line_buf);
610 if (len > 0 && line_buf[len - 1] == '\n') {
611 // Since we read a new line we are done reading the line. This will
612 // exit the loop after copying this buffer into the result.
613 keep_going = false;
614 }
615 if (!result) {
616 // Allocate the initial result and make room for the terminating
617 // '\0'.
618 result.reset(js_pod_malloc<char>(len + 1));
619 if (!result) {
620 return nullptr;
621 }
622 } else {
623 // Allocate a new result with enough room for the new addition.
624 int new_len = offset + len + 1;
625 char* new_result = js_pod_malloc<char>(new_len);
626 if (!new_result) {
627 return nullptr;
628 }
629 // Copy the existing input into the new array and set the new
630 // array as the result.
631 memcpy(new_result, result.get(), offset * sizeof(char));
632 result.reset(new_result);
633 }
634 // Copy the newly read line into the result.
635 memcpy(result.get() + offset, line_buf, len * sizeof(char));
636 offset += len;
637 }
638
639 MOZ_ASSERT(result);
640 result[offset] = '\0';
641 return result.release();
642 }
643
644 void ArmDebugger::debug() {
645 intptr_t last_pc = -1;
646 bool done = false;
647
648 #define COMMAND_SIZE 63
649 #define ARG_SIZE 255
650
651 #define STR(a) #a
652 #define XSTR(a) STR(a)
653
654 char cmd[COMMAND_SIZE + 1];
655 char arg1[ARG_SIZE + 1];
656 char arg2[ARG_SIZE + 1];
657 char* argv[3] = {cmd, arg1, arg2};
658
659 // Make sure to have a proper terminating character if reaching the limit.
660 cmd[COMMAND_SIZE] = 0;
661 arg1[ARG_SIZE] = 0;
662 arg2[ARG_SIZE] = 0;
663
664 // Undo all set breakpoints while running in the debugger shell. This will
665 // make them invisible to all commands.
666 undoBreakpoints();
667
668 #ifndef JS_DISASM_ARM
669 static bool disasm_warning_printed = false;
670 if (!disasm_warning_printed) {
671 printf(
672 " No ARM disassembler present. Enable JS_DISASM_ARM in "
673 "configure.in.");
674 disasm_warning_printed = true;
675 }
676 #endif
677
678 while (!done && !sim_->has_bad_pc()) {
679 if (last_pc != sim_->get_pc()) {
680 #ifdef JS_DISASM_ARM
681 disasm::NameConverter converter;
682 disasm::Disassembler dasm(converter);
683 disasm::EmbeddedVector<char, disasm::ReasonableBufferSize> buffer;
684 dasm.InstructionDecode(buffer,
685 reinterpret_cast<uint8_t*>(sim_->get_pc()));
686 printf(" 0x%08x %s\n", sim_->get_pc(), buffer.start());
687 #endif
688 last_pc = sim_->get_pc();
689 }
690 char* line = ReadLine("sim> ");
691 if (line == nullptr) {
692 break;
693 } else {
694 char* last_input = sim_->lastDebuggerInput();
695 if (strcmp(line, "\n") == 0 && last_input != nullptr) {
696 line = last_input;
697 } else {
698 // Ownership is transferred to sim_;
699 sim_->setLastDebuggerInput(line);
700 }
701
702 // Use sscanf to parse the individual parts of the command line. At the
703 // moment no command expects more than two parameters.
704 int argc = sscanf(line,
705 "%" XSTR(COMMAND_SIZE) "s "
706 "%" XSTR(ARG_SIZE) "s "
707 "%" XSTR(ARG_SIZE) "s",
708 cmd, arg1, arg2);
709 if (argc < 0) {
710 continue;
711 } else if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) {
712 sim_->instructionDecode(
713 reinterpret_cast<SimInstruction*>(sim_->get_pc()));
714 sim_->icount_++;
715 } else if ((strcmp(cmd, "skip") == 0)) {
716 sim_->set_pc(sim_->get_pc() + 4);
717 sim_->icount_++;
718 } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) {
719 // Execute the one instruction we broke at with breakpoints
720 // disabled.
721 sim_->instructionDecode(
722 reinterpret_cast<SimInstruction*>(sim_->get_pc()));
723 sim_->icount_++;
724 // Leave the debugger shell.
725 done = true;
726 } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) {
727 if (argc == 2 || (argc == 3 && strcmp(arg2, "fp") == 0)) {
728 int32_t value;
729 double dvalue;
730 if (strcmp(arg1, "all") == 0) {
731 for (uint32_t i = 0; i < Registers::Total; i++) {
732 value = getRegisterValue(i);
733 printf("%3s: 0x%08x %10d", Registers::GetName(i), value, value);
734 if ((argc == 3 && strcmp(arg2, "fp") == 0) && i < 8 &&
735 (i % 2) == 0) {
736 dvalue = getRegisterPairDoubleValue(i);
737 printf(" (%.16g)\n", dvalue);
738 } else {
739 printf("\n");
740 }
741 }
742 for (uint32_t i = 0; i < FloatRegisters::TotalPhys; i++) {
743 getVFPDoubleRegisterValue(i, &dvalue);
744 uint64_t as_words = mozilla::BitwiseCast<uint64_t>(dvalue);
745 printf("%3s: %.16g 0x%08x %08x\n",
746 FloatRegister::FromCode(i).name(), dvalue,
747 static_cast<uint32_t>(as_words >> 32),
748 static_cast<uint32_t>(as_words & 0xffffffff));
749 }
750 } else {
751 if (getValue(arg1, &value)) {
752 printf("%s: 0x%08x %d \n", arg1, value, value);
753 } else if (getVFPDoubleValue(arg1, &dvalue)) {
754 uint64_t as_words = mozilla::BitwiseCast<uint64_t>(dvalue);
755 printf("%s: %.16g 0x%08x %08x\n", arg1, dvalue,
756 static_cast<uint32_t>(as_words >> 32),
757 static_cast<uint32_t>(as_words & 0xffffffff));
758 } else {
759 printf("%s unrecognized\n", arg1);
760 }
761 }
762 } else {
763 printf("print <register>\n");
764 }
765 } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) {
766 int32_t* cur = nullptr;
767 int32_t* end = nullptr;
768 int next_arg = 1;
769
770 if (strcmp(cmd, "stack") == 0) {
771 cur = reinterpret_cast<int32_t*>(sim_->get_register(Simulator::sp));
772 } else { // "mem"
773 int32_t value;
774 if (!getValue(arg1, &value)) {
775 printf("%s unrecognized\n", arg1);
776 continue;
777 }
778 cur = reinterpret_cast<int32_t*>(value);
779 next_arg++;
780 }
781
782 int32_t words;
783 if (argc == next_arg) {
784 words = 10;
785 } else {
786 if (!getValue(argv[next_arg], &words)) {
787 words = 10;
788 }
789 }
790 end = cur + words;
791
792 while (cur < end) {
793 printf(" %p: 0x%08x %10d", cur, *cur, *cur);
794 printf("\n");
795 cur++;
796 }
797 } else if (strcmp(cmd, "disasm") == 0 || strcmp(cmd, "di") == 0) {
798 #ifdef JS_DISASM_ARM
799 uint8_t* prev = nullptr;
800 uint8_t* cur = nullptr;
801 uint8_t* end = nullptr;
802
803 if (argc == 1) {
804 cur = reinterpret_cast<uint8_t*>(sim_->get_pc());
805 end = cur + (10 * SimInstruction::kInstrSize);
806 } else if (argc == 2) {
807 Register reg = Register::FromName(arg1);
808 if (reg != InvalidReg || strncmp(arg1, "0x", 2) == 0) {
809 // The argument is an address or a register name.
810 int32_t value;
811 if (getValue(arg1, &value)) {
812 cur = reinterpret_cast<uint8_t*>(value);
813 // Disassemble 10 instructions at <arg1>.
814 end = cur + (10 * SimInstruction::kInstrSize);
815 }
816 } else {
817 // The argument is the number of instructions.
818 int32_t value;
819 if (getValue(arg1, &value)) {
820 cur = reinterpret_cast<uint8_t*>(sim_->get_pc());
821 // Disassemble <arg1> instructions.
822 end = cur + (value * SimInstruction::kInstrSize);
823 }
824 }
825 } else {
826 int32_t value1;
827 int32_t value2;
828 if (getValue(arg1, &value1) && getValue(arg2, &value2)) {
829 cur = reinterpret_cast<uint8_t*>(value1);
830 end = cur + (value2 * SimInstruction::kInstrSize);
831 }
832 }
833 while (cur < end) {
834 disasm::NameConverter converter;
835 disasm::Disassembler dasm(converter);
836 disasm::EmbeddedVector<char, disasm::ReasonableBufferSize> buffer;
837
838 prev = cur;
839 cur += dasm.InstructionDecode(buffer, cur);
840 printf(" 0x%08x %s\n", reinterpret_cast<uint32_t>(prev),
841 buffer.start());
842 }
843 #endif
844 } else if (strcmp(cmd, "gdb") == 0) {
845 printf("relinquishing control to gdb\n");
846 #ifdef _MSC_VER
847 __debugbreak();
848 #else
849 asm("int $3");
850 #endif
851 printf("regaining control from gdb\n");
852 } else if (strcmp(cmd, "break") == 0) {
853 if (argc == 2) {
854 int32_t value;
855 if (getValue(arg1, &value)) {
856 if (!setBreakpoint(reinterpret_cast<SimInstruction*>(value))) {
857 printf("setting breakpoint failed\n");
858 }
859 } else {
860 printf("%s unrecognized\n", arg1);
861 }
862 } else {
863 printf("break <address>\n");
864 }
865 } else if (strcmp(cmd, "del") == 0) {
866 if (!deleteBreakpoint(nullptr)) {
867 printf("deleting breakpoint failed\n");
868 }
869 } else if (strcmp(cmd, "flags") == 0) {
870 printf("N flag: %d; ", sim_->n_flag_);
871 printf("Z flag: %d; ", sim_->z_flag_);
872 printf("C flag: %d; ", sim_->c_flag_);
873 printf("V flag: %d\n", sim_->v_flag_);
874 printf("INVALID OP flag: %d; ", sim_->inv_op_vfp_flag_);
875 printf("DIV BY ZERO flag: %d; ", sim_->div_zero_vfp_flag_);
876 printf("OVERFLOW flag: %d; ", sim_->overflow_vfp_flag_);
877 printf("UNDERFLOW flag: %d; ", sim_->underflow_vfp_flag_);
878 printf("INEXACT flag: %d;\n", sim_->inexact_vfp_flag_);
879 } else if (strcmp(cmd, "stop") == 0) {
880 int32_t value;
881 intptr_t stop_pc = sim_->get_pc() - 2 * SimInstruction::kInstrSize;
882 SimInstruction* stop_instr = reinterpret_cast<SimInstruction*>(stop_pc);
883 SimInstruction* msg_address = reinterpret_cast<SimInstruction*>(
884 stop_pc + SimInstruction::kInstrSize);
885 if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) {
886 // Remove the current stop.
887 if (sim_->isStopInstruction(stop_instr)) {
888 stop_instr->setInstructionBits(kNopInstr);
889 msg_address->setInstructionBits(kNopInstr);
890 } else {
891 printf("Not at debugger stop.\n");
892 }
893 } else if (argc == 3) {
894 // Print information about all/the specified breakpoint(s).
895 if (strcmp(arg1, "info") == 0) {
896 if (strcmp(arg2, "all") == 0) {
897 printf("Stop information:\n");
898 for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) {
899 sim_->printStopInfo(i);
900 }
901 } else if (getValue(arg2, &value)) {
902 sim_->printStopInfo(value);
903 } else {
904 printf("Unrecognized argument.\n");
905 }
906 } else if (strcmp(arg1, "enable") == 0) {
907 // Enable all/the specified breakpoint(s).
908 if (strcmp(arg2, "all") == 0) {
909 for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) {
910 sim_->enableStop(i);
911 }
912 } else if (getValue(arg2, &value)) {
913 sim_->enableStop(value);
914 } else {
915 printf("Unrecognized argument.\n");
916 }
917 } else if (strcmp(arg1, "disable") == 0) {
918 // Disable all/the specified breakpoint(s).
919 if (strcmp(arg2, "all") == 0) {
920 for (uint32_t i = 0; i < sim_->kNumOfWatchedStops; i++) {
921 sim_->disableStop(i);
922 }
923 } else if (getValue(arg2, &value)) {
924 sim_->disableStop(value);
925 } else {
926 printf("Unrecognized argument.\n");
927 }
928 }
929 } else {
930 printf("Wrong usage. Use help command for more information.\n");
931 }
932 } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) {
933 printf("cont\n");
934 printf(" continue execution (alias 'c')\n");
935 printf("skip\n");
936 printf(" skip one instruction (set pc to next instruction)\n");
937 printf("stepi\n");
938 printf(" step one instruction (alias 'si')\n");
939 printf("print <register>\n");
940 printf(" print register content (alias 'p')\n");
941 printf(" use register name 'all' to print all registers\n");
942 printf(" add argument 'fp' to print register pair double values\n");
943 printf("flags\n");
944 printf(" print flags\n");
945 printf("stack [<words>]\n");
946 printf(" dump stack content, default dump 10 words)\n");
947 printf("mem <address> [<words>]\n");
948 printf(" dump memory content, default dump 10 words)\n");
949 printf("disasm [<instructions>]\n");
950 printf("disasm [<address/register>]\n");
951 printf("disasm [[<address/register>] <instructions>]\n");
952 printf(" disassemble code, default is 10 instructions\n");
953 printf(" from pc (alias 'di')\n");
954 printf("gdb\n");
955 printf(" enter gdb\n");
956 printf("break <address>\n");
957 printf(" set a break point on the address\n");
958 printf("del\n");
959 printf(" delete the breakpoint\n");
960 printf("stop feature:\n");
961 printf(" Description:\n");
962 printf(" Stops are debug instructions inserted by\n");
963 printf(" the Assembler::stop() function.\n");
964 printf(" When hitting a stop, the Simulator will\n");
965 printf(" stop and and give control to the ArmDebugger.\n");
966 printf(" The first %d stop codes are watched:\n",
967 Simulator::kNumOfWatchedStops);
968 printf(" - They can be enabled / disabled: the Simulator\n");
969 printf(" will / won't stop when hitting them.\n");
970 printf(" - The Simulator keeps track of how many times they \n");
971 printf(" are met. (See the info command.) Going over a\n");
972 printf(" disabled stop still increases its counter. \n");
973 printf(" Commands:\n");
974 printf(" stop info all/<code> : print infos about number <code>\n");
975 printf(" or all stop(s).\n");
976 printf(" stop enable/disable all/<code> : enables / disables\n");
977 printf(" all or number <code> stop(s)\n");
978 printf(" stop unstop\n");
979 printf(" ignore the stop instruction at the current location\n");
980 printf(" from now on\n");
981 } else {
982 printf("Unknown command: %s\n", cmd);
983 }
984 }
985 }
986
987 // Add all the breakpoints back to stop execution and enter the debugger
988 // shell when hit.
989 redoBreakpoints();
990
991 #undef COMMAND_SIZE
992 #undef ARG_SIZE
993
994 #undef STR
995 #undef XSTR
996 }
997
998 static bool AllOnOnePage(uintptr_t start, int size) {
999 intptr_t start_page = (start & ~CachePage::kPageMask);
1000 intptr_t end_page = ((start + size) & ~CachePage::kPageMask);
1001 return start_page == end_page;
1002 }
1003
1004 static CachePage* GetCachePageLocked(SimulatorProcess::ICacheMap& i_cache,
1005 void* page) {
1006 SimulatorProcess::ICacheMap::AddPtr p = i_cache.lookupForAdd(page);
1007 if (p) {
1008 return p->value();
1009 }
1010
1011 AutoEnterOOMUnsafeRegion oomUnsafe;
1012 CachePage* new_page = js_new<CachePage>();
1013 if (!new_page || !i_cache.add(p, page, new_page)) {
1014 oomUnsafe.crash("Simulator CachePage");
1015 }
1016
1017 return new_page;
1018 }
1019
1020 // Flush from start up to and not including start + size.
1021 static void FlushOnePageLocked(SimulatorProcess::ICacheMap& i_cache,
1022 intptr_t start, int size) {
1023 MOZ_ASSERT(size <= CachePage::kPageSize);
1024 MOZ_ASSERT(AllOnOnePage(start, size - 1));
1025 MOZ_ASSERT((start & CachePage::kLineMask) == 0);
1026 MOZ_ASSERT((size & CachePage::kLineMask) == 0);
1027
1028 void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask));
1029 int offset = (start & CachePage::kPageMask);
1030 CachePage* cache_page = GetCachePageLocked(i_cache, page);
1031 char* valid_bytemap = cache_page->validityByte(offset);
1032 memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift);
1033 }
1034
1035 static void FlushICacheLocked(SimulatorProcess::ICacheMap& i_cache,
1036 void* start_addr, size_t size) {
1037 intptr_t start = reinterpret_cast<intptr_t>(start_addr);
1038 int intra_line = (start & CachePage::kLineMask);
1039 start -= intra_line;
1040 size += intra_line;
1041 size = ((size - 1) | CachePage::kLineMask) + 1;
1042 int offset = (start & CachePage::kPageMask);
1043 while (!AllOnOnePage(start, size - 1)) {
1044 int bytes_to_flush = CachePage::kPageSize - offset;
1045 FlushOnePageLocked(i_cache, start, bytes_to_flush);
1046 start += bytes_to_flush;
1047 size -= bytes_to_flush;
1048 MOZ_ASSERT((start & CachePage::kPageMask) == 0);
1049 offset = 0;
1050 }
1051 if (size != 0) {
1052 FlushOnePageLocked(i_cache, start, size);
1053 }
1054 }
1055
1056 /* static */
1057 void SimulatorProcess::checkICacheLocked(SimInstruction* instr) {
1058 intptr_t address = reinterpret_cast<intptr_t>(instr);
1059 void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask));
1060 void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask));
1061 int offset = (address & CachePage::kPageMask);
1062 CachePage* cache_page = GetCachePageLocked(icache(), page);
1063 char* cache_valid_byte = cache_page->validityByte(offset);
1064 bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID);
1065 char* cached_line = cache_page->cachedData(offset & ~CachePage::kLineMask);
1066
1067 if (cache_hit) {
1068 // Check that the data in memory matches the contents of the I-cache.
1069 mozilla::DebugOnly<int> cmpret =
1070 memcmp(reinterpret_cast<void*>(instr), cache_page->cachedData(offset),
1071 SimInstruction::kInstrSize);
1072 MOZ_ASSERT(cmpret == 0);
1073 } else {
1074 // Cache miss. Load memory into the cache.
1075 memcpy(cached_line, line, CachePage::kLineLength);
1076 *cache_valid_byte = CachePage::LINE_VALID;
1077 }
1078 }
1079
1080 HashNumber SimulatorProcess::ICacheHasher::hash(const Lookup& l) {
1081 return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(l)) >> 2;
1082 }
1083
1084 bool SimulatorProcess::ICacheHasher::match(const Key& k, const Lookup& l) {
1085 MOZ_ASSERT((reinterpret_cast<intptr_t>(k) & CachePage::kPageMask) == 0);
1086 MOZ_ASSERT((reinterpret_cast<intptr_t>(l) & CachePage::kPageMask) == 0);
1087 return k == l;
1088 }
1089
1090 void Simulator::setLastDebuggerInput(char* input) {
1091 js_free(lastDebuggerInput_);
1092 lastDebuggerInput_ = input;
1093 }
1094
1095 /* static */
1096 void SimulatorProcess::FlushICache(void* start_addr, size_t size) {
1097 JitSpewCont(JitSpew_CacheFlush, "[%p %zx]", start_addr, size);
1098 if (!ICacheCheckingDisableCount) {
1099 AutoLockSimulatorCache als;
1100 js::jit::FlushICacheLocked(icache(), start_addr, size);
1101 }
1102 }
1103
1104 Simulator::Simulator() {
1105 // Set up simulator support first. Some of this information is needed to
1106 // setup the architecture state.
1107
1108 // Note, allocation and anything that depends on allocated memory is
1109 // deferred until init(), in order to handle OOM properly.
1110
1111 stack_ = nullptr;
1112 stackLimit_ = 0;
1113 pc_modified_ = false;
1114 icount_ = 0L;
1115 break_pc_ = nullptr;
1116 break_instr_ = 0;
1117 single_stepping_ = false;
1118 single_step_callback_ = nullptr;
1119 single_step_callback_arg_ = nullptr;
1120 skipCalleeSavedRegsCheck = false;
1121
1122 // Set up architecture state.
1123 // All registers are initialized to zero to start with.
1124 for (int i = 0; i < num_registers; i++) {
1125 registers_[i] = 0;
1126 }
1127
1128 n_flag_ = false;
1129 z_flag_ = false;
1130 c_flag_ = false;
1131 v_flag_ = false;
1132
1133 for (int i = 0; i < num_d_registers * 2; i++) {
1134 vfp_registers_[i] = 0;
1135 }
1136
1137 n_flag_FPSCR_ = false;
1138 z_flag_FPSCR_ = false;
1139 c_flag_FPSCR_ = false;
1140 v_flag_FPSCR_ = false;
1141 FPSCR_rounding_mode_ = SimRZ;
1142 FPSCR_default_NaN_mode_ = true;
1143
1144 inv_op_vfp_flag_ = false;
1145 div_zero_vfp_flag_ = false;
1146 overflow_vfp_flag_ = false;
1147 underflow_vfp_flag_ = false;
1148 inexact_vfp_flag_ = false;
1149
1150 // The lr and pc are initialized to a known bad value that will cause an
1151 // access violation if the simulator ever tries to execute it.
1152 registers_[pc] = bad_lr;
1153 registers_[lr] = bad_lr;
1154
1155 lastDebuggerInput_ = nullptr;
1156
1157 exclusiveMonitorHeld_ = false;
1158 exclusiveMonitor_ = 0;
1159 }
1160
1161 bool Simulator::init() {
1162 // Allocate 2MB for the stack. Note that we will only use 1MB, see below.
1163 static const size_t stackSize = 2 * 1024 * 1024;
1164 stack_ = js_pod_malloc<char>(stackSize);
1165 if (!stack_) {
1166 return false;
1167 }
1168
1169 // Leave a safety margin of 1MB to prevent overrunning the stack when
1170 // pushing values (total stack size is 2MB).
1171 stackLimit_ = reinterpret_cast<uintptr_t>(stack_) + 1024 * 1024;
1172
1173 // The sp is initialized to point to the bottom (high address) of the
1174 // allocated stack area. To be safe in potential stack underflows we leave
1175 // some buffer below.
1176 registers_[sp] = reinterpret_cast<int32_t>(stack_) + stackSize - 64;
1177
1178 return true;
1179 }
1180
1181 // When the generated code calls a VM function (masm.callWithABI) we need to
1182 // call that function instead of trying to execute it with the simulator
1183 // (because it's x86 code instead of arm code). We do that by redirecting the VM
1184 // call to a svc (Supervisor Call) instruction that is handled by the
1185 // simulator. We write the original destination of the jump just at a known
1186 // offset from the svc instruction so the simulator knows what to call.
1187 class Redirection {
1188 friend class SimulatorProcess;
1189
1190 // sim's lock must already be held.
1191 Redirection(void* nativeFunction, ABIFunctionType type)
1192 : nativeFunction_(nativeFunction),
1193 swiInstruction_(Assembler::AL | (0xf * (1 << 24)) | kCallRtRedirected),
1194 type_(type),
1195 next_(nullptr) {
1196 next_ = SimulatorProcess::redirection();
1197 if (!SimulatorProcess::ICacheCheckingDisableCount) {
1198 FlushICacheLocked(SimulatorProcess::icache(), addressOfSwiInstruction(),
1199 SimInstruction::kInstrSize);
1200 }
1201 SimulatorProcess::setRedirection(this);
1202 }
1203
1204 public:
1205 void* addressOfSwiInstruction() { return &swiInstruction_; }
1206 void* nativeFunction() const { return nativeFunction_; }
1207 ABIFunctionType type() const { return type_; }
1208
1209 static Redirection* Get(void* nativeFunction, ABIFunctionType type) {
1210 AutoLockSimulatorCache als;
1211
1212 Redirection* current = SimulatorProcess::redirection();
1213 for (; current != nullptr; current = current->next_) {
1214 if (current->nativeFunction_ == nativeFunction) {
1215 MOZ_ASSERT(current->type() == type);
1216 return current;
1217 }
1218 }
1219
1220 // Note: we can't use js_new here because the constructor is private.
1221 AutoEnterOOMUnsafeRegion oomUnsafe;
1222 Redirection* redir = js_pod_malloc<Redirection>(1);
1223 if (!redir) {
1224 oomUnsafe.crash("Simulator redirection");
1225 }
1226 new (redir) Redirection(nativeFunction, type);
1227 return redir;
1228 }
1229
1230 static Redirection* FromSwiInstruction(SimInstruction* swiInstruction) {
1231 uint8_t* addrOfSwi = reinterpret_cast<uint8_t*>(swiInstruction);
1232 uint8_t* addrOfRedirection =
1233 addrOfSwi - offsetof(Redirection, swiInstruction_);
1234 return reinterpret_cast<Redirection*>(addrOfRedirection);
1235 }
1236
1237 private:
1238 void* nativeFunction_;
1239 uint32_t swiInstruction_;
1240 ABIFunctionType type_;
1241 Redirection* next_;
1242 };
1243
1244 Simulator::~Simulator() { js_free(stack_); }
1245
1246 SimulatorProcess::SimulatorProcess()
1247 : cacheLock_(mutexid::SimulatorCacheLock), redirection_(nullptr) {
1248 if (getenv("ARM_SIM_ICACHE_CHECKS")) {
1249 ICacheCheckingDisableCount = 0;
1250 }
1251 }
1252
1253 SimulatorProcess::~SimulatorProcess() {
1254 Redirection* r = redirection_;
1255 while (r) {
1256 Redirection* next = r->next_;
1257 js_delete(r);
1258 r = next;
1259 }
1260 }
1261
1262 /* static */
1263 void* Simulator::RedirectNativeFunction(void* nativeFunction,
1264 ABIFunctionType type) {
1265 Redirection* redirection = Redirection::Get(nativeFunction, type);
1266 return redirection->addressOfSwiInstruction();
1267 }
1268
1269 // Sets the register in the architecture state. It will also deal with updating
1270 // Simulator internal state for special registers such as PC.
1271 void Simulator::set_register(int reg, int32_t value) {
1272 MOZ_ASSERT(reg >= 0 && reg < num_registers);
1273 if (reg == pc) {
1274 pc_modified_ = true;
1275 }
1276 registers_[reg] = value;
1277 }
1278
1279 // Get the register from the architecture state. This function does handle the
1280 // special case of accessing the PC register.
1281 int32_t Simulator::get_register(int reg) const {
1282 MOZ_ASSERT(reg >= 0 && reg < num_registers);
1283 // Work around GCC bug: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43949
1284 if (reg >= num_registers) return 0;
1285 return registers_[reg] + ((reg == pc) ? SimInstruction::kPCReadOffset : 0);
1286 }
1287
1288 double Simulator::get_double_from_register_pair(int reg) {
1289 MOZ_ASSERT(reg >= 0 && reg < num_registers && (reg % 2) == 0);
1290
1291 // Read the bits from the unsigned integer register_[] array into the double
1292 // precision floating point value and return it.
1293 double dm_val = 0.0;
1294 char buffer[2 * sizeof(vfp_registers_[0])];
1295 memcpy(buffer, &registers_[reg], 2 * sizeof(registers_[0]));
1296 memcpy(&dm_val, buffer, 2 * sizeof(registers_[0]));
1297 return dm_val;
1298 }
1299
1300 void Simulator::set_register_pair_from_double(int reg, double* value) {
1301 MOZ_ASSERT(reg >= 0 && reg < num_registers && (reg % 2) == 0);
1302 memcpy(registers_ + reg, value, sizeof(*value));
1303 }
1304
1305 void Simulator::set_dw_register(int dreg, const int* dbl) {
1306 MOZ_ASSERT(dreg >= 0 && dreg < num_d_registers);
1307 registers_[dreg] = dbl[0];
1308 registers_[dreg + 1] = dbl[1];
1309 }
1310
1311 void Simulator::get_d_register(int dreg, uint64_t* value) {
1312 MOZ_ASSERT(dreg >= 0 && dreg < int(FloatRegisters::TotalPhys));
1313 memcpy(value, vfp_registers_ + dreg * 2, sizeof(*value));
1314 }
1315
1316 void Simulator::set_d_register(int dreg, const uint64_t* value) {
1317 MOZ_ASSERT(dreg >= 0 && dreg < int(FloatRegisters::TotalPhys));
1318 memcpy(vfp_registers_ + dreg * 2, value, sizeof(*value));
1319 }
1320
1321 void Simulator::get_d_register(int dreg, uint32_t* value) {
1322 MOZ_ASSERT(dreg >= 0 && dreg < int(FloatRegisters::TotalPhys));
1323 memcpy(value, vfp_registers_ + dreg * 2, sizeof(*value) * 2);
1324 }
1325
1326 void Simulator::set_d_register(int dreg, const uint32_t* value) {
1327 MOZ_ASSERT(dreg >= 0 && dreg < int(FloatRegisters::TotalPhys));
1328 memcpy(vfp_registers_ + dreg * 2, value, sizeof(*value) * 2);
1329 }
1330
1331 void Simulator::get_q_register(int qreg, uint64_t* value) {
1332 MOZ_ASSERT(qreg >= 0 && qreg < num_q_registers);
1333 memcpy(value, vfp_registers_ + qreg * 4, sizeof(*value) * 2);
1334 }
1335
1336 void Simulator::set_q_register(int qreg, const uint64_t* value) {
1337 MOZ_ASSERT(qreg >= 0 && qreg < num_q_registers);
1338 memcpy(vfp_registers_ + qreg * 4, value, sizeof(*value) * 2);
1339 }
1340
1341 void Simulator::get_q_register(int qreg, uint32_t* value) {
1342 MOZ_ASSERT(qreg >= 0 && qreg < num_q_registers);
1343 memcpy(value, vfp_registers_ + qreg * 4, sizeof(*value) * 4);
1344 }
1345
1346 void Simulator::set_q_register(int qreg, const uint32_t* value) {
1347 MOZ_ASSERT((qreg >= 0) && (qreg < num_q_registers));
1348 memcpy(vfp_registers_ + qreg * 4, value, sizeof(*value) * 4);
1349 }
1350
1351 void Simulator::set_pc(int32_t value) {
1352 pc_modified_ = true;
1353 registers_[pc] = value;
1354 }
1355
1356 bool Simulator::has_bad_pc() const {
1357 return registers_[pc] == bad_lr || registers_[pc] == end_sim_pc;
1358 }
1359
1360 // Raw access to the PC register without the special adjustment when reading.
1361 int32_t Simulator::get_pc() const { return registers_[pc]; }
1362
1363 void Simulator::set_s_register(int sreg, unsigned int value) {
1364 MOZ_ASSERT(sreg >= 0 && sreg < num_s_registers);
1365 vfp_registers_[sreg] = value;
1366 }
1367
1368 unsigned Simulator::get_s_register(int sreg) const {
1369 MOZ_ASSERT(sreg >= 0 && sreg < num_s_registers);
1370 return vfp_registers_[sreg];
1371 }
1372
1373 template <class InputType, int register_size>
1374 void Simulator::setVFPRegister(int reg_index, const InputType& value) {
1375 MOZ_ASSERT(reg_index >= 0);
1376 MOZ_ASSERT_IF(register_size == 1, reg_index < num_s_registers);
1377 MOZ_ASSERT_IF(register_size == 2, reg_index < int(FloatRegisters::TotalPhys));
1378
1379 char buffer[register_size * sizeof(vfp_registers_[0])];
1380 memcpy(buffer, &value, register_size * sizeof(vfp_registers_[0]));
1381 memcpy(&vfp_registers_[reg_index * register_size], buffer,
1382 register_size * sizeof(vfp_registers_[0]));
1383 }
1384
1385 template <class ReturnType, int register_size>
1386 void Simulator::getFromVFPRegister(int reg_index, ReturnType* out) {
1387 MOZ_ASSERT(reg_index >= 0);
1388 MOZ_ASSERT_IF(register_size == 1, reg_index < num_s_registers);
1389 MOZ_ASSERT_IF(register_size == 2, reg_index < int(FloatRegisters::TotalPhys));
1390
1391 char buffer[register_size * sizeof(vfp_registers_[0])];
1392 memcpy(buffer, &vfp_registers_[register_size * reg_index],
1393 register_size * sizeof(vfp_registers_[0]));
1394 memcpy(out, buffer, register_size * sizeof(vfp_registers_[0]));
1395 }
1396
1397 // These forced-instantiations are for jsapi-tests. Evidently, nothing
1398 // requires these to be instantiated.
1399 template void Simulator::getFromVFPRegister<double, 2>(int reg_index,
1400 double* out);
1401 template void Simulator::getFromVFPRegister<float, 1>(int reg_index,
1402 float* out);
1403 template void Simulator::setVFPRegister<double, 2>(int reg_index,
1404 const double& value);
1405 template void Simulator::setVFPRegister<float, 1>(int reg_index,
1406 const float& value);
1407
1408 void Simulator::getFpArgs(double* x, double* y, int32_t* z) {
1409 if (ARMFlags::UseHardFpABI()) {
1410 get_double_from_d_register(0, x);
1411 get_double_from_d_register(1, y);
1412 *z = get_register(0);
1413 } else {
1414 *x = get_double_from_register_pair(0);
1415 *y = get_double_from_register_pair(2);
1416 *z = get_register(2);
1417 }
1418 }
1419
1420 void Simulator::getFpFromStack(int32_t* stack, double* x) {
1421 MOZ_ASSERT(stack && x);
1422 char buffer[2 * sizeof(stack[0])];
1423 memcpy(buffer, stack, 2 * sizeof(stack[0]));
1424 memcpy(x, buffer, 2 * sizeof(stack[0]));
1425 }
1426
1427 void Simulator::setCallResultDouble(double result) {
1428 // The return value is either in r0/r1 or d0.
1429 if (ARMFlags::UseHardFpABI()) {
1430 char buffer[2 * sizeof(vfp_registers_[0])];
1431 memcpy(buffer, &result, sizeof(buffer));
1432 // Copy result to d0.
1433 memcpy(vfp_registers_, buffer, sizeof(buffer));
1434 } else {
1435 char buffer[2 * sizeof(registers_[0])];
1436 memcpy(buffer, &result, sizeof(buffer));
1437 // Copy result to r0 and r1.
1438 memcpy(registers_, buffer, sizeof(buffer));
1439 }
1440 }
1441
1442 void Simulator::setCallResultFloat(float result) {
1443 if (ARMFlags::UseHardFpABI()) {
1444 char buffer[sizeof(registers_[0])];
1445 memcpy(buffer, &result, sizeof(buffer));
1446 // Copy result to s0.
1447 memcpy(vfp_registers_, buffer, sizeof(buffer));
1448 } else {
1449 char buffer[sizeof(registers_[0])];
1450 memcpy(buffer, &result, sizeof(buffer));
1451 // Copy result to r0.
1452 memcpy(registers_, buffer, sizeof(buffer));
1453 }
1454 }
1455
1456 void Simulator::setCallResult(int64_t res) {
1457 set_register(r0, static_cast<int32_t>(res));
1458 set_register(r1, static_cast<int32_t>(res >> 32));
1459 }
1460
1461 void Simulator::exclusiveMonitorSet(uint64_t value) {
1462 exclusiveMonitor_ = value;
1463 exclusiveMonitorHeld_ = true;
1464 }
1465
1466 uint64_t Simulator::exclusiveMonitorGetAndClear(bool* held) {
1467 *held = exclusiveMonitorHeld_;
1468 exclusiveMonitorHeld_ = false;
1469 return *held ? exclusiveMonitor_ : 0;
1470 }
1471
1472 void Simulator::exclusiveMonitorClear() { exclusiveMonitorHeld_ = false; }
1473
1474 JS::ProfilingFrameIterator::RegisterState Simulator::registerState() {
1475 wasm::RegisterState state;
1476 state.pc = (void*)get_pc();
1477 state.fp = (void*)get_register(fp);
1478 state.sp = (void*)get_register(sp);
1479 state.lr = (void*)get_register(lr);
1480 return state;
1481 }
1482
1483 uint64_t Simulator::readQ(int32_t addr, SimInstruction* instr,
1484 UnalignedPolicy f) {
1485 if (handleWasmSegFault(addr, 8)) {
1486 return UINT64_MAX;
1487 }
1488
1489 if ((addr & 3) == 0 ||
1490 (f == AllowUnaligned && !ARMFlags::HasAlignmentFault())) {
1491 uint64_t* ptr = reinterpret_cast<uint64_t*>(addr);
1492 return *ptr;
1493 }
1494
1495 // See the comments below in readW.
1496 if (ARMFlags::FixupFault() &&
1497 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1498 char* ptr = reinterpret_cast<char*>(addr);
1499 uint64_t value;
1500 memcpy(&value, ptr, sizeof(value));
1501 return value;
1502 }
1503
1504 printf("Unaligned read at 0x%08x, pc=%p\n", addr, instr);
1505 MOZ_CRASH();
1506 }
1507
1508 void Simulator::writeQ(int32_t addr, uint64_t value, SimInstruction* instr,
1509 UnalignedPolicy f) {
1510 if (handleWasmSegFault(addr, 8)) {
1511 return;
1512 }
1513
1514 if ((addr & 3) == 0 ||
1515 (f == AllowUnaligned && !ARMFlags::HasAlignmentFault())) {
1516 uint64_t* ptr = reinterpret_cast<uint64_t*>(addr);
1517 *ptr = value;
1518 return;
1519 }
1520
1521 // See the comments below in readW.
1522 if (ARMFlags::FixupFault() &&
1523 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1524 char* ptr = reinterpret_cast<char*>(addr);
1525 memcpy(ptr, &value, sizeof(value));
1526 return;
1527 }
1528
1529 printf("Unaligned write at 0x%08x, pc=%p\n", addr, instr);
1530 MOZ_CRASH();
1531 }
1532
1533 int Simulator::readW(int32_t addr, SimInstruction* instr, UnalignedPolicy f) {
1534 if (handleWasmSegFault(addr, 4)) {
1535 return -1;
1536 }
1537
1538 if ((addr & 3) == 0 ||
1539 (f == AllowUnaligned && !ARMFlags::HasAlignmentFault())) {
1540 intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
1541 return *ptr;
1542 }
1543
1544 // In WebAssembly, we want unaligned accesses to either raise a signal or
1545 // do the right thing. Making this simulator properly emulate the behavior
1546 // of raising a signal is complex, so as a special-case, when in wasm code,
1547 // we just do the right thing.
1548 if (ARMFlags::FixupFault() &&
1549 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1550 char* ptr = reinterpret_cast<char*>(addr);
1551 int value;
1552 memcpy(&value, ptr, sizeof(value));
1553 return value;
1554 }
1555
1556 printf("Unaligned read at 0x%08x, pc=%p\n", addr, instr);
1557 MOZ_CRASH();
1558 }
1559
1560 void Simulator::writeW(int32_t addr, int value, SimInstruction* instr,
1561 UnalignedPolicy f) {
1562 if (handleWasmSegFault(addr, 4)) {
1563 return;
1564 }
1565
1566 if ((addr & 3) == 0 ||
1567 (f == AllowUnaligned && !ARMFlags::HasAlignmentFault())) {
1568 intptr_t* ptr = reinterpret_cast<intptr_t*>(addr);
1569 *ptr = value;
1570 return;
1571 }
1572
1573 // See the comments above in readW.
1574 if (ARMFlags::FixupFault() &&
1575 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1576 char* ptr = reinterpret_cast<char*>(addr);
1577 memcpy(ptr, &value, sizeof(value));
1578 return;
1579 }
1580
1581 printf("Unaligned write at 0x%08x, pc=%p\n", addr, instr);
1582 MOZ_CRASH();
1583 }
1584
1585 // For the time being, define Relaxed operations in terms of SeqCst
1586 // operations - we don't yet need Relaxed operations anywhere else in
1587 // the system, and the distinction is not important to the simulation
1588 // at the level where we're operating.
1589
1590 template <typename T>
1591 static T loadRelaxed(SharedMem<T*> addr) {
1592 return AtomicOperations::loadSeqCst(addr);
1593 }
1594
1595 template <typename T>
1596 static T compareExchangeRelaxed(SharedMem<T*> addr, T oldval, T newval) {
1597 return AtomicOperations::compareExchangeSeqCst(addr, oldval, newval);
1598 }
1599
1600 int Simulator::readExW(int32_t addr, SimInstruction* instr) {
1601 if (addr & 3) {
1602 MOZ_CRASH("Unaligned exclusive read");
1603 }
1604
1605 if (handleWasmSegFault(addr, 4)) {
1606 return -1;
1607 }
1608
1609 SharedMem<int32_t*> ptr =
1610 SharedMem<int32_t*>::shared(reinterpret_cast<int32_t*>(addr));
1611 int32_t value = loadRelaxed(ptr);
1612 exclusiveMonitorSet(value);
1613 return value;
1614 }
1615
1616 int32_t Simulator::writeExW(int32_t addr, int value, SimInstruction* instr) {
1617 if (addr & 3) {
1618 MOZ_CRASH("Unaligned exclusive write");
1619 }
1620
1621 if (handleWasmSegFault(addr, 4)) {
1622 return -1;
1623 }
1624
1625 SharedMem<int32_t*> ptr =
1626 SharedMem<int32_t*>::shared(reinterpret_cast<int32_t*>(addr));
1627 bool held;
1628 int32_t expected = int32_t(exclusiveMonitorGetAndClear(&held));
1629 if (!held) {
1630 return 1;
1631 }
1632 int32_t old = compareExchangeRelaxed(ptr, expected, int32_t(value));
1633 return old != expected;
1634 }
1635
1636 uint16_t Simulator::readHU(int32_t addr, SimInstruction* instr) {
1637 if (handleWasmSegFault(addr, 2)) {
1638 return UINT16_MAX;
1639 }
1640
1641 // The regexp engine emits unaligned loads, so we don't check for them here
1642 // like most of the other methods do.
1643 if ((addr & 1) == 0 || !ARMFlags::HasAlignmentFault()) {
1644 uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1645 return *ptr;
1646 }
1647
1648 // See comments above in readW.
1649 if (ARMFlags::FixupFault() &&
1650 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1651 char* ptr = reinterpret_cast<char*>(addr);
1652 uint16_t value;
1653 memcpy(&value, ptr, sizeof(value));
1654 return value;
1655 }
1656
1657 printf("Unaligned unsigned halfword read at 0x%08x, pc=%p\n", addr, instr);
1658 MOZ_CRASH();
1659 return 0;
1660 }
1661
1662 int16_t Simulator::readH(int32_t addr, SimInstruction* instr) {
1663 if (handleWasmSegFault(addr, 2)) {
1664 return -1;
1665 }
1666
1667 if ((addr & 1) == 0 || !ARMFlags::HasAlignmentFault()) {
1668 int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1669 return *ptr;
1670 }
1671
1672 // See comments above in readW.
1673 if (ARMFlags::FixupFault() &&
1674 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1675 char* ptr = reinterpret_cast<char*>(addr);
1676 int16_t value;
1677 memcpy(&value, ptr, sizeof(value));
1678 return value;
1679 }
1680
1681 printf("Unaligned signed halfword read at 0x%08x\n", addr);
1682 MOZ_CRASH();
1683 return 0;
1684 }
1685
1686 void Simulator::writeH(int32_t addr, uint16_t value, SimInstruction* instr) {
1687 if (handleWasmSegFault(addr, 2)) {
1688 return;
1689 }
1690
1691 if ((addr & 1) == 0 || !ARMFlags::HasAlignmentFault()) {
1692 uint16_t* ptr = reinterpret_cast<uint16_t*>(addr);
1693 *ptr = value;
1694 return;
1695 }
1696
1697 // See the comments above in readW.
1698 if (ARMFlags::FixupFault() &&
1699 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1700 char* ptr = reinterpret_cast<char*>(addr);
1701 memcpy(ptr, &value, sizeof(value));
1702 return;
1703 }
1704
1705 printf("Unaligned unsigned halfword write at 0x%08x, pc=%p\n", addr, instr);
1706 MOZ_CRASH();
1707 }
1708
1709 void Simulator::writeH(int32_t addr, int16_t value, SimInstruction* instr) {
1710 if (handleWasmSegFault(addr, 2)) {
1711 return;
1712 }
1713
1714 if ((addr & 1) == 0 || !ARMFlags::HasAlignmentFault()) {
1715 int16_t* ptr = reinterpret_cast<int16_t*>(addr);
1716 *ptr = value;
1717 return;
1718 }
1719
1720 // See the comments above in readW.
1721 if (ARMFlags::FixupFault() &&
1722 wasm::InCompiledCode(reinterpret_cast<void*>(get_pc()))) {
1723 char* ptr = reinterpret_cast<char*>(addr);
1724 memcpy(ptr, &value, sizeof(value));
1725 return;
1726 }
1727
1728 printf("Unaligned halfword write at 0x%08x, pc=%p\n", addr, instr);
1729 MOZ_CRASH();
1730 }
1731
1732 uint16_t Simulator::readExHU(int32_t addr, SimInstruction* instr) {
1733 if (addr & 1) {
1734 MOZ_CRASH("Unaligned exclusive read");
1735 }
1736
1737 if (handleWasmSegFault(addr, 2)) {
1738 return UINT16_MAX;
1739 }
1740
1741 SharedMem<uint16_t*> ptr =
1742 SharedMem<uint16_t*>::shared(reinterpret_cast<uint16_t*>(addr));
1743 uint16_t value = loadRelaxed(ptr);
1744 exclusiveMonitorSet(value);
1745 return value;
1746 }
1747
1748 int32_t Simulator::writeExH(int32_t addr, uint16_t value,
1749 SimInstruction* instr) {
1750 if (addr & 1) {
1751 MOZ_CRASH("Unaligned exclusive write");
1752 }
1753
1754 if (handleWasmSegFault(addr, 2)) {
1755 return -1;
1756 }
1757
1758 SharedMem<uint16_t*> ptr =
1759 SharedMem<uint16_t*>::shared(reinterpret_cast<uint16_t*>(addr));
1760 bool held;
1761 uint16_t expected = uint16_t(exclusiveMonitorGetAndClear(&held));
1762 if (!held) {
1763 return 1;
1764 }
1765 uint16_t old = compareExchangeRelaxed(ptr, expected, value);
1766 return old != expected;
1767 }
1768
1769 uint8_t Simulator::readBU(int32_t addr) {
1770 if (handleWasmSegFault(addr, 1)) {
1771 return UINT8_MAX;
1772 }
1773
1774 uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1775 return *ptr;
1776 }
1777
1778 uint8_t Simulator::readExBU(int32_t addr) {
1779 if (handleWasmSegFault(addr, 1)) {
1780 return UINT8_MAX;
1781 }
1782
1783 SharedMem<uint8_t*> ptr =
1784 SharedMem<uint8_t*>::shared(reinterpret_cast<uint8_t*>(addr));
1785 uint8_t value = loadRelaxed(ptr);
1786 exclusiveMonitorSet(value);
1787 return value;
1788 }
1789
1790 int32_t Simulator::writeExB(int32_t addr, uint8_t value) {
1791 if (handleWasmSegFault(addr, 1)) {
1792 return -1;
1793 }
1794
1795 SharedMem<uint8_t*> ptr =
1796 SharedMem<uint8_t*>::shared(reinterpret_cast<uint8_t*>(addr));
1797 bool held;
1798 uint8_t expected = uint8_t(exclusiveMonitorGetAndClear(&held));
1799 if (!held) {
1800 return 1;
1801 }
1802 uint8_t old = compareExchangeRelaxed(ptr, expected, value);
1803 return old != expected;
1804 }
1805
1806 int8_t Simulator::readB(int32_t addr) {
1807 if (handleWasmSegFault(addr, 1)) {
1808 return -1;
1809 }
1810
1811 int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1812 return *ptr;
1813 }
1814
1815 void Simulator::writeB(int32_t addr, uint8_t value) {
1816 if (handleWasmSegFault(addr, 1)) {
1817 return;
1818 }
1819
1820 uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
1821 *ptr = value;
1822 }
1823
1824 void Simulator::writeB(int32_t addr, int8_t value) {
1825 if (handleWasmSegFault(addr, 1)) {
1826 return;
1827 }
1828
1829 int8_t* ptr = reinterpret_cast<int8_t*>(addr);
1830 *ptr = value;
1831 }
1832
1833 int32_t* Simulator::readDW(int32_t addr) {
1834 if (handleWasmSegFault(addr, 8)) {
1835 return nullptr;
1836 }
1837
1838 if ((addr & 3) == 0) {
1839 int32_t* ptr = reinterpret_cast<int32_t*>(addr);
1840 return ptr;
1841 }
1842
1843 printf("Unaligned read at 0x%08x\n", addr);
1844 MOZ_CRASH();
1845 }
1846
1847 void Simulator::writeDW(int32_t addr, int32_t value1, int32_t value2) {
1848 if (handleWasmSegFault(addr, 8)) {
1849 return;
1850 }
1851
1852 if ((addr & 3) == 0) {
1853 int32_t* ptr = reinterpret_cast<int32_t*>(addr);
1854 *ptr++ = value1;
1855 *ptr = value2;
1856 return;
1857 }
1858
1859 printf("Unaligned write at 0x%08x\n", addr);
1860 MOZ_CRASH();
1861 }
1862
1863 int32_t Simulator::readExDW(int32_t addr, int32_t* hibits) {
1864 if (addr & 3) {
1865 MOZ_CRASH("Unaligned exclusive read");
1866 }
1867
1868 if (handleWasmSegFault(addr, 8)) {
1869 return -1;
1870 }
1871
1872 SharedMem<uint64_t*> ptr =
1873 SharedMem<uint64_t*>::shared(reinterpret_cast<uint64_t*>(addr));
1874 // The spec says that the low part of value shall be read from addr and
1875 // the high part shall be read from addr+4. On a little-endian system
1876 // where we read a 64-bit quadword the low part of the value will be in
1877 // the low part of the quadword, and the high part of the value in the
1878 // high part of the quadword.
1879 uint64_t value = loadRelaxed(ptr);
1880 exclusiveMonitorSet(value);
1881 *hibits = int32_t(value >> 32);
1882 return int32_t(value);
1883 }
1884
1885 int32_t Simulator::writeExDW(int32_t addr, int32_t value1, int32_t value2) {
1886 if (addr & 3) {
1887 MOZ_CRASH("Unaligned exclusive write");
1888 }
1889
1890 if (handleWasmSegFault(addr, 8)) {
1891 return -1;
1892 }
1893
1894 SharedMem<uint64_t*> ptr =
1895 SharedMem<uint64_t*>::shared(reinterpret_cast<uint64_t*>(addr));
1896 // The spec says that value1 shall be stored at addr and value2 at
1897 // addr+4. On a little-endian system that means constructing a 64-bit
1898 // value where value1 is in the low half of a 64-bit quadword and value2
1899 // is in the high half of the quadword.
1900 uint64_t value = (uint64_t(value2) << 32) | uint32_t(value1);
1901 bool held;
1902 uint64_t expected = exclusiveMonitorGetAndClear(&held);
1903 if (!held) {
1904 return 1;
1905 }
1906 uint64_t old = compareExchangeRelaxed(ptr, expected, value);
1907 return old != expected;
1908 }
1909
1910 uintptr_t Simulator::stackLimit() const { return stackLimit_; }
1911
1912 uintptr_t* Simulator::addressOfStackLimit() { return &stackLimit_; }
1913
1914 bool Simulator::overRecursed(uintptr_t newsp) const {
1915 if (newsp == 0) {
1916 newsp = get_register(sp);
1917 }
1918 return newsp <= stackLimit();
1919 }
1920
1921 bool Simulator::overRecursedWithExtra(uint32_t extra) const {
1922 uintptr_t newsp = get_register(sp) - extra;
1923 return newsp <= stackLimit();
1924 }
1925
1926 // Checks if the current instruction should be executed based on its condition
1927 // bits.
1928 bool Simulator::conditionallyExecute(SimInstruction* instr) {
1929 switch (instr->conditionField()) {
1930 case Assembler::EQ:
1931 return z_flag_;
1932 case Assembler::NE:
1933 return !z_flag_;
1934 case Assembler::CS:
1935 return c_flag_;
1936 case Assembler::CC:
1937 return !c_flag_;
1938 case Assembler::MI:
1939 return n_flag_;
1940 case Assembler::PL:
1941 return !n_flag_;
1942 case Assembler::VS:
1943 return v_flag_;
1944 case Assembler::VC:
1945 return !v_flag_;
1946 case Assembler::HI:
1947 return c_flag_ && !z_flag_;
1948 case Assembler::LS:
1949 return !c_flag_ || z_flag_;
1950 case Assembler::GE:
1951 return n_flag_ == v_flag_;
1952 case Assembler::LT:
1953 return n_flag_ != v_flag_;
1954 case Assembler::GT:
1955 return !z_flag_ && (n_flag_ == v_flag_);
1956 case Assembler::LE:
1957 return z_flag_ || (n_flag_ != v_flag_);
1958 case Assembler::AL:
1959 return true;
1960 default:
1961 MOZ_CRASH();
1962 }
1963 return false;
1964 }
1965
1966 // Calculate and set the Negative and Zero flags.
1967 void Simulator::setNZFlags(int32_t val) {
1968 n_flag_ = (val < 0);
1969 z_flag_ = (val == 0);
1970 }
1971
1972 // Set the Carry flag.
1973 void Simulator::setCFlag(bool val) { c_flag_ = val; }
1974
1975 // Set the oVerflow flag.
1976 void Simulator::setVFlag(bool val) { v_flag_ = val; }
1977
1978 // Calculate C flag value for additions.
1979 bool Simulator::carryFrom(int32_t left, int32_t right, int32_t carry) {
1980 uint32_t uleft = static_cast<uint32_t>(left);
1981 uint32_t uright = static_cast<uint32_t>(right);
1982 uint32_t urest = 0xffffffffU - uleft;
1983 return (uright > urest) ||
1984 (carry && (((uright + 1) > urest) || (uright > (urest - 1))));
1985 }
1986
1987 // Calculate C flag value for subtractions.
1988 bool Simulator::borrowFrom(int32_t left, int32_t right) {
1989 uint32_t uleft = static_cast<uint32_t>(left);
1990 uint32_t uright = static_cast<uint32_t>(right);
1991 return (uright > uleft);
1992 }
1993
1994 // Calculate V flag value for additions and subtractions.
1995 bool Simulator::overflowFrom(int32_t alu_out, int32_t left, int32_t right,
1996 bool addition) {
1997 bool overflow;
1998 if (addition) {
1999 // Operands have the same sign.
2000 overflow = ((left >= 0 && right >= 0) || (left < 0 && right < 0))
2001 // And operands and result have different sign.
2002 && ((left < 0 && alu_out >= 0) || (left >= 0 && alu_out < 0));
2003 } else {
2004 // Operands have different signs.
2005 overflow = ((left < 0 && right >= 0) || (left >= 0 && right < 0))
2006 // And first operand and result have different signs.
2007 && ((left < 0 && alu_out >= 0) || (left >= 0 && alu_out < 0));
2008 }
2009 return overflow;
2010 }
2011
2012 // Support for VFP comparisons.
2013 void Simulator::compute_FPSCR_Flags(double val1, double val2) {
2014 if (std::isnan(val1) || std::isnan(val2)) {
2015 n_flag_FPSCR_ = false;
2016 z_flag_FPSCR_ = false;
2017 c_flag_FPSCR_ = true;
2018 v_flag_FPSCR_ = true;
2019 // All non-NaN cases.
2020 } else if (val1 == val2) {
2021 n_flag_FPSCR_ = false;
2022 z_flag_FPSCR_ = true;
2023 c_flag_FPSCR_ = true;
2024 v_flag_FPSCR_ = false;
2025 } else if (val1 < val2) {
2026 n_flag_FPSCR_ = true;
2027 z_flag_FPSCR_ = false;
2028 c_flag_FPSCR_ = false;
2029 v_flag_FPSCR_ = false;
2030 } else {
2031 // Case when (val1 > val2).
2032 n_flag_FPSCR_ = false;
2033 z_flag_FPSCR_ = false;
2034 c_flag_FPSCR_ = true;
2035 v_flag_FPSCR_ = false;
2036 }
2037 }
2038
2039 void Simulator::copy_FPSCR_to_APSR() {
2040 n_flag_ = n_flag_FPSCR_;
2041 z_flag_ = z_flag_FPSCR_;
2042 c_flag_ = c_flag_FPSCR_;
2043 v_flag_ = v_flag_FPSCR_;
2044 }
2045
2046 // Addressing Mode 1 - Data-processing operands:
2047 // Get the value based on the shifter_operand with register.
2048 int32_t Simulator::getShiftRm(SimInstruction* instr, bool* carry_out) {
2049 ShiftType shift = instr->shifttypeValue();
2050 int shift_amount = instr->shiftAmountValue();
2051 int32_t result = get_register(instr->rmValue());
2052 if (instr->bit(4) == 0) {
2053 // By immediate.
2054 if (shift == ROR && shift_amount == 0) {
2055 MOZ_CRASH("NYI");
2056 return result;
2057 }
2058 if ((shift == LSR || shift == ASR) && shift_amount == 0) {
2059 shift_amount = 32;
2060 }
2061 switch (shift) {
2062 case ASR: {
2063 if (shift_amount == 0) {
2064 if (result < 0) {
2065 result = 0xffffffff;
2066 *carry_out = true;
2067 } else {
2068 result = 0;
2069 *carry_out = false;
2070 }
2071 } else {
2072 result >>= (shift_amount - 1);
2073 *carry_out = (result & 1) == 1;
2074 result >>= 1;
2075 }
2076 break;
2077 }
2078
2079 case LSL: {
2080 if (shift_amount == 0) {
2081 *carry_out = c_flag_;
2082 } else {
2083 result <<= (shift_amount - 1);
2084 *carry_out = (result < 0);
2085 result <<= 1;
2086 }
2087 break;
2088 }
2089
2090 case LSR: {
2091 if (shift_amount == 0) {
2092 result = 0;
2093 *carry_out = c_flag_;
2094 } else {
2095 uint32_t uresult = static_cast<uint32_t>(result);
2096 uresult >>= (shift_amount - 1);
2097 *carry_out = (uresult & 1) == 1;
2098 uresult >>= 1;
2099 result = static_cast<int32_t>(uresult);
2100 }
2101 break;
2102 }
2103
2104 case ROR: {
2105 if (shift_amount == 0) {
2106 *carry_out = c_flag_;
2107 } else {
2108 uint32_t left = static_cast<uint32_t>(result) >> shift_amount;
2109 uint32_t right = static_cast<uint32_t>(result) << (32 - shift_amount);
2110 result = right | left;
2111 *carry_out = (static_cast<uint32_t>(result) >> 31) != 0;
2112 }
2113 break;
2114 }
2115
2116 default:
2117 MOZ_CRASH();
2118 }
2119 } else {
2120 // By register.
2121 int rs = instr->rsValue();
2122 shift_amount = get_register(rs) & 0xff;
2123 switch (shift) {
2124 case ASR: {
2125 if (shift_amount == 0) {
2126 *carry_out = c_flag_;
2127 } else if (shift_amount < 32) {
2128 result >>= (shift_amount - 1);
2129 *carry_out = (result & 1) == 1;
2130 result >>= 1;
2131 } else {
2132 MOZ_ASSERT(shift_amount >= 32);
2133 if (result < 0) {
2134 *carry_out = true;
2135 result = 0xffffffff;
2136 } else {
2137 *carry_out = false;
2138 result = 0;
2139 }
2140 }
2141 break;
2142 }
2143
2144 case LSL: {
2145 if (shift_amount == 0) {
2146 *carry_out = c_flag_;
2147 } else if (shift_amount < 32) {
2148 result <<= (shift_amount - 1);
2149 *carry_out = (result < 0);
2150 result <<= 1;
2151 } else if (shift_amount == 32) {
2152 *carry_out = (result & 1) == 1;
2153 result = 0;
2154 } else {
2155 MOZ_ASSERT(shift_amount > 32);
2156 *carry_out = false;
2157 result = 0;
2158 }
2159 break;
2160 }
2161
2162 case LSR: {
2163 if (shift_amount == 0) {
2164 *carry_out = c_flag_;
2165 } else if (shift_amount < 32) {
2166 uint32_t uresult = static_cast<uint32_t>(result);
2167 uresult >>= (shift_amount - 1);
2168 *carry_out = (uresult & 1) == 1;
2169 uresult >>= 1;
2170 result = static_cast<int32_t>(uresult);
2171 } else if (shift_amount == 32) {
2172 *carry_out = (result < 0);
2173 result = 0;
2174 } else {
2175 *carry_out = false;
2176 result = 0;
2177 }
2178 break;
2179 }
2180
2181 case ROR: {
2182 if (shift_amount == 0) {
2183 *carry_out = c_flag_;
2184 } else {
2185 uint32_t left = static_cast<uint32_t>(result) >> shift_amount;
2186 uint32_t right = static_cast<uint32_t>(result) << (32 - shift_amount);
2187 result = right | left;
2188 *carry_out = (static_cast<uint32_t>(result) >> 31) != 0;
2189 }
2190 break;
2191 }
2192
2193 default:
2194 MOZ_CRASH();
2195 }
2196 }
2197 return result;
2198 }
2199
2200 // Addressing Mode 1 - Data-processing operands:
2201 // Get the value based on the shifter_operand with immediate.
2202 int32_t Simulator::getImm(SimInstruction* instr, bool* carry_out) {
2203 int rotate = instr->rotateValue() * 2;
2204 int immed8 = instr->immed8Value();
2205 int imm = (immed8 >> rotate) | (immed8 << (32 - rotate));
2206 *carry_out = (rotate == 0) ? c_flag_ : (imm < 0);
2207 return imm;
2208 }
2209
2210 int32_t Simulator::processPU(SimInstruction* instr, int num_regs, int reg_size,
2211 intptr_t* start_address, intptr_t* end_address) {
2212 int rn = instr->rnValue();
2213 int32_t rn_val = get_register(rn);
2214 switch (instr->PUField()) {
2215 case da_x:
2216 MOZ_CRASH();
2217 break;
2218 case ia_x:
2219 *start_address = rn_val;
2220 *end_address = rn_val + (num_regs * reg_size) - reg_size;
2221 rn_val = rn_val + (num_regs * reg_size);
2222 break;
2223 case db_x:
2224 *start_address = rn_val - (num_regs * reg_size);
2225 *end_address = rn_val - reg_size;
2226 rn_val = *start_address;
2227 break;
2228 case ib_x:
2229 *start_address = rn_val + reg_size;
2230 *end_address = rn_val + (num_regs * reg_size);
2231 rn_val = *end_address;
2232 break;
2233 default:
2234 MOZ_CRASH();
2235 }
2236 return rn_val;
2237 }
2238
2239 // Addressing Mode 4 - Load and Store Multiple
2240 void Simulator::handleRList(SimInstruction* instr, bool load) {
2241 int rlist = instr->rlistValue();
2242 int num_regs = mozilla::CountPopulation32(rlist);
2243
2244 intptr_t start_address = 0;
2245 intptr_t end_address = 0;
2246 int32_t rn_val =
2247 processPU(instr, num_regs, sizeof(void*), &start_address, &end_address);
2248 intptr_t* address = reinterpret_cast<intptr_t*>(start_address);
2249
2250 // Catch null pointers a little earlier.
2251 MOZ_ASSERT(start_address > 8191 || start_address < 0);
2252
2253 int reg = 0;
2254 while (rlist != 0) {
2255 if ((rlist & 1) != 0) {
2256 if (load) {
2257 set_register(reg, *address);
2258 } else {
2259 *address = get_register(reg);
2260 }
2261 address += 1;
2262 }
2263 reg++;
2264 rlist >>= 1;
2265 }
2266 MOZ_ASSERT(end_address == ((intptr_t)address) - 4);
2267 if (instr->hasW()) {
2268 set_register(instr->rnValue(), rn_val);
2269 }
2270 }
2271
2272 // Addressing Mode 6 - Load and Store Multiple Coprocessor registers.
2273 void Simulator::handleVList(SimInstruction* instr) {
2274 VFPRegPrecision precision =
2275 (instr->szValue() == 0) ? kSinglePrecision : kDoublePrecision;
2276 int operand_size = (precision == kSinglePrecision) ? 4 : 8;
2277 bool load = (instr->VLValue() == 0x1);
2278
2279 int vd;
2280 int num_regs;
2281 vd = instr->VFPDRegValue(precision);
2282 if (precision == kSinglePrecision) {
2283 num_regs = instr->immed8Value();
2284 } else {
2285 num_regs = instr->immed8Value() / 2;
2286 }
2287
2288 intptr_t start_address = 0;
2289 intptr_t end_address = 0;
2290 int32_t rn_val =
2291 processPU(instr, num_regs, operand_size, &start_address, &end_address);
2292
2293 intptr_t* address = reinterpret_cast<intptr_t*>(start_address);
2294 for (int reg = vd; reg < vd + num_regs; reg++) {
2295 if (precision == kSinglePrecision) {
2296 if (load) {
2297 set_s_register_from_sinteger(
2298 reg, readW(reinterpret_cast<int32_t>(address), instr));
2299 } else {
2300 writeW(reinterpret_cast<int32_t>(address),
2301 get_sinteger_from_s_register(reg), instr);
2302 }
2303 address += 1;
2304 } else {
2305 if (load) {
2306 int32_t data[] = {readW(reinterpret_cast<int32_t>(address), instr),
2307 readW(reinterpret_cast<int32_t>(address + 1), instr)};
2308 double d;
2309 memcpy(&d, data, 8);
2310 set_d_register_from_double(reg, d);
2311 } else {
2312 int32_t data[2];
2313 double d;
2314 get_double_from_d_register(reg, &d);
2315 memcpy(data, &d, 8);
2316 writeW(reinterpret_cast<int32_t>(address), data[0], instr);
2317 writeW(reinterpret_cast<int32_t>(address + 1), data[1], instr);
2318 }
2319 address += 2;
2320 }
2321 }
2322 MOZ_ASSERT(reinterpret_cast<intptr_t>(address) - operand_size == end_address);
2323 if (instr->hasW()) {
2324 set_register(instr->rnValue(), rn_val);
2325 }
2326 }
2327
2328 ABI_FUNCTION_TYPE_SIM_PROTOTYPES
2329
2330 // Fill the volatile registers with scratch values.
2331 //
2332 // Some of the ABI calls assume that the float registers are not scratched,
2333 // even though the ABI defines them as volatile - a performance
2334 // optimization. These are all calls passing operands in integer registers,
2335 // so for now the simulator does not scratch any float registers for these
2336 // calls. Should try to narrow it further in future.
2337 //
2338 void Simulator::scratchVolatileRegisters(void* target) {
2339 // The ARM backend makes calls to __aeabi_idivmod and
2340 // __aeabi_uidivmod assuming that the float registers are
2341 // non-volatile as a performance optimization, so the float
2342 // registers must not be scratch when calling these.
2343 bool scratchFloat = target != __aeabi_idivmod && target != __aeabi_uidivmod;
2344 int32_t scratch_value = 0xa5a5a5a5 ^ uint32_t(icount_);
2345 set_register(r0, scratch_value);
2346 set_register(r1, scratch_value);
2347 set_register(r2, scratch_value);
2348 set_register(r3, scratch_value);
2349 set_register(r12, scratch_value); // Intra-Procedure-call scratch register.
2350 set_register(r14, scratch_value); // Link register.
2351
2352 if (scratchFloat) {
2353 uint64_t scratch_value_d =
2354 0x5a5a5a5a5a5a5a5aLU ^ uint64_t(icount_) ^ (uint64_t(icount_) << 30);
2355 for (uint32_t i = d0; i < d8; i++) {
2356 set_d_register(i, &scratch_value_d);
2357 }
2358 for (uint32_t i = d16; i < FloatRegisters::TotalPhys; i++) {
2359 set_d_register(i, &scratch_value_d);
2360 }
2361 }
2362 }
2363
2364 static int64_t MakeInt64(int32_t first, int32_t second) {
2365 // Little-endian order.
2366 return ((int64_t)second << 32) | (uint32_t)first;
2367 }
2368
2369 // Software interrupt instructions are used by the simulator to call into C++.
2370 void Simulator::softwareInterrupt(SimInstruction* instr) {
2371 int svc = instr->svcValue();
2372 switch (svc) {
2373 case kCallRtRedirected: {
2374 Redirection* redirection = Redirection::FromSwiInstruction(instr);
2375 int32_t* stack_pointer = reinterpret_cast<int32_t*>(get_register(sp));
2376 int32_t a0 = get_register(r0);
2377 int32_t a1 = get_register(r1);
2378 int32_t a2 = get_register(r2);
2379 int32_t a3 = get_register(r3);
2380 float s0, s1, s2, s3, s4;
2381 get_float_from_s_register(0, &s0);
2382 get_float_from_s_register(0, &s1);
2383 get_float_from_s_register(0, &s2);
2384 get_float_from_s_register(0, &s3);
2385 get_float_from_s_register(0, &s4);
2386 double d0, d1, d2, d3, d4;
2387 get_double_from_d_register(0, &d0);
2388 get_double_from_d_register(1, &d1);
2389 get_double_from_d_register(2, &d2);
2390 get_double_from_d_register(3, &d3);
2391 get_double_from_d_register(4, &d4);
2392
2393 int32_t saved_lr = get_register(lr);
2394 intptr_t external =
2395 reinterpret_cast<intptr_t>(redirection->nativeFunction());
2396
2397 bool stack_aligned = (get_register(sp) & (ABIStackAlignment - 1)) == 0;
2398 if (!stack_aligned) {
2399 fprintf(stderr, "Runtime call with unaligned stack!\n");
2400 MOZ_CRASH();
2401 }
2402
2403 if (single_stepping_) {
2404 single_step_callback_(single_step_callback_arg_, this, nullptr);
2405 }
2406
2407 switch (redirection->type()) {
2408 ABI_FUNCTION_TYPE_ARM32_SIM_DISPATCH
2409 default:
2410 MOZ_CRASH("call");
2411 }
2412
2413 if (single_stepping_) {
2414 single_step_callback_(single_step_callback_arg_, this, nullptr);
2415 }
2416
2417 set_register(lr, saved_lr);
2418 set_pc(get_register(lr));
2419 break;
2420 }
2421 case kBreakpoint: {
2422 ArmDebugger dbg(this);
2423 dbg.debug();
2424 break;
2425 }
2426 default: { // Stop uses all codes greater than 1 << 23.
2427 if (svc >= (1 << 23)) {
2428 uint32_t code = svc & kStopCodeMask;
2429 if (isWatchedStop(code)) {
2430 increaseStopCounter(code);
2431 }
2432
2433 // Stop if it is enabled, otherwise go on jumping over the stop and
2434 // the message address.
2435 if (isEnabledStop(code)) {
2436 ArmDebugger dbg(this);
2437 dbg.stop(instr);
2438 } else {
2439 set_pc(get_pc() + 2 * SimInstruction::kInstrSize);
2440 }
2441 } else {
2442 // This is not a valid svc code.
2443 MOZ_CRASH();
2444 break;
2445 }
2446 }
2447 }
2448 }
2449
2450 void Simulator::canonicalizeNaN(double* value) {
2451 if (!wasm::CodeExists && !wasm::LookupCodeBlock(get_pc_as<void*>()) &&
2452 FPSCR_default_NaN_mode_) {
2453 *value = JS::CanonicalizeNaN(*value);
2454 }
2455 }
2456
2457 void Simulator::canonicalizeNaN(float* value) {
2458 if (!wasm::CodeExists && !wasm::LookupCodeBlock(get_pc_as<void*>()) &&
2459 FPSCR_default_NaN_mode_) {
2460 *value = JS::CanonicalizeNaN(*value);
2461 }
2462 }
2463
2464 // Stop helper functions.
2465 bool Simulator::isStopInstruction(SimInstruction* instr) {
2466 return (instr->bits(27, 24) == 0xF) && (instr->svcValue() >= kStopCode);
2467 }
2468
2469 bool Simulator::isWatchedStop(uint32_t code) {
2470 MOZ_ASSERT(code <= kMaxStopCode);
2471 return code < kNumOfWatchedStops;
2472 }
2473
2474 bool Simulator::isEnabledStop(uint32_t code) {
2475 MOZ_ASSERT(code <= kMaxStopCode);
2476 // Unwatched stops are always enabled.
2477 return !isWatchedStop(code) ||
2478 !(watched_stops_[code].count & kStopDisabledBit);
2479 }
2480
2481 void Simulator::enableStop(uint32_t code) {
2482 MOZ_ASSERT(isWatchedStop(code));
2483 if (!isEnabledStop(code)) {
2484 watched_stops_[code].count &= ~kStopDisabledBit;
2485 }
2486 }
2487
2488 void Simulator::disableStop(uint32_t code) {
2489 MOZ_ASSERT(isWatchedStop(code));
2490 if (isEnabledStop(code)) {
2491 watched_stops_[code].count |= kStopDisabledBit;
2492 }
2493 }
2494
2495 void Simulator::increaseStopCounter(uint32_t code) {
2496 MOZ_ASSERT(code <= kMaxStopCode);
2497 MOZ_ASSERT(isWatchedStop(code));
2498 if ((watched_stops_[code].count & ~(1 << 31)) == 0x7fffffff) {
2499 printf(
2500 "Stop counter for code %i has overflowed.\n"
2501 "Enabling this code and reseting the counter to 0.\n",
2502 code);
2503 watched_stops_[code].count = 0;
2504 enableStop(code);
2505 } else {
2506 watched_stops_[code].count++;
2507 }
2508 }
2509
2510 // Print a stop status.
2511 void Simulator::printStopInfo(uint32_t code) {
2512 MOZ_ASSERT(code <= kMaxStopCode);
2513 if (!isWatchedStop(code)) {
2514 printf("Stop not watched.");
2515 } else {
2516 const char* state = isEnabledStop(code) ? "Enabled" : "Disabled";
2517 int32_t count = watched_stops_[code].count & ~kStopDisabledBit;
2518 // Don't print the state of unused breakpoints.
2519 if (count != 0) {
2520 if (watched_stops_[code].desc) {
2521 printf("stop %i - 0x%x: \t%s, \tcounter = %i, \t%s\n", code, code,
2522 state, count, watched_stops_[code].desc);
2523 } else {
2524 printf("stop %i - 0x%x: \t%s, \tcounter = %i\n", code, code, state,
2525 count);
2526 }
2527 }
2528 }
2529 }
2530
2531 // Instruction types 0 and 1 are both rolled into one function because they only
2532 // differ in the handling of the shifter_operand.
2533 void Simulator::decodeType01(SimInstruction* instr) {
2534 int type = instr->typeValue();
2535 if (type == 0 && instr->isSpecialType0()) {
2536 // Multiply instruction or extra loads and stores.
2537 if (instr->bits(7, 4) == 9) {
2538 if (instr->bit(24) == 0) {
2539 // Raw field decoding here. Multiply instructions have their Rd
2540 // in funny places.
2541 int rn = instr->rnValue();
2542 int rm = instr->rmValue();
2543 int rs = instr->rsValue();
2544 int32_t rs_val = get_register(rs);
2545 int32_t rm_val = get_register(rm);
2546 if (instr->bit(23) == 0) {
2547 if (instr->bit(21) == 0) {
2548 // The MUL instruction description (A 4.1.33) refers to
2549 // Rd as being the destination for the operation, but it
2550 // confusingly uses the Rn field to encode it.
2551 int rd = rn; // Remap the rn field to the Rd register.
2552 int32_t alu_out = rm_val * rs_val;
2553 set_register(rd, alu_out);
2554 if (instr->hasS()) {
2555 setNZFlags(alu_out);
2556 }
2557 } else {
2558 int rd = instr->rdValue();
2559 int32_t acc_value = get_register(rd);
2560 if (instr->bit(22) == 0) {
2561 // The MLA instruction description (A 4.1.28) refers
2562 // to the order of registers as "Rd, Rm, Rs,
2563 // Rn". But confusingly it uses the Rn field to
2564 // encode the Rd register and the Rd field to encode
2565 // the Rn register.
2566 int32_t mul_out = rm_val * rs_val;
2567 int32_t result = acc_value + mul_out;
2568 set_register(rn, result);
2569 } else {
2570 int32_t mul_out = rm_val * rs_val;
2571 int32_t result = acc_value - mul_out;
2572 set_register(rn, result);
2573 }
2574 }
2575 } else {
2576 // The signed/long multiply instructions use the terms RdHi
2577 // and RdLo when referring to the target registers. They are
2578 // mapped to the Rn and Rd fields as follows:
2579 // RdLo == Rd
2580 // RdHi == Rn (This is confusingly stored in variable rd here
2581 // because the mul instruction from above uses the
2582 // Rn field to encode the Rd register. Good luck figuring
2583 // this out without reading the ARM instruction manual
2584 // at a very detailed level.)
2585 int rd_hi = rn; // Remap the rn field to the RdHi register.
2586 int rd_lo = instr->rdValue();
2587 int32_t hi_res = 0;
2588 int32_t lo_res = 0;
2589 if (instr->bit(22) == 1) {
2590 int64_t left_op = static_cast<int32_t>(rm_val);
2591 int64_t right_op = static_cast<int32_t>(rs_val);
2592 uint64_t result = left_op * right_op;
2593 hi_res = static_cast<int32_t>(result >> 32);
2594 lo_res = static_cast<int32_t>(result & 0xffffffff);
2595 } else {
2596 // Unsigned multiply.
2597 uint64_t left_op = static_cast<uint32_t>(rm_val);
2598 uint64_t right_op = static_cast<uint32_t>(rs_val);
2599 uint64_t result = left_op * right_op;
2600 hi_res = static_cast<int32_t>(result >> 32);
2601 lo_res = static_cast<int32_t>(result & 0xffffffff);
2602 }
2603 set_register(rd_lo, lo_res);
2604 set_register(rd_hi, hi_res);
2605 if (instr->hasS()) {
2606 MOZ_CRASH();
2607 }
2608 }
2609 } else {
2610 if (instr->bits(excl::ExclusiveOpHi, excl::ExclusiveOpLo) ==
2611 excl::ExclusiveOpcode) {
2612 // Load-exclusive / store-exclusive.
2613 if (instr->bit(excl::ExclusiveLoad)) {
2614 int rn = instr->rnValue();
2615 int rt = instr->rtValue();
2616 int32_t address = get_register(rn);
2617 switch (instr->bits(excl::ExclusiveSizeHi, excl::ExclusiveSizeLo)) {
2618 case excl::ExclusiveWord:
2619 set_register(rt, readExW(address, instr));
2620 break;
2621 case excl::ExclusiveDouble: {
2622 MOZ_ASSERT((rt % 2) == 0);
2623 int32_t hibits;
2624 int32_t lobits = readExDW(address, &hibits);
2625 set_register(rt, lobits);
2626 set_register(rt + 1, hibits);
2627 break;
2628 }
2629 case excl::ExclusiveByte:
2630 set_register(rt, readExBU(address));
2631 break;
2632 case excl::ExclusiveHalf:
2633 set_register(rt, readExHU(address, instr));
2634 break;
2635 }
2636 } else {
2637 int rn = instr->rnValue();
2638 int rd = instr->rdValue();
2639 int rt = instr->bits(3, 0);
2640 int32_t address = get_register(rn);
2641 int32_t value = get_register(rt);
2642 int32_t result = 0;
2643 switch (instr->bits(excl::ExclusiveSizeHi, excl::ExclusiveSizeLo)) {
2644 case excl::ExclusiveWord:
2645 result = writeExW(address, value, instr);
2646 break;
2647 case excl::ExclusiveDouble: {
2648 MOZ_ASSERT((rt % 2) == 0);
2649 int32_t value2 = get_register(rt + 1);
2650 result = writeExDW(address, value, value2);
2651 break;
2652 }
2653 case excl::ExclusiveByte:
2654 result = writeExB(address, (uint8_t)value);
2655 break;
2656 case excl::ExclusiveHalf:
2657 result = writeExH(address, (uint16_t)value, instr);
2658 break;
2659 }
2660 set_register(rd, result);
2661 }
2662 } else {
2663 MOZ_CRASH(); // Not used atm
2664 }
2665 }
2666 } else {
2667 // Extra load/store instructions.
2668 int rd = instr->rdValue();
2669 int rn = instr->rnValue();
2670 int32_t rn_val = get_register(rn);
2671 int32_t addr = 0;
2672 if (instr->bit(22) == 0) {
2673 int rm = instr->rmValue();
2674 int32_t rm_val = get_register(rm);
2675 switch (instr->PUField()) {
2676 case da_x:
2677 MOZ_ASSERT(!instr->hasW());
2678 addr = rn_val;
2679 rn_val -= rm_val;
2680 set_register(rn, rn_val);
2681 break;
2682 case ia_x:
2683 MOZ_ASSERT(!instr->hasW());
2684 addr = rn_val;
2685 rn_val += rm_val;
2686 set_register(rn, rn_val);
2687 break;
2688 case db_x:
2689 rn_val -= rm_val;
2690 addr = rn_val;
2691 if (instr->hasW()) {
2692 set_register(rn, rn_val);
2693 }
2694 break;
2695 case ib_x:
2696 rn_val += rm_val;
2697 addr = rn_val;
2698 if (instr->hasW()) {
2699 set_register(rn, rn_val);
2700 }
2701 break;
2702 default:
2703 // The PU field is a 2-bit field.
2704 MOZ_CRASH();
2705 break;
2706 }
2707 } else {
2708 int32_t imm_val = (instr->immedHValue() << 4) | instr->immedLValue();
2709 switch (instr->PUField()) {
2710 case da_x:
2711 MOZ_ASSERT(!instr->hasW());
2712 addr = rn_val;
2713 rn_val -= imm_val;
2714 set_register(rn, rn_val);
2715 break;
2716 case ia_x:
2717 MOZ_ASSERT(!instr->hasW());
2718 addr = rn_val;
2719 rn_val += imm_val;
2720 set_register(rn, rn_val);
2721 break;
2722 case db_x:
2723 rn_val -= imm_val;
2724 addr = rn_val;
2725 if (instr->hasW()) {
2726 set_register(rn, rn_val);
2727 }
2728 break;
2729 case ib_x:
2730 rn_val += imm_val;
2731 addr = rn_val;
2732 if (instr->hasW()) {
2733 set_register(rn, rn_val);
2734 }
2735 break;
2736 default:
2737 // The PU field is a 2-bit field.
2738 MOZ_CRASH();
2739 break;
2740 }
2741 }
2742 if ((instr->bits(7, 4) & 0xd) == 0xd && instr->bit(20) == 0) {
2743 MOZ_ASSERT((rd % 2) == 0);
2744 if (instr->hasH()) {
2745 // The strd instruction.
2746 int32_t value1 = get_register(rd);
2747 int32_t value2 = get_register(rd + 1);
2748 writeDW(addr, value1, value2);
2749 } else {
2750 // The ldrd instruction.
2751 int* rn_data = readDW(addr);
2752 if (rn_data) {
2753 set_dw_register(rd, rn_data);
2754 }
2755 }
2756 } else if (instr->hasH()) {
2757 if (instr->hasSign()) {
2758 if (instr->hasL()) {
2759 int16_t val = readH(addr, instr);
2760 set_register(rd, val);
2761 } else {
2762 int16_t val = get_register(rd);
2763 writeH(addr, val, instr);
2764 }
2765 } else {
2766 if (instr->hasL()) {
2767 uint16_t val = readHU(addr, instr);
2768 set_register(rd, val);
2769 } else {
2770 uint16_t val = get_register(rd);
2771 writeH(addr, val, instr);
2772 }
2773 }
2774 } else {
2775 // Signed byte loads.
2776 MOZ_ASSERT(instr->hasSign());
2777 MOZ_ASSERT(instr->hasL());
2778 int8_t val = readB(addr);
2779 set_register(rd, val);
2780 }
2781 return;
2782 }
2783 } else if ((type == 0) && instr->isMiscType0()) {
2784 if (instr->bits(7, 4) == 0) {
2785 if (instr->bit(21) == 0) {
2786 // mrs
2787 int rd = instr->rdValue();
2788 uint32_t flags;
2789 if (instr->bit(22) == 0) {
2790 // CPSR. Note: The Q flag is not yet implemented!
2791 flags = (n_flag_ << 31) | (z_flag_ << 30) | (c_flag_ << 29) |
2792 (v_flag_ << 28);
2793 } else {
2794 // SPSR
2795 MOZ_CRASH();
2796 }
2797 set_register(rd, flags);
2798 } else {
2799 // msr
2800 if (instr->bits(27, 23) == 2) {
2801 // Register operand. For now we only emit mask 0b1100.
2802 int rm = instr->rmValue();
2803 mozilla::DebugOnly<uint32_t> mask = instr->bits(19, 16);
2804 MOZ_ASSERT(mask == (3 << 2));
2805
2806 uint32_t flags = get_register(rm);
2807 n_flag_ = (flags >> 31) & 1;
2808 z_flag_ = (flags >> 30) & 1;
2809 c_flag_ = (flags >> 29) & 1;
2810 v_flag_ = (flags >> 28) & 1;
2811 } else {
2812 MOZ_CRASH();
2813 }
2814 }
2815 } else if (instr->bits(22, 21) == 1) {
2816 int rm = instr->rmValue();
2817 switch (instr->bits(7, 4)) {
2818 case 1: // BX
2819 set_pc(get_register(rm));
2820 break;
2821 case 3: { // BLX
2822 uint32_t old_pc = get_pc();
2823 set_pc(get_register(rm));
2824 set_register(lr, old_pc + SimInstruction::kInstrSize);
2825 break;
2826 }
2827 case 7: { // BKPT
2828 fprintf(stderr, "Simulator hit BKPT.\n");
2829 if (getenv("ARM_SIM_DEBUGGER")) {
2830 ArmDebugger dbg(this);
2831 dbg.debug();
2832 } else {
2833 fprintf(stderr,
2834 "Use ARM_SIM_DEBUGGER=1 to enter the builtin debugger.\n");
2835 MOZ_CRASH("ARM simulator breakpoint");
2836 }
2837 break;
2838 }
2839 default:
2840 MOZ_CRASH();
2841 }
2842 } else if (instr->bits(22, 21) == 3) {
2843 int rm = instr->rmValue();
2844 int rd = instr->rdValue();
2845 switch (instr->bits(7, 4)) {
2846 case 1: { // CLZ
2847 uint32_t bits = get_register(rm);
2848 int leading_zeros = 0;
2849 if (bits == 0) {
2850 leading_zeros = 32;
2851 } else {
2852 leading_zeros = mozilla::CountLeadingZeroes32(bits);
2853 }
2854 set_register(rd, leading_zeros);
2855 break;
2856 }
2857 default:
2858 MOZ_CRASH();
2859 break;
2860 }
2861 } else {
2862 printf("%08x\n", instr->instructionBits());
2863 MOZ_CRASH();
2864 }
2865 } else if ((type == 1) && instr->isNopType1()) {
2866 // NOP.
2867 } else if ((type == 1) && instr->isYieldType1()) {
2868 AtomicOperations::pause();
2869 } else if ((type == 1) && instr->isCsdbType1()) {
2870 // Speculation barrier. (No-op for the simulator)
2871 } else {
2872 int rd = instr->rdValue();
2873 int rn = instr->rnValue();
2874 // Use uint32_t here for integer overflow in operations below not to be
2875 // undefined behavior, leading to our own calculations of overflow being
2876 // messed up by the compiler.
2877 uint32_t rn_val = get_register(rn);
2878 uint32_t shifter_operand = 0;
2879 bool shifter_carry_out = 0;
2880 if (type == 0) {
2881 shifter_operand = getShiftRm(instr, &shifter_carry_out);
2882 } else {
2883 MOZ_ASSERT(instr->typeValue() == 1);
2884 shifter_operand = getImm(instr, &shifter_carry_out);
2885 }
2886 int32_t alu_out;
2887 switch (instr->opcodeField()) {
2888 case OpAnd:
2889 alu_out = rn_val & shifter_operand;
2890 set_register(rd, alu_out);
2891 if (instr->hasS()) {
2892 setNZFlags(alu_out);
2893 setCFlag(shifter_carry_out);
2894 }
2895 break;
2896 case OpEor:
2897 alu_out = rn_val ^ shifter_operand;
2898 set_register(rd, alu_out);
2899 if (instr->hasS()) {
2900 setNZFlags(alu_out);
2901 setCFlag(shifter_carry_out);
2902 }
2903 break;
2904 case OpSub:
2905 alu_out = rn_val - shifter_operand;
2906 set_register(rd, alu_out);
2907 if (instr->hasS()) {
2908 setNZFlags(alu_out);
2909 setCFlag(!borrowFrom(rn_val, shifter_operand));
2910 setVFlag(overflowFrom(alu_out, rn_val, shifter_operand, false));
2911 }
2912 break;
2913 case OpRsb:
2914 alu_out = shifter_operand - rn_val;
2915 set_register(rd, alu_out);
2916 if (instr->hasS()) {
2917 setNZFlags(alu_out);
2918 setCFlag(!borrowFrom(shifter_operand, rn_val));
2919 setVFlag(overflowFrom(alu_out, shifter_operand, rn_val, false));
2920 }
2921 break;
2922 case OpAdd:
2923 alu_out = rn_val + shifter_operand;
2924 set_register(rd, alu_out);
2925 if (instr->hasS()) {
2926 setNZFlags(alu_out);
2927 setCFlag(carryFrom(rn_val, shifter_operand));
2928 setVFlag(overflowFrom(alu_out, rn_val, shifter_operand, true));
2929 }
2930 break;
2931 case OpAdc:
2932 alu_out = rn_val + shifter_operand + getCarry();
2933 set_register(rd, alu_out);
2934 if (instr->hasS()) {
2935 setNZFlags(alu_out);
2936 setCFlag(carryFrom(rn_val, shifter_operand, getCarry()));
2937 setVFlag(overflowFrom(alu_out, rn_val, shifter_operand, true));
2938 }
2939 break;
2940 case OpSbc:
2941 alu_out = rn_val - shifter_operand - (getCarry() == 0 ? 1 : 0);
2942 set_register(rd, alu_out);
2943 if (instr->hasS()) {
2944 MOZ_CRASH();
2945 }
2946 break;
2947 case OpRsc:
2948 alu_out = shifter_operand - rn_val - (getCarry() == 0 ? 1 : 0);
2949 set_register(rd, alu_out);
2950 if (instr->hasS()) {
2951 MOZ_CRASH();
2952 }
2953 break;
2954 case OpTst:
2955 if (instr->hasS()) {
2956 alu_out = rn_val & shifter_operand;
2957 setNZFlags(alu_out);
2958 setCFlag(shifter_carry_out);
2959 } else {
2960 alu_out = instr->immedMovwMovtValue();
2961 set_register(rd, alu_out);
2962 }
2963 break;
2964 case OpTeq:
2965 if (instr->hasS()) {
2966 alu_out = rn_val ^ shifter_operand;
2967 setNZFlags(alu_out);
2968 setCFlag(shifter_carry_out);
2969 } else {
2970 // Other instructions matching this pattern are handled in the
2971 // miscellaneous instructions part above.
2972 MOZ_CRASH();
2973 }
2974 break;
2975 case OpCmp:
2976 if (instr->hasS()) {
2977 alu_out = rn_val - shifter_operand;
2978 setNZFlags(alu_out);
2979 setCFlag(!borrowFrom(rn_val, shifter_operand));
2980 setVFlag(overflowFrom(alu_out, rn_val, shifter_operand, false));
2981 } else {
2982 alu_out =
2983 (get_register(rd) & 0xffff) | (instr->immedMovwMovtValue() << 16);
2984 set_register(rd, alu_out);
2985 }
2986 break;
2987 case OpCmn:
2988 if (instr->hasS()) {
2989 alu_out = rn_val + shifter_operand;
2990 setNZFlags(alu_out);
2991 setCFlag(carryFrom(rn_val, shifter_operand));
2992 setVFlag(overflowFrom(alu_out, rn_val, shifter_operand, true));
2993 } else {
2994 // Other instructions matching this pattern are handled in the
2995 // miscellaneous instructions part above.
2996 MOZ_CRASH();
2997 }
2998 break;
2999 case OpOrr:
3000 alu_out = rn_val | shifter_operand;
3001 set_register(rd, alu_out);
3002 if (instr->hasS()) {
3003 setNZFlags(alu_out);
3004 setCFlag(shifter_carry_out);
3005 }
3006 break;
3007 case OpMov:
3008 alu_out = shifter_operand;
3009 set_register(rd, alu_out);
3010 if (instr->hasS()) {
3011 setNZFlags(alu_out);
3012 setCFlag(shifter_carry_out);
3013 }
3014 break;
3015 case OpBic:
3016 alu_out = rn_val & ~shifter_operand;
3017 set_register(rd, alu_out);
3018 if (instr->hasS()) {
3019 setNZFlags(alu_out);
3020 setCFlag(shifter_carry_out);
3021 }
3022 break;
3023 case OpMvn:
3024 alu_out = ~shifter_operand;
3025 set_register(rd, alu_out);
3026 if (instr->hasS()) {
3027 setNZFlags(alu_out);
3028 setCFlag(shifter_carry_out);
3029 }
3030 break;
3031 default:
3032 MOZ_CRASH();
3033 break;
3034 }
3035 }
3036 }
3037
3038 void Simulator::decodeType2(SimInstruction* instr) {
3039 int rd = instr->rdValue();
3040 int rn = instr->rnValue();
3041 int32_t rn_val = get_register(rn);
3042 int32_t im_val = instr->offset12Value();
3043 int32_t addr = 0;
3044 switch (instr->PUField()) {
3045 case da_x:
3046 MOZ_ASSERT(!instr->hasW());
3047 addr = rn_val;
3048 rn_val -= im_val;
3049 set_register(rn, rn_val);
3050 break;
3051 case ia_x:
3052 MOZ_ASSERT(!instr->hasW());
3053 addr = rn_val;
3054 rn_val += im_val;
3055 set_register(rn, rn_val);
3056 break;
3057 case db_x:
3058 rn_val -= im_val;
3059 addr = rn_val;
3060 if (instr->hasW()) {
3061 set_register(rn, rn_val);
3062 }
3063 break;
3064 case ib_x:
3065 rn_val += im_val;
3066 addr = rn_val;
3067 if (instr->hasW()) {
3068 set_register(rn, rn_val);
3069 }
3070 break;
3071 default:
3072 MOZ_CRASH();
3073 break;
3074 }
3075 if (instr->hasB()) {
3076 if (instr->hasL()) {
3077 uint8_t val = readBU(addr);
3078 set_register(rd, val);
3079 } else {
3080 uint8_t val = get_register(rd);
3081 writeB(addr, val);
3082 }
3083 } else {
3084 if (instr->hasL()) {
3085 set_register(rd, readW(addr, instr, AllowUnaligned));
3086 } else {
3087 writeW(addr, get_register(rd), instr, AllowUnaligned);
3088 }
3089 }
3090 }
3091
3092 static uint32_t rotateBytes(uint32_t val, int32_t rotate) {
3093 switch (rotate) {
3094 default:
3095 return val;
3096 case 1:
3097 return (val >> 8) | (val << 24);
3098 case 2:
3099 return (val >> 16) | (val << 16);
3100 case 3:
3101 return (val >> 24) | (val << 8);
3102 }
3103 }
3104
3105 void Simulator::decodeType3(SimInstruction* instr) {
3106 if (MOZ_UNLIKELY(instr->isUDF())) {
3107 uint8_t* newPC;
3108 if (wasm::HandleIllegalInstruction(registerState(), &newPC)) {
3109 set_pc((int32_t)newPC);
3110 return;
3111 }
3112 MOZ_CRASH("illegal instruction encountered");
3113 }
3114
3115 int rd = instr->rdValue();
3116 int rn = instr->rnValue();
3117 int32_t rn_val = get_register(rn);
3118 bool shifter_carry_out = 0;
3119 int32_t shifter_operand = getShiftRm(instr, &shifter_carry_out);
3120 int32_t addr = 0;
3121 switch (instr->PUField()) {
3122 case da_x:
3123 MOZ_ASSERT(!instr->hasW());
3124 MOZ_CRASH();
3125 break;
3126 case ia_x: {
3127 if (instr->bit(4) == 0) {
3128 // Memop.
3129 } else {
3130 if (instr->bit(5) == 0) {
3131 switch (instr->bits(22, 21)) {
3132 case 0:
3133 if (instr->bit(20) == 0) {
3134 if (instr->bit(6) == 0) {
3135 // Pkhbt.
3136 uint32_t rn_val = get_register(rn);
3137 uint32_t rm_val = get_register(instr->rmValue());
3138 int32_t shift = instr->bits(11, 7);
3139 rm_val <<= shift;
3140 set_register(rd, (rn_val & 0xFFFF) | (rm_val & 0xFFFF0000U));
3141 } else {
3142 // Pkhtb.
3143 uint32_t rn_val = get_register(rn);
3144 int32_t rm_val = get_register(instr->rmValue());
3145 int32_t shift = instr->bits(11, 7);
3146 if (shift == 0) {
3147 shift = 32;
3148 }
3149 rm_val >>= shift;
3150 set_register(rd, (rn_val & 0xFFFF0000U) | (rm_val & 0xFFFF));
3151 }
3152 } else {
3153 MOZ_CRASH();
3154 }
3155 break;
3156 case 1:
3157 MOZ_CRASH();
3158 break;
3159 case 2:
3160 MOZ_CRASH();
3161 break;
3162 case 3: {
3163 // Usat.
3164 int32_t sat_pos = instr->bits(20, 16);
3165 int32_t sat_val = (1 << sat_pos) - 1;
3166 int32_t shift = instr->bits(11, 7);
3167 int32_t shift_type = instr->bit(6);
3168 int32_t rm_val = get_register(instr->rmValue());
3169 if (shift_type == 0) { // LSL
3170 rm_val <<= shift;
3171 } else { // ASR
3172 rm_val >>= shift;
3173 }
3174
3175 // If saturation occurs, the Q flag should be set in the
3176 // CPSR. There is no Q flag yet, and no instruction (MRS)
3177 // to read the CPSR directly.
3178 if (rm_val > sat_val) {
3179 rm_val = sat_val;
3180 } else if (rm_val < 0) {
3181 rm_val = 0;
3182 }
3183 set_register(rd, rm_val);
3184 break;
3185 }
3186 }
3187 } else {
3188 switch (instr->bits(22, 21)) {
3189 case 0:
3190 MOZ_CRASH();
3191 break;
3192 case 1:
3193 if (instr->bits(7, 4) == 7 && instr->bits(19, 16) == 15) {
3194 uint32_t rm_val = rotateBytes(get_register(instr->rmValue()),
3195 instr->bits(11, 10));
3196 if (instr->bit(20)) {
3197 // Sxth.
3198 set_register(rd, (int32_t)(int16_t)(rm_val & 0xFFFF));
3199 } else {
3200 // Sxtb.
3201 set_register(rd, (int32_t)(int8_t)(rm_val & 0xFF));
3202 }
3203 } else if (instr->bits(20, 16) == 0b1'1111 &&
3204 instr->bits(11, 4) == 0b1111'0011) {
3205 // Rev
3206 uint32_t rm_val = get_register(instr->rmValue());
3207
3208 static_assert(MOZ_LITTLE_ENDIAN());
3209 set_register(rd,
3210 mozilla::NativeEndian::swapToBigEndian(rm_val));
3211 } else if (instr->bits(20, 16) == 0b1'1111 &&
3212 instr->bits(11, 4) == 0b1111'1011) {
3213 // Rev16
3214 uint32_t rm_val = get_register(instr->rmValue());
3215
3216 static_assert(MOZ_LITTLE_ENDIAN());
3217 uint32_t hi = mozilla::NativeEndian::swapToBigEndian(
3218 uint16_t(rm_val >> 16));
3219 uint32_t lo =
3220 mozilla::NativeEndian::swapToBigEndian(uint16_t(rm_val));
3221 set_register(rd, (hi << 16) | lo);
3222 } else {
3223 MOZ_CRASH();
3224 }
3225 break;
3226 case 2:
3227 if ((instr->bit(20) == 0) && (instr->bits(9, 6) == 1)) {
3228 if (instr->bits(19, 16) == 0xF) {
3229 // Uxtb16.
3230 uint32_t rm_val = rotateBytes(get_register(instr->rmValue()),
3231 instr->bits(11, 10));
3232 set_register(rd, (rm_val & 0xFF) | (rm_val & 0xFF0000));
3233 } else {
3234 MOZ_CRASH();
3235 }
3236 } else {
3237 MOZ_CRASH();
3238 }
3239 break;
3240 case 3:
3241 if ((instr->bit(20) == 0) && (instr->bits(9, 6) == 1)) {
3242 if (instr->bits(19, 16) == 0xF) {
3243 // Uxtb.
3244 uint32_t rm_val = rotateBytes(get_register(instr->rmValue()),
3245 instr->bits(11, 10));
3246 set_register(rd, (rm_val & 0xFF));
3247 } else {
3248 // Uxtab.
3249 uint32_t rn_val = get_register(rn);
3250 uint32_t rm_val = rotateBytes(get_register(instr->rmValue()),
3251 instr->bits(11, 10));
3252 set_register(rd, rn_val + (rm_val & 0xFF));
3253 }
3254 } else if ((instr->bit(20) == 1) && (instr->bits(9, 6) == 1)) {
3255 if (instr->bits(19, 16) == 0xF) {
3256 // Uxth.
3257 uint32_t rm_val = rotateBytes(get_register(instr->rmValue()),
3258 instr->bits(11, 10));
3259 set_register(rd, (rm_val & 0xFFFF));
3260 } else {
3261 // Uxtah.
3262 uint32_t rn_val = get_register(rn);
3263 uint32_t rm_val = rotateBytes(get_register(instr->rmValue()),
3264 instr->bits(11, 10));
3265 set_register(rd, rn_val + (rm_val & 0xFFFF));
3266 }
3267 } else if (instr->bits(20, 16) == 0b1'1111 &&
3268 instr->bits(11, 4) == 0b1111'1011) {
3269 // Revsh
3270 uint32_t rm_val = get_register(instr->rmValue());
3271
3272 static_assert(MOZ_LITTLE_ENDIAN());
3273 set_register(
3274 rd, int32_t(int16_t(mozilla::NativeEndian::swapToBigEndian(
3275 uint16_t(rm_val)))));
3276 } else {
3277 MOZ_CRASH();
3278 }
3279 break;
3280 }
3281 }
3282 return;
3283 }
3284 break;
3285 }
3286 case db_x: { // sudiv
3287 if (instr->bit(22) == 0x0 && instr->bit(20) == 0x1 &&
3288 instr->bits(15, 12) == 0x0f && instr->bits(7, 4) == 0x1) {
3289 if (!instr->hasW()) {
3290 // sdiv (in V8 notation matching ARM ISA format) rn = rm/rs.
3291 int rm = instr->rmValue();
3292 int32_t rm_val = get_register(rm);
3293 int rs = instr->rsValue();
3294 int32_t rs_val = get_register(rs);
3295 int32_t ret_val = 0;
3296 MOZ_ASSERT(rs_val != 0);
3297 if ((rm_val == INT32_MIN) && (rs_val == -1)) {
3298 ret_val = INT32_MIN;
3299 } else {
3300 ret_val = rm_val / rs_val;
3301 }
3302 set_register(rn, ret_val);
3303 return;
3304 } else {
3305 // udiv (in V8 notation matching ARM ISA format) rn = rm/rs.
3306 int rm = instr->rmValue();
3307 uint32_t rm_val = get_register(rm);
3308 int rs = instr->rsValue();
3309 uint32_t rs_val = get_register(rs);
3310 uint32_t ret_val = 0;
3311 MOZ_ASSERT(rs_val != 0);
3312 ret_val = rm_val / rs_val;
3313 set_register(rn, ret_val);
3314 return;
3315 }
3316 }
3317
3318 addr = rn_val - shifter_operand;
3319 if (instr->hasW()) {
3320 set_register(rn, addr);
3321 }
3322 break;
3323 }
3324 case ib_x: {
3325 if (instr->hasW() && (instr->bits(6, 4) == 0x5)) {
3326 uint32_t widthminus1 = static_cast<uint32_t>(instr->bits(20, 16));
3327 uint32_t lsbit = static_cast<uint32_t>(instr->bits(11, 7));
3328 uint32_t msbit = widthminus1 + lsbit;
3329 if (msbit <= 31) {
3330 if (instr->bit(22)) {
3331 // ubfx - unsigned bitfield extract.
3332 uint32_t rm_val =
3333 static_cast<uint32_t>(get_register(instr->rmValue()));
3334 uint32_t extr_val = rm_val << (31 - msbit);
3335 extr_val = extr_val >> (31 - widthminus1);
3336 set_register(instr->rdValue(), extr_val);
3337 } else {
3338 // sbfx - signed bitfield extract.
3339 int32_t rm_val = get_register(instr->rmValue());
3340 int32_t extr_val = rm_val << (31 - msbit);
3341 extr_val = extr_val >> (31 - widthminus1);
3342 set_register(instr->rdValue(), extr_val);
3343 }
3344 } else {
3345 MOZ_CRASH();
3346 }
3347 return;
3348 } else if (!instr->hasW() && (instr->bits(6, 4) == 0x1)) {
3349 uint32_t lsbit = static_cast<uint32_t>(instr->bits(11, 7));
3350 uint32_t msbit = static_cast<uint32_t>(instr->bits(20, 16));
3351 if (msbit >= lsbit) {
3352 // bfc or bfi - bitfield clear/insert.
3353 uint32_t rd_val =
3354 static_cast<uint32_t>(get_register(instr->rdValue()));
3355 uint32_t bitcount = msbit - lsbit + 1;
3356 uint32_t mask = (1 << bitcount) - 1;
3357 rd_val &= ~(mask << lsbit);
3358 if (instr->rmValue() != 15) {
3359 // bfi - bitfield insert.
3360 uint32_t rm_val =
3361 static_cast<uint32_t>(get_register(instr->rmValue()));
3362 rm_val &= mask;
3363 rd_val |= rm_val << lsbit;
3364 }
3365 set_register(instr->rdValue(), rd_val);
3366 } else {
3367 MOZ_CRASH();
3368 }
3369 return;
3370 } else {
3371 addr = rn_val + shifter_operand;
3372 if (instr->hasW()) {
3373 set_register(rn, addr);
3374 }
3375 }
3376 break;
3377 }
3378 default:
3379 MOZ_CRASH();
3380 break;
3381 }
3382 if (instr->hasB()) {
3383 if (instr->hasL()) {
3384 uint8_t byte = readB(addr);
3385 set_register(rd, byte);
3386 } else {
3387 uint8_t byte = get_register(rd);
3388 writeB(addr, byte);
3389 }
3390 } else {
3391 if (instr->hasL()) {
3392 set_register(rd, readW(addr, instr, AllowUnaligned));
3393 } else {
3394 writeW(addr, get_register(rd), instr, AllowUnaligned);
3395 }
3396 }
3397 }
3398
3399 void Simulator::decodeType4(SimInstruction* instr) {
3400 // Only allowed to be set in privileged mode.
3401 MOZ_ASSERT(instr->bit(22) == 0);
3402 bool load = instr->hasL();
3403 handleRList(instr, load);
3404 }
3405
3406 void Simulator::decodeType5(SimInstruction* instr) {
3407 int off = instr->sImmed24Value() << 2;
3408 intptr_t pc_address = get_pc();
3409 if (instr->hasLink()) {
3410 set_register(lr, pc_address + SimInstruction::kInstrSize);
3411 }
3412 int pc_reg = get_register(pc);
3413 set_pc(pc_reg + off);
3414 }
3415
3416 void Simulator::decodeType6(SimInstruction* instr) {
3417 decodeType6CoprocessorIns(instr);
3418 }
3419
3420 void Simulator::decodeType7(SimInstruction* instr) {
3421 if (instr->bit(24) == 1) {
3422 softwareInterrupt(instr);
3423 } else if (instr->bit(4) == 1 && instr->bits(11, 9) != 5) {
3424 decodeType7CoprocessorIns(instr);
3425 } else {
3426 decodeTypeVFP(instr);
3427 }
3428 }
3429
3430 void Simulator::decodeType7CoprocessorIns(SimInstruction* instr) {
3431 if (instr->bit(20) == 0) {
3432 // MCR, MCR2
3433 if (instr->coprocessorValue() == 15) {
3434 int opc1 = instr->bits(23, 21);
3435 int opc2 = instr->bits(7, 5);
3436 int CRn = instr->bits(19, 16);
3437 int CRm = instr->bits(3, 0);
3438 if (opc1 == 0 && opc2 == 4 && CRn == 7 && CRm == 10) {
3439 // ARMv6 DSB instruction. We do not use DSB.
3440 MOZ_CRASH("DSB not implemented");
3441 } else if (opc1 == 0 && opc2 == 5 && CRn == 7 && CRm == 10) {
3442 // ARMv6 DMB instruction.
3443 AtomicOperations::fenceSeqCst();
3444 } else if (opc1 == 0 && opc2 == 4 && CRn == 7 && CRm == 5) {
3445 // ARMv6 ISB instruction. We do not use ISB.
3446 MOZ_CRASH("ISB not implemented");
3447 } else {
3448 MOZ_CRASH();
3449 }
3450 } else {
3451 MOZ_CRASH();
3452 }
3453 } else {
3454 // MRC, MRC2
3455 MOZ_CRASH();
3456 }
3457 }
3458
3459 void Simulator::decodeTypeVFP(SimInstruction* instr) {
3460 MOZ_ASSERT(instr->typeValue() == 7 && instr->bit(24) == 0);
3461 MOZ_ASSERT(instr->bits(11, 9) == 0x5);
3462
3463 // Obtain double precision register codes.
3464 VFPRegPrecision precision =
3465 (instr->szValue() == 1) ? kDoublePrecision : kSinglePrecision;
3466 int vm = instr->VFPMRegValue(precision);
3467 int vd = instr->VFPDRegValue(precision);
3468 int vn = instr->VFPNRegValue(precision);
3469
3470 if (instr->bit(4) == 0) {
3471 if (instr->opc1Value() == 0x7) {
3472 // Other data processing instructions.
3473 if ((instr->opc2Value() == 0x0) && (instr->opc3Value() == 0x1)) {
3474 // vmov register to register.
3475 if (instr->szValue() == 0x1) {
3476 int m = instr->VFPMRegValue(kDoublePrecision);
3477 int d = instr->VFPDRegValue(kDoublePrecision);
3478 double temp;
3479 get_double_from_d_register(m, &temp);
3480 set_d_register_from_double(d, temp);
3481 } else {
3482 int m = instr->VFPMRegValue(kSinglePrecision);
3483 int d = instr->VFPDRegValue(kSinglePrecision);
3484 float temp;
3485 get_float_from_s_register(m, &temp);
3486 set_s_register_from_float(d, temp);
3487 }
3488 } else if ((instr->opc2Value() == 0x0) && (instr->opc3Value() == 0x3)) {
3489 // vabs
3490 if (instr->szValue() == 0x1) {
3491 union {
3492 double f64;
3493 uint64_t u64;
3494 } u;
3495 get_double_from_d_register(vm, &u.f64);
3496 u.u64 &= 0x7fffffffffffffffu;
3497 double dd_value = u.f64;
3498 canonicalizeNaN(&dd_value);
3499 set_d_register_from_double(vd, dd_value);
3500 } else {
3501 union {
3502 float f32;
3503 uint32_t u32;
3504 } u;
3505 get_float_from_s_register(vm, &u.f32);
3506 u.u32 &= 0x7fffffffu;
3507 float fd_value = u.f32;
3508 canonicalizeNaN(&fd_value);
3509 set_s_register_from_float(vd, fd_value);
3510 }
3511 } else if ((instr->opc2Value() == 0x1) && (instr->opc3Value() == 0x1)) {
3512 // vneg
3513 if (instr->szValue() == 0x1) {
3514 double dm_value;
3515 get_double_from_d_register(vm, &dm_value);
3516 double dd_value = -dm_value;
3517 canonicalizeNaN(&dd_value);
3518 set_d_register_from_double(vd, dd_value);
3519 } else {
3520 float fm_value;
3521 get_float_from_s_register(vm, &fm_value);
3522 float fd_value = -fm_value;
3523 canonicalizeNaN(&fd_value);
3524 set_s_register_from_float(vd, fd_value);
3525 }
3526 } else if ((instr->opc2Value() == 0x7) && (instr->opc3Value() == 0x3)) {
3527 decodeVCVTBetweenDoubleAndSingle(instr);
3528 } else if ((instr->opc2Value() == 0x8) && (instr->opc3Value() & 0x1)) {
3529 decodeVCVTBetweenFloatingPointAndInteger(instr);
3530 } else if ((instr->opc2Value() == 0xA) && (instr->opc3Value() == 0x3) &&
3531 (instr->bit(8) == 1)) {
3532 // vcvt.f64.s32 Dd, Dd, #<fbits>.
3533 int fraction_bits = 32 - ((instr->bits(3, 0) << 1) | instr->bit(5));
3534 int fixed_value = get_sinteger_from_s_register(vd * 2);
3535 double divide = 1 << fraction_bits;
3536 set_d_register_from_double(vd, fixed_value / divide);
3537 } else if (((instr->opc2Value() >> 1) == 0x6) &&
3538 (instr->opc3Value() & 0x1)) {
3539 decodeVCVTBetweenFloatingPointAndInteger(instr);
3540 } else if (((instr->opc2Value() == 0x4) || (instr->opc2Value() == 0x5)) &&
3541 (instr->opc3Value() & 0x1)) {
3542 decodeVCMP(instr);
3543 } else if (((instr->opc2Value() == 0x1)) && (instr->opc3Value() == 0x3)) {
3544 // vsqrt
3545 if (instr->szValue() == 0x1) {
3546 double dm_value;
3547 get_double_from_d_register(vm, &dm_value);
3548 double dd_value = std::sqrt(dm_value);
3549 canonicalizeNaN(&dd_value);
3550 set_d_register_from_double(vd, dd_value);
3551 } else {
3552 float fm_value;
3553 get_float_from_s_register(vm, &fm_value);
3554 float fd_value = std::sqrt(fm_value);
3555 canonicalizeNaN(&fd_value);
3556 set_s_register_from_float(vd, fd_value);
3557 }
3558 } else if (instr->opc3Value() == 0x0) {
3559 // vmov immediate.
3560 if (instr->szValue() == 0x1) {
3561 set_d_register_from_double(vd, instr->doubleImmedVmov());
3562 } else {
3563 // vmov.f32 immediate.
3564 set_s_register_from_float(vd, instr->float32ImmedVmov());
3565 }
3566 } else if ((instr->opc2Value() & ~0x1) == 0x2 &&
3567 (instr->opc3Value() & 0x1)) {
3568 decodeVCVTBetweenFloatingPointAndHalf(instr);
3569 } else {
3570 decodeVCVTBetweenFloatingPointAndIntegerFrac(instr);
3571 }
3572 } else if (instr->opc1Value() == 0x3) {
3573 if (instr->szValue() != 0x1) {
3574 if (instr->opc3Value() & 0x1) {
3575 // vsub
3576 float fn_value;
3577 get_float_from_s_register(vn, &fn_value);
3578 float fm_value;
3579 get_float_from_s_register(vm, &fm_value);
3580 float fd_value = fn_value - fm_value;
3581 canonicalizeNaN(&fd_value);
3582 set_s_register_from_float(vd, fd_value);
3583 } else {
3584 // vadd
3585 float fn_value;
3586 get_float_from_s_register(vn, &fn_value);
3587 float fm_value;
3588 get_float_from_s_register(vm, &fm_value);
3589 float fd_value = fn_value + fm_value;
3590 canonicalizeNaN(&fd_value);
3591 set_s_register_from_float(vd, fd_value);
3592 }
3593 } else {
3594 if (instr->opc3Value() & 0x1) {
3595 // vsub
3596 double dn_value;
3597 get_double_from_d_register(vn, &dn_value);
3598 double dm_value;
3599 get_double_from_d_register(vm, &dm_value);
3600 double dd_value = dn_value - dm_value;
3601 canonicalizeNaN(&dd_value);
3602 set_d_register_from_double(vd, dd_value);
3603 } else {
3604 // vadd
3605 double dn_value;
3606 get_double_from_d_register(vn, &dn_value);
3607 double dm_value;
3608 get_double_from_d_register(vm, &dm_value);
3609 double dd_value = dn_value + dm_value;
3610 canonicalizeNaN(&dd_value);
3611 set_d_register_from_double(vd, dd_value);
3612 }
3613 }
3614 } else if ((instr->opc1Value() == 0x2) && !(instr->opc3Value() & 0x1)) {
3615 // vmul
3616 if (instr->szValue() != 0x1) {
3617 float fn_value;
3618 get_float_from_s_register(vn, &fn_value);
3619 float fm_value;
3620 get_float_from_s_register(vm, &fm_value);
3621 float fd_value = fn_value * fm_value;
3622 canonicalizeNaN(&fd_value);
3623 set_s_register_from_float(vd, fd_value);
3624 } else {
3625 double dn_value;
3626 get_double_from_d_register(vn, &dn_value);
3627 double dm_value;
3628 get_double_from_d_register(vm, &dm_value);
3629 double dd_value = dn_value * dm_value;
3630 canonicalizeNaN(&dd_value);
3631 set_d_register_from_double(vd, dd_value);
3632 }
3633 } else if ((instr->opc1Value() == 0x0)) {
3634 // vmla, vmls
3635 const bool is_vmls = (instr->opc3Value() & 0x1);
3636
3637 if (instr->szValue() != 0x1) {
3638 MOZ_CRASH("Not used by V8.");
3639 }
3640
3641 double dd_val;
3642 get_double_from_d_register(vd, &dd_val);
3643 double dn_val;
3644 get_double_from_d_register(vn, &dn_val);
3645 double dm_val;
3646 get_double_from_d_register(vm, &dm_val);
3647
3648 // Note: we do the mul and add/sub in separate steps to avoid
3649 // getting a result with too high precision.
3650 set_d_register_from_double(vd, dn_val * dm_val);
3651 double temp;
3652 get_double_from_d_register(vd, &temp);
3653 if (is_vmls) {
3654 temp = dd_val - temp;
3655 } else {
3656 temp = dd_val + temp;
3657 }
3658 canonicalizeNaN(&temp);
3659 set_d_register_from_double(vd, temp);
3660 } else if ((instr->opc1Value() == 0x4) && !(instr->opc3Value() & 0x1)) {
3661 // vdiv
3662 if (instr->szValue() != 0x1) {
3663 float fn_value;
3664 get_float_from_s_register(vn, &fn_value);
3665 float fm_value;
3666 get_float_from_s_register(vm, &fm_value);
3667 float fd_value = fn_value / fm_value;
3668 div_zero_vfp_flag_ = (fm_value == 0);
3669 canonicalizeNaN(&fd_value);
3670 set_s_register_from_float(vd, fd_value);
3671 } else {
3672 double dn_value;
3673 get_double_from_d_register(vn, &dn_value);
3674 double dm_value;
3675 get_double_from_d_register(vm, &dm_value);
3676 double dd_value = dn_value / dm_value;
3677 div_zero_vfp_flag_ = (dm_value == 0);
3678 canonicalizeNaN(&dd_value);
3679 set_d_register_from_double(vd, dd_value);
3680 }
3681 } else {
3682 MOZ_CRASH();
3683 }
3684 } else {
3685 if (instr->VCValue() == 0x0 && instr->VAValue() == 0x0) {
3686 decodeVMOVBetweenCoreAndSinglePrecisionRegisters(instr);
3687 } else if ((instr->VLValue() == 0x0) && (instr->VCValue() == 0x1) &&
3688 (instr->bit(23) == 0x0)) {
3689 // vmov (ARM core register to scalar).
3690 int vd = instr->bits(19, 16) | (instr->bit(7) << 4);
3691 double dd_value;
3692 get_double_from_d_register(vd, &dd_value);
3693 int32_t data[2];
3694 memcpy(data, &dd_value, 8);
3695 data[instr->bit(21)] = get_register(instr->rtValue());
3696 memcpy(&dd_value, data, 8);
3697 set_d_register_from_double(vd, dd_value);
3698 } else if ((instr->VLValue() == 0x1) && (instr->VCValue() == 0x1) &&
3699 (instr->bit(23) == 0x0)) {
3700 // vmov (scalar to ARM core register).
3701 int vn = instr->bits(19, 16) | (instr->bit(7) << 4);
3702 double dn_value;
3703 get_double_from_d_register(vn, &dn_value);
3704 int32_t data[2];
3705 memcpy(data, &dn_value, 8);
3706 set_register(instr->rtValue(), data[instr->bit(21)]);
3707 } else if ((instr->VLValue() == 0x1) && (instr->VCValue() == 0x0) &&
3708 (instr->VAValue() == 0x7) && (instr->bits(19, 16) == 0x1)) {
3709 // vmrs
3710 uint32_t rt = instr->rtValue();
3711 if (rt == 0xF) {
3712 copy_FPSCR_to_APSR();
3713 } else {
3714 // Emulate FPSCR from the Simulator flags.
3715 uint32_t fpscr = (n_flag_FPSCR_ << 31) | (z_flag_FPSCR_ << 30) |
3716 (c_flag_FPSCR_ << 29) | (v_flag_FPSCR_ << 28) |
3717 (FPSCR_default_NaN_mode_ << 25) |
3718 (inexact_vfp_flag_ << 4) | (underflow_vfp_flag_ << 3) |
3719 (overflow_vfp_flag_ << 2) | (div_zero_vfp_flag_ << 1) |
3720 (inv_op_vfp_flag_ << 0) | (FPSCR_rounding_mode_);
3721 set_register(rt, fpscr);
3722 }
3723 } else if ((instr->VLValue() == 0x0) && (instr->VCValue() == 0x0) &&
3724 (instr->VAValue() == 0x7) && (instr->bits(19, 16) == 0x1)) {
3725 // vmsr
3726 uint32_t rt = instr->rtValue();
3727 if (rt == pc) {
3728 MOZ_CRASH();
3729 } else {
3730 uint32_t rt_value = get_register(rt);
3731 n_flag_FPSCR_ = (rt_value >> 31) & 1;
3732 z_flag_FPSCR_ = (rt_value >> 30) & 1;
3733 c_flag_FPSCR_ = (rt_value >> 29) & 1;
3734 v_flag_FPSCR_ = (rt_value >> 28) & 1;
3735 FPSCR_default_NaN_mode_ = (rt_value >> 25) & 1;
3736 inexact_vfp_flag_ = (rt_value >> 4) & 1;
3737 underflow_vfp_flag_ = (rt_value >> 3) & 1;
3738 overflow_vfp_flag_ = (rt_value >> 2) & 1;
3739 div_zero_vfp_flag_ = (rt_value >> 1) & 1;
3740 inv_op_vfp_flag_ = (rt_value >> 0) & 1;
3741 FPSCR_rounding_mode_ =
3742 static_cast<VFPRoundingMode>((rt_value)&kVFPRoundingModeMask);
3743 }
3744 } else {
3745 MOZ_CRASH();
3746 }
3747 }
3748 }
3749
3750 void Simulator::decodeVMOVBetweenCoreAndSinglePrecisionRegisters(
3751 SimInstruction* instr) {
3752 MOZ_ASSERT(instr->bit(4) == 1 && instr->VCValue() == 0x0 &&
3753 instr->VAValue() == 0x0);
3754
3755 int t = instr->rtValue();
3756 int n = instr->VFPNRegValue(kSinglePrecision);
3757 bool to_arm_register = (instr->VLValue() == 0x1);
3758 if (to_arm_register) {
3759 int32_t int_value = get_sinteger_from_s_register(n);
3760 set_register(t, int_value);
3761 } else {
3762 int32_t rs_val = get_register(t);
3763 set_s_register_from_sinteger(n, rs_val);
3764 }
3765 }
3766
3767 void Simulator::decodeVCMP(SimInstruction* instr) {
3768 MOZ_ASSERT((instr->bit(4) == 0) && (instr->opc1Value() == 0x7));
3769 MOZ_ASSERT(((instr->opc2Value() == 0x4) || (instr->opc2Value() == 0x5)) &&
3770 (instr->opc3Value() & 0x1));
3771 // Comparison.
3772
3773 VFPRegPrecision precision = kSinglePrecision;
3774 if (instr->szValue() == 1) {
3775 precision = kDoublePrecision;
3776 }
3777
3778 int d = instr->VFPDRegValue(precision);
3779 int m = 0;
3780 if (instr->opc2Value() == 0x4) {
3781 m = instr->VFPMRegValue(precision);
3782 }
3783
3784 if (precision == kDoublePrecision) {
3785 double dd_value;
3786 get_double_from_d_register(d, &dd_value);
3787 double dm_value = 0.0;
3788 if (instr->opc2Value() == 0x4) {
3789 get_double_from_d_register(m, &dm_value);
3790 }
3791
3792 // Raise exceptions for quiet NaNs if necessary.
3793 if (instr->bit(7) == 1) {
3794 if (std::isnan(dd_value)) {
3795 inv_op_vfp_flag_ = true;
3796 }
3797 }
3798 compute_FPSCR_Flags(dd_value, dm_value);
3799 } else {
3800 float fd_value;
3801 get_float_from_s_register(d, &fd_value);
3802 float fm_value = 0.0;
3803 if (instr->opc2Value() == 0x4) {
3804 get_float_from_s_register(m, &fm_value);
3805 }
3806
3807 // Raise exceptions for quiet NaNs if necessary.
3808 if (instr->bit(7) == 1) {
3809 if (std::isnan(fd_value)) {
3810 inv_op_vfp_flag_ = true;
3811 }
3812 }
3813 compute_FPSCR_Flags(fd_value, fm_value);
3814 }
3815 }
3816
3817 void Simulator::decodeVCVTBetweenDoubleAndSingle(SimInstruction* instr) {
3818 MOZ_ASSERT(instr->bit(4) == 0 && instr->opc1Value() == 0x7);
3819 MOZ_ASSERT(instr->opc2Value() == 0x7 && instr->opc3Value() == 0x3);
3820
3821 VFPRegPrecision dst_precision = kDoublePrecision;
3822 VFPRegPrecision src_precision = kSinglePrecision;
3823 if (instr->szValue() == 1) {
3824 dst_precision = kSinglePrecision;
3825 src_precision = kDoublePrecision;
3826 }
3827
3828 int dst = instr->VFPDRegValue(dst_precision);
3829 int src = instr->VFPMRegValue(src_precision);
3830
3831 if (dst_precision == kSinglePrecision) {
3832 double val;
3833 get_double_from_d_register(src, &val);
3834 set_s_register_from_float(dst, static_cast<float>(val));
3835 } else {
3836 float val;
3837 get_float_from_s_register(src, &val);
3838 set_d_register_from_double(dst, static_cast<double>(val));
3839 }
3840 }
3841
3842 static bool get_inv_op_vfp_flag(VFPRoundingMode mode, double val,
3843 bool unsigned_) {
3844 MOZ_ASSERT(mode == SimRN || mode == SimRM || mode == SimRZ);
3845 double max_uint = static_cast<double>(0xffffffffu);
3846 double max_int = static_cast<double>(INT32_MAX);
3847 double min_int = static_cast<double>(INT32_MIN);
3848
3849 // Check for NaN.
3850 if (val != val) {
3851 return true;
3852 }
3853
3854 // Check for overflow. This code works because 32bit integers can be exactly
3855 // represented by ieee-754 64bit floating-point values.
3856 switch (mode) {
3857 case SimRN:
3858 return unsigned_ ? (val >= (max_uint + 0.5)) || (val < -0.5)
3859 : (val >= (max_int + 0.5)) || (val < (min_int - 0.5));
3860 case SimRM:
3861 return unsigned_ ? (val >= (max_uint + 1.0)) || (val < 0)
3862 : (val >= (max_int + 1.0)) || (val < min_int);
3863 case SimRZ:
3864 return unsigned_ ? (val >= (max_uint + 1.0)) || (val <= -1)
3865 : (val >= (max_int + 1.0)) || (val <= (min_int - 1.0));
3866 default:
3867 MOZ_CRASH();
3868 return true;
3869 }
3870 }
3871
3872 // We call this function only if we had a vfp invalid exception.
3873 // It returns the correct saturated value.
3874 static int VFPConversionSaturate(double val, bool unsigned_res) {
3875 if (val != val) { // NaN.
3876 return 0;
3877 }
3878 if (unsigned_res) {
3879 return (val < 0) ? 0 : 0xffffffffu;
3880 }
3881 return (val < 0) ? INT32_MIN : INT32_MAX;
3882 }
3883
3884 void Simulator::decodeVCVTBetweenFloatingPointAndInteger(
3885 SimInstruction* instr) {
3886 MOZ_ASSERT((instr->bit(4) == 0) && (instr->opc1Value() == 0x7) &&
3887 (instr->bits(27, 23) == 0x1D));
3888 MOZ_ASSERT(
3889 ((instr->opc2Value() == 0x8) && (instr->opc3Value() & 0x1)) ||
3890 (((instr->opc2Value() >> 1) == 0x6) && (instr->opc3Value() & 0x1)));
3891
3892 // Conversion between floating-point and integer.
3893 bool to_integer = (instr->bit(18) == 1);
3894
3895 VFPRegPrecision src_precision =
3896 (instr->szValue() == 1) ? kDoublePrecision : kSinglePrecision;
3897
3898 if (to_integer) {
3899 // We are playing with code close to the C++ standard's limits below,
3900 // hence the very simple code and heavy checks.
3901 //
3902 // Note: C++ defines default type casting from floating point to integer
3903 // as (close to) rounding toward zero ("fractional part discarded").
3904
3905 int dst = instr->VFPDRegValue(kSinglePrecision);
3906 int src = instr->VFPMRegValue(src_precision);
3907
3908 // Bit 7 in vcvt instructions indicates if we should use the FPSCR
3909 // rounding mode or the default Round to Zero mode.
3910 VFPRoundingMode mode = (instr->bit(7) != 1) ? FPSCR_rounding_mode_ : SimRZ;
3911 MOZ_ASSERT(mode == SimRM || mode == SimRZ || mode == SimRN);
3912
3913 bool unsigned_integer = (instr->bit(16) == 0);
3914 bool double_precision = (src_precision == kDoublePrecision);
3915
3916 double val;
3917 if (double_precision) {
3918 get_double_from_d_register(src, &val);
3919 } else {
3920 float fval;
3921 get_float_from_s_register(src, &fval);
3922 val = double(fval);
3923 }
3924
3925 int temp = unsigned_integer ? static_cast<uint32_t>(val)
3926 : static_cast<int32_t>(val);
3927
3928 inv_op_vfp_flag_ = get_inv_op_vfp_flag(mode, val, unsigned_integer);
3929
3930 double abs_diff = unsigned_integer
3931 ? std::fabs(val - static_cast<uint32_t>(temp))
3932 : std::fabs(val - temp);
3933
3934 inexact_vfp_flag_ = (abs_diff != 0);
3935
3936 if (inv_op_vfp_flag_) {
3937 temp = VFPConversionSaturate(val, unsigned_integer);
3938 } else {
3939 switch (mode) {
3940 case SimRN: {
3941 int val_sign = (val > 0) ? 1 : -1;
3942 if (abs_diff > 0.5) {
3943 temp += val_sign;
3944 } else if (abs_diff == 0.5) {
3945 // Round to even if exactly halfway.
3946 temp = ((temp % 2) == 0) ? temp : temp + val_sign;
3947 }
3948 break;
3949 }
3950
3951 case SimRM:
3952 temp = temp > val ? temp - 1 : temp;
3953 break;
3954
3955 case SimRZ:
3956 // Nothing to do.
3957 break;
3958
3959 default:
3960 MOZ_CRASH();
3961 }
3962 }
3963
3964 // Update the destination register.
3965 set_s_register_from_sinteger(dst, temp);
3966 } else {
3967 bool unsigned_integer = (instr->bit(7) == 0);
3968 int dst = instr->VFPDRegValue(src_precision);
3969 int src = instr->VFPMRegValue(kSinglePrecision);
3970
3971 int val = get_sinteger_from_s_register(src);
3972
3973 if (src_precision == kDoublePrecision) {
3974 if (unsigned_integer) {
3975 set_d_register_from_double(
3976 dst, static_cast<double>(static_cast<uint32_t>(val)));
3977 } else {
3978 set_d_register_from_double(dst, static_cast<double>(val));
3979 }
3980 } else {
3981 if (unsigned_integer) {
3982 set_s_register_from_float(
3983 dst, static_cast<float>(static_cast<uint32_t>(val)));
3984 } else {
3985 set_s_register_from_float(dst, static_cast<float>(val));
3986 }
3987 }
3988 }
3989 }
3990
3991 // A VFPv3 specific instruction.
3992 void Simulator::decodeVCVTBetweenFloatingPointAndIntegerFrac(
3993 SimInstruction* instr) {
3994 MOZ_ASSERT(instr->bits(27, 24) == 0xE && instr->opc1Value() == 0x7 &&
3995 instr->bit(19) == 1 && instr->bit(17) == 1 &&
3996 instr->bits(11, 9) == 0x5 && instr->bit(6) == 1 &&
3997 instr->bit(4) == 0);
3998
3999 int size = (instr->bit(7) == 1) ? 32 : 16;
4000
4001 int fraction_bits = size - ((instr->bits(3, 0) << 1) | instr->bit(5));
4002 double mult = 1 << fraction_bits;
4003
4004 MOZ_ASSERT(size == 32); // Only handling size == 32 for now.
4005
4006 // Conversion between floating-point and integer.
4007 bool to_fixed = (instr->bit(18) == 1);
4008
4009 VFPRegPrecision precision =
4010 (instr->szValue() == 1) ? kDoublePrecision : kSinglePrecision;
4011
4012 if (to_fixed) {
4013 // We are playing with code close to the C++ standard's limits below,
4014 // hence the very simple code and heavy checks.
4015 //
4016 // Note: C++ defines default type casting from floating point to integer
4017 // as (close to) rounding toward zero ("fractional part discarded").
4018
4019 int dst = instr->VFPDRegValue(precision);
4020
4021 bool unsigned_integer = (instr->bit(16) == 1);
4022 bool double_precision = (precision == kDoublePrecision);
4023
4024 double val;
4025 if (double_precision) {
4026 get_double_from_d_register(dst, &val);
4027 } else {
4028 float fval;
4029 get_float_from_s_register(dst, &fval);
4030 val = double(fval);
4031 }
4032
4033 // Scale value by specified number of fraction bits.
4034 val *= mult;
4035
4036 // Rounding down towards zero. No need to account for the rounding error
4037 // as this instruction always rounds down towards zero. See SimRZ below.
4038 int temp = unsigned_integer ? static_cast<uint32_t>(val)
4039 : static_cast<int32_t>(val);
4040
4041 inv_op_vfp_flag_ = get_inv_op_vfp_flag(SimRZ, val, unsigned_integer);
4042
4043 double abs_diff = unsigned_integer
4044 ? std::fabs(val - static_cast<uint32_t>(temp))
4045 : std::fabs(val - temp);
4046
4047 inexact_vfp_flag_ = (abs_diff != 0);
4048
4049 if (inv_op_vfp_flag_) {
4050 temp = VFPConversionSaturate(val, unsigned_integer);
4051 }
4052
4053 // Update the destination register.
4054 if (double_precision) {
4055 uint32_t dbl[2];
4056 dbl[0] = temp;
4057 dbl[1] = 0;
4058 set_d_register(dst, dbl);
4059 } else {
4060 set_s_register_from_sinteger(dst, temp);
4061 }
4062 } else {
4063 MOZ_CRASH(); // Not implemented, fixed to float.
4064 }
4065 }
4066
4067 void Simulator::decodeVCVTBetweenFloatingPointAndHalf(SimInstruction* instr) {
4068 MOZ_ASSERT(instr->bit(4) == 0 && instr->opc1Value() == 0x7);
4069 MOZ_ASSERT((instr->opc2Value() & ~0x1) == 0x2 && (instr->opc3Value() & 0x1));
4070
4071 bool top_half = (instr->bit(7) == 1);
4072 bool to_half = (instr->bit(16) == 1);
4073
4074 VFPRegPrecision dst_precision = kSinglePrecision;
4075 VFPRegPrecision src_precision = kSinglePrecision;
4076 if (instr->szValue() == 1) {
4077 if (to_half) {
4078 src_precision = kDoublePrecision;
4079 } else {
4080 dst_precision = kDoublePrecision;
4081 }
4082 }
4083
4084 int dst = instr->VFPDRegValue(dst_precision);
4085 int src = instr->VFPMRegValue(src_precision);
4086
4087 if (to_half) {
4088 uint32_t f16bits;
4089 if (src_precision == kSinglePrecision) {
4090 float val;
4091 get_float_from_s_register(src, &val);
4092 f16bits = js::float16{val}.toRawBits();
4093 } else {
4094 double val;
4095 get_double_from_d_register(src, &val);
4096 f16bits = js::float16{val}.toRawBits();
4097 }
4098
4099 float val;
4100 get_float_from_s_register(dst, &val);
4101 uint32_t f32bits = mozilla::BitwiseCast<uint32_t>(val);
4102
4103 if (top_half) {
4104 f32bits = (f16bits << 16) | (f32bits & 0xffff);
4105 } else {
4106 f32bits = (f32bits & 0xffff'0000) | f16bits;
4107 }
4108
4109 float rval;
4110 mozilla::BitwiseCast(f32bits, &rval);
4111
4112 set_s_register_from_float(dst, rval);
4113 } else {
4114 float val;
4115 get_float_from_s_register(src, &val);
4116 uint32_t f32bits = mozilla::BitwiseCast<uint32_t>(val);
4117
4118 if (top_half) {
4119 f32bits >>= 16;
4120 }
4121
4122 auto rval = js::float16::fromRawBits(uint16_t(f32bits));
4123
4124 if (dst_precision == kSinglePrecision) {
4125 set_s_register_from_float(dst, static_cast<float>(rval));
4126 } else {
4127 set_d_register_from_double(dst, static_cast<double>(rval));
4128 }
4129 }
4130 }
4131
4132 void Simulator::decodeType6CoprocessorIns(SimInstruction* instr) {
4133 MOZ_ASSERT(instr->typeValue() == 6);
4134
4135 if (instr->coprocessorValue() == 0xA) {
4136 switch (instr->opcodeValue()) {
4137 case 0x8:
4138 case 0xA:
4139 case 0xC:
4140 case 0xE: { // Load and store single precision float to memory.
4141 int rn = instr->rnValue();
4142 int vd = instr->VFPDRegValue(kSinglePrecision);
4143 int offset = instr->immed8Value();
4144 if (!instr->hasU()) {
4145 offset = -offset;
4146 }
4147
4148 int32_t address = get_register(rn) + 4 * offset;
4149 if (instr->hasL()) {
4150 // Load double from memory: vldr.
4151 set_s_register_from_sinteger(vd, readW(address, instr));
4152 } else {
4153 // Store double to memory: vstr.
4154 writeW(address, get_sinteger_from_s_register(vd), instr);
4155 }
4156 break;
4157 }
4158 case 0x4:
4159 case 0x5:
4160 case 0x6:
4161 case 0x7:
4162 case 0x9:
4163 case 0xB:
4164 // Load/store multiple single from memory: vldm/vstm.
4165 handleVList(instr);
4166 break;
4167 default:
4168 MOZ_CRASH();
4169 }
4170 } else if (instr->coprocessorValue() == 0xB) {
4171 switch (instr->opcodeValue()) {
4172 case 0x2:
4173 // Load and store double to two GP registers
4174 if (instr->bits(7, 6) != 0 || instr->bit(4) != 1) {
4175 MOZ_CRASH(); // Not used atm.
4176 } else {
4177 int rt = instr->rtValue();
4178 int rn = instr->rnValue();
4179 int vm = instr->VFPMRegValue(kDoublePrecision);
4180 if (instr->hasL()) {
4181 int32_t data[2];
4182 double d;
4183 get_double_from_d_register(vm, &d);
4184 memcpy(data, &d, 8);
4185 set_register(rt, data[0]);
4186 set_register(rn, data[1]);
4187 } else {
4188 int32_t data[] = {get_register(rt), get_register(rn)};
4189 double d;
4190 memcpy(&d, data, 8);
4191 set_d_register_from_double(vm, d);
4192 }
4193 }
4194 break;
4195 case 0x8:
4196 case 0xA:
4197 case 0xC:
4198 case 0xE: { // Load and store double to memory.
4199 int rn = instr->rnValue();
4200 int vd = instr->VFPDRegValue(kDoublePrecision);
4201 int offset = instr->immed8Value();
4202 if (!instr->hasU()) {
4203 offset = -offset;
4204 }
4205 int32_t address = get_register(rn) + 4 * offset;
4206 if (instr->hasL()) {
4207 // Load double from memory: vldr.
4208 uint64_t data = readQ(address, instr);
4209 double val;
4210 memcpy(&val, &data, 8);
4211 set_d_register_from_double(vd, val);
4212 } else {
4213 // Store double to memory: vstr.
4214 uint64_t data;
4215 double val;
4216 get_double_from_d_register(vd, &val);
4217 memcpy(&data, &val, 8);
4218 writeQ(address, data, instr);
4219 }
4220 break;
4221 }
4222 case 0x4:
4223 case 0x5:
4224 case 0x6:
4225 case 0x7:
4226 case 0x9:
4227 case 0xB:
4228 // Load/store multiple double from memory: vldm/vstm.
4229 handleVList(instr);
4230 break;
4231 default:
4232 MOZ_CRASH();
4233 }
4234 } else {
4235 MOZ_CRASH();
4236 }
4237 }
4238
4239 void Simulator::decodeSpecialCondition(SimInstruction* instr) {
4240 switch (instr->specialValue()) {
4241 case 5:
4242 if (instr->bits(18, 16) == 0 && instr->bits(11, 6) == 0x28 &&
4243 instr->bit(4) == 1) {
4244 // vmovl signed
4245 if ((instr->vdValue() & 1) != 0) {
4246 MOZ_CRASH("Undefined behavior");
4247 }
4248 int Vd = (instr->bit(22) << 3) | (instr->vdValue() >> 1);
4249 int Vm = (instr->bit(5) << 4) | instr->vmValue();
4250 int imm3 = instr->bits(21, 19);
4251 if (imm3 != 1 && imm3 != 2 && imm3 != 4) {
4252 MOZ_CRASH();
4253 }
4254 int esize = 8 * imm3;
4255 int elements = 64 / esize;
4256 int8_t from[8];
4257 get_d_register(Vm, reinterpret_cast<uint64_t*>(from));
4258 int16_t to[8];
4259 int e = 0;
4260 while (e < elements) {
4261 to[e] = from[e];
4262 e++;
4263 }
4264 set_q_register(Vd, reinterpret_cast<uint64_t*>(to));
4265 } else {
4266 MOZ_CRASH();
4267 }
4268 break;
4269 case 7:
4270 if (instr->bits(18, 16) == 0 && instr->bits(11, 6) == 0x28 &&
4271 instr->bit(4) == 1) {
4272 // vmovl unsigned.
4273 if ((instr->vdValue() & 1) != 0) {
4274 MOZ_CRASH("Undefined behavior");
4275 }
4276 int Vd = (instr->bit(22) << 3) | (instr->vdValue() >> 1);
4277 int Vm = (instr->bit(5) << 4) | instr->vmValue();
4278 int imm3 = instr->bits(21, 19);
4279 if (imm3 != 1 && imm3 != 2 && imm3 != 4) {
4280 MOZ_CRASH();
4281 }
4282 int esize = 8 * imm3;
4283 int elements = 64 / esize;
4284 uint8_t from[8];
4285 get_d_register(Vm, reinterpret_cast<uint64_t*>(from));
4286 uint16_t to[8];
4287 int e = 0;
4288 while (e < elements) {
4289 to[e] = from[e];
4290 e++;
4291 }
4292 set_q_register(Vd, reinterpret_cast<uint64_t*>(to));
4293 } else {
4294 MOZ_CRASH();
4295 }
4296 break;
4297 case 8:
4298 if (instr->bits(21, 20) == 0) {
4299 // vst1
4300 int Vd = (instr->bit(22) << 4) | instr->vdValue();
4301 int Rn = instr->vnValue();
4302 int type = instr->bits(11, 8);
4303 int Rm = instr->vmValue();
4304 int32_t address = get_register(Rn);
4305 int regs = 0;
4306 switch (type) {
4307 case nlt_1:
4308 regs = 1;
4309 break;
4310 case nlt_2:
4311 regs = 2;
4312 break;
4313 case nlt_3:
4314 regs = 3;
4315 break;
4316 case nlt_4:
4317 regs = 4;
4318 break;
4319 default:
4320 MOZ_CRASH();
4321 break;
4322 }
4323 int r = 0;
4324 while (r < regs) {
4325 uint32_t data[2];
4326 get_d_register(Vd + r, data);
4327 // TODO: We should AllowUnaligned here only if the alignment attribute
4328 // of the instruction calls for default alignment.
4329 //
4330 // Use writeQ to get handling of traps right. (The spec says to
4331 // perform two individual word writes, but let's not worry about
4332 // that.)
4333 writeQ(address, (uint64_t(data[1]) << 32) | uint64_t(data[0]), instr,
4334 AllowUnaligned);
4335 address += 8;
4336 r++;
4337 }
4338 if (Rm != 15) {
4339 if (Rm == 13) {
4340 set_register(Rn, address);
4341 } else {
4342 set_register(Rn, get_register(Rn) + get_register(Rm));
4343 }
4344 }
4345 } else if (instr->bits(21, 20) == 2) {
4346 // vld1
4347 int Vd = (instr->bit(22) << 4) | instr->vdValue();
4348 int Rn = instr->vnValue();
4349 int type = instr->bits(11, 8);
4350 int Rm = instr->vmValue();
4351 int32_t address = get_register(Rn);
4352 int regs = 0;
4353 switch (type) {
4354 case nlt_1:
4355 regs = 1;
4356 break;
4357 case nlt_2:
4358 regs = 2;
4359 break;
4360 case nlt_3:
4361 regs = 3;
4362 break;
4363 case nlt_4:
4364 regs = 4;
4365 break;
4366 default:
4367 MOZ_CRASH();
4368 break;
4369 }
4370 int r = 0;
4371 while (r < regs) {
4372 uint32_t data[2];
4373 // TODO: We should AllowUnaligned here only if the alignment attribute
4374 // of the instruction calls for default alignment.
4375 //
4376 // Use readQ to get handling of traps right. (The spec says to
4377 // perform two individual word reads, but let's not worry about that.)
4378 uint64_t tmp = readQ(address, instr, AllowUnaligned);
4379 data[0] = tmp;
4380 data[1] = tmp >> 32;
4381 set_d_register(Vd + r, data);
4382 address += 8;
4383 r++;
4384 }
4385 if (Rm != 15) {
4386 if (Rm == 13) {
4387 set_register(Rn, address);
4388 } else {
4389 set_register(Rn, get_register(Rn) + get_register(Rm));
4390 }
4391 }
4392 } else {
4393 MOZ_CRASH();
4394 }
4395 break;
4396 case 9:
4397 if (instr->bits(9, 8) == 0) {
4398 int Vd = (instr->bit(22) << 4) | instr->vdValue();
4399 int Rn = instr->vnValue();
4400 int size = instr->bits(11, 10);
4401 int Rm = instr->vmValue();
4402 int index = instr->bits(7, 5);
4403 int align = instr->bit(4);
4404 int32_t address = get_register(Rn);
4405 if (size != 2 || align) {
4406 MOZ_CRASH("NYI");
4407 }
4408 int a = instr->bits(5, 4);
4409 if (a != 0 && a != 3) {
4410 MOZ_CRASH("Unspecified");
4411 }
4412 if (index > 1) {
4413 Vd++;
4414 index -= 2;
4415 }
4416 uint32_t data[2];
4417 get_d_register(Vd, data);
4418 switch (instr->bits(21, 20)) {
4419 case 0:
4420 // vst1 single element from one lane
4421 writeW(address, data[index], instr, AllowUnaligned);
4422 break;
4423 case 2:
4424 // vld1 single element to one lane
4425 data[index] = readW(address, instr, AllowUnaligned);
4426 set_d_register(Vd, data);
4427 break;
4428 default:
4429 MOZ_CRASH("NYI");
4430 }
4431 address += 4;
4432 if (Rm != 15) {
4433 if (Rm == 13) {
4434 set_register(Rn, address);
4435 } else {
4436 set_register(Rn, get_register(Rn) + get_register(Rm));
4437 }
4438 }
4439 } else {
4440 MOZ_CRASH();
4441 }
4442 break;
4443 case 0xA:
4444 if (instr->bits(31, 20) == 0xf57) {
4445 switch (instr->bits(7, 4)) {
4446 case 1: // CLREX
4447 exclusiveMonitorClear();
4448 break;
4449 case 5: // DMB
4450 AtomicOperations::fenceSeqCst();
4451 break;
4452 case 4: // DSB
4453 // We do not use DSB.
4454 MOZ_CRASH("DSB unimplemented");
4455 case 6: // ISB
4456 // We do not use ISB.
4457 MOZ_CRASH("ISB unimplemented");
4458 default:
4459 MOZ_CRASH();
4460 }
4461 } else {
4462 MOZ_CRASH();
4463 }
4464 break;
4465 case 0xB:
4466 if (instr->bits(22, 20) == 5 && instr->bits(15, 12) == 0xf) {
4467 // pld: ignore instruction.
4468 } else {
4469 MOZ_CRASH();
4470 }
4471 break;
4472 case 0x1C:
4473 case 0x1D:
4474 if (instr->bit(4) == 1 && instr->bits(11, 9) != 5) {
4475 // MCR, MCR2, MRC, MRC2 with cond == 15
4476 decodeType7CoprocessorIns(instr);
4477 } else {
4478 MOZ_CRASH();
4479 }
4480 break;
4481 default:
4482 MOZ_CRASH();
4483 }
4484 }
4485
4486 // Executes the current instruction.
4487 void Simulator::instructionDecode(SimInstruction* instr) {
4488 if (!SimulatorProcess::ICacheCheckingDisableCount) {
4489 AutoLockSimulatorCache als;
4490 SimulatorProcess::checkICacheLocked(instr);
4491 }
4492
4493 pc_modified_ = false;
4494
4495 static const uint32_t kSpecialCondition = 15 << 28;
4496 if (instr->conditionField() == kSpecialCondition) {
4497 decodeSpecialCondition(instr);
4498 } else if (conditionallyExecute(instr)) {
4499 switch (instr->typeValue()) {
4500 case 0:
4501 case 1:
4502 decodeType01(instr);
4503 break;
4504 case 2:
4505 decodeType2(instr);
4506 break;
4507 case 3:
4508 decodeType3(instr);
4509 break;
4510 case 4:
4511 decodeType4(instr);
4512 break;
4513 case 5:
4514 decodeType5(instr);
4515 break;
4516 case 6:
4517 decodeType6(instr);
4518 break;
4519 case 7:
4520 decodeType7(instr);
4521 break;
4522 default:
4523 MOZ_CRASH();
4524 break;
4525 }
4526 // If the instruction is a non taken conditional stop, we need to skip
4527 // the inlined message address.
4528 } else if (instr->isStop()) {
4529 set_pc(get_pc() + 2 * SimInstruction::kInstrSize);
4530 }
4531 if (!pc_modified_) {
4532 set_register(pc,
4533 reinterpret_cast<int32_t>(instr) + SimInstruction::kInstrSize);
4534 }
4535 }
4536
4537 void Simulator::enable_single_stepping(SingleStepCallback cb, void* arg) {
4538 single_stepping_ = true;
4539 single_step_callback_ = cb;
4540 single_step_callback_arg_ = arg;
4541 single_step_callback_(single_step_callback_arg_, this, (void*)get_pc());
4542 }
4543
4544 void Simulator::disable_single_stepping() {
4545 if (!single_stepping_) {
4546 return;
4547 }
4548 single_step_callback_(single_step_callback_arg_, this, (void*)get_pc());
4549 single_stepping_ = false;
4550 single_step_callback_ = nullptr;
4551 single_step_callback_arg_ = nullptr;
4552 }
4553
4554 template <bool EnableStopSimAt>
4555 void Simulator::execute() {
4556 if (single_stepping_) {
4557 single_step_callback_(single_step_callback_arg_, this, nullptr);
4558 }
4559
4560 // Get the PC to simulate. Cannot use the accessor here as we need the raw
4561 // PC value and not the one used as input to arithmetic instructions.
4562 int program_counter = get_pc();
4563
4564 while (program_counter != end_sim_pc) {
4565 if (EnableStopSimAt && (icount_ == Simulator::StopSimAt)) {
4566 fprintf(stderr, "\nStopped simulation at icount %lld\n", icount_);
4567 ArmDebugger dbg(this);
4568 dbg.debug();
4569 } else {
4570 if (single_stepping_) {
4571 single_step_callback_(single_step_callback_arg_, this,
4572 (void*)program_counter);
4573 }
4574 SimInstruction* instr =
4575 reinterpret_cast<SimInstruction*>(program_counter);
4576 instructionDecode(instr);
4577 icount_++;
4578 }
4579 program_counter = get_pc();
4580 }
4581
4582 if (single_stepping_) {
4583 single_step_callback_(single_step_callback_arg_, this, nullptr);
4584 }
4585 }
4586
4587 void Simulator::callInternal(uint8_t* entry) {
4588 // Prepare to execute the code at entry.
4589 set_register(pc, reinterpret_cast<int32_t>(entry));
4590
4591 // Put down marker for end of simulation. The simulator will stop simulation
4592 // when the PC reaches this value. By saving the "end simulation" value into
4593 // the LR the simulation stops when returning to this call point.
4594 set_register(lr, end_sim_pc);
4595
4596 // Remember the values of callee-saved registers. The code below assumes
4597 // that r9 is not used as sb (static base) in simulator code and therefore
4598 // is regarded as a callee-saved register.
4599 int32_t r4_val = get_register(r4);
4600 int32_t r5_val = get_register(r5);
4601 int32_t r6_val = get_register(r6);
4602 int32_t r7_val = get_register(r7);
4603 int32_t r8_val = get_register(r8);
4604 int32_t r9_val = get_register(r9);
4605 int32_t r10_val = get_register(r10);
4606 int32_t r11_val = get_register(r11);
4607
4608 // Remember d8 to d15 which are callee-saved.
4609 uint64_t d8_val;
4610 get_d_register(d8, &d8_val);
4611 uint64_t d9_val;
4612 get_d_register(d9, &d9_val);
4613 uint64_t d10_val;
4614 get_d_register(d10, &d10_val);
4615 uint64_t d11_val;
4616 get_d_register(d11, &d11_val);
4617 uint64_t d12_val;
4618 get_d_register(d12, &d12_val);
4619 uint64_t d13_val;
4620 get_d_register(d13, &d13_val);
4621 uint64_t d14_val;
4622 get_d_register(d14, &d14_val);
4623 uint64_t d15_val;
4624 get_d_register(d15, &d15_val);
4625
4626 // Set up the callee-saved registers with a known value. To be able to check
4627 // that they are preserved properly across JS execution.
4628 int32_t callee_saved_value = uint32_t(icount_);
4629 uint64_t callee_saved_value_d = uint64_t(icount_);
4630
4631 if (!skipCalleeSavedRegsCheck) {
4632 set_register(r4, callee_saved_value);
4633 set_register(r5, callee_saved_value);
4634 set_register(r6, callee_saved_value);
4635 set_register(r7, callee_saved_value);
4636 set_register(r8, callee_saved_value);
4637 set_register(r9, callee_saved_value);
4638 set_register(r10, callee_saved_value);
4639 set_register(r11, callee_saved_value);
4640
4641 set_d_register(d8, &callee_saved_value_d);
4642 set_d_register(d9, &callee_saved_value_d);
4643 set_d_register(d10, &callee_saved_value_d);
4644 set_d_register(d11, &callee_saved_value_d);
4645 set_d_register(d12, &callee_saved_value_d);
4646 set_d_register(d13, &callee_saved_value_d);
4647 set_d_register(d14, &callee_saved_value_d);
4648 set_d_register(d15, &callee_saved_value_d);
4649 }
4650 // Start the simulation.
4651 if (Simulator::StopSimAt != -1L) {
4652 execute<true>();
4653 } else {
4654 execute<false>();
4655 }
4656
4657 if (!skipCalleeSavedRegsCheck) {
4658 // Check that the callee-saved registers have been preserved.
4659 MOZ_ASSERT(callee_saved_value == get_register(r4));
4660 MOZ_ASSERT(callee_saved_value == get_register(r5));
4661 MOZ_ASSERT(callee_saved_value == get_register(r6));
4662 MOZ_ASSERT(callee_saved_value == get_register(r7));
4663 MOZ_ASSERT(callee_saved_value == get_register(r8));
4664 MOZ_ASSERT(callee_saved_value == get_register(r9));
4665 MOZ_ASSERT(callee_saved_value == get_register(r10));
4666 MOZ_ASSERT(callee_saved_value == get_register(r11));
4667
4668 uint64_t value;
4669 get_d_register(d8, &value);
4670 MOZ_ASSERT(callee_saved_value_d == value);
4671 get_d_register(d9, &value);
4672 MOZ_ASSERT(callee_saved_value_d == value);
4673 get_d_register(d10, &value);
4674 MOZ_ASSERT(callee_saved_value_d == value);
4675 get_d_register(d11, &value);
4676 MOZ_ASSERT(callee_saved_value_d == value);
4677 get_d_register(d12, &value);
4678 MOZ_ASSERT(callee_saved_value_d == value);
4679 get_d_register(d13, &value);
4680 MOZ_ASSERT(callee_saved_value_d == value);
4681 get_d_register(d14, &value);
4682 MOZ_ASSERT(callee_saved_value_d == value);
4683 get_d_register(d15, &value);
4684 MOZ_ASSERT(callee_saved_value_d == value);
4685
4686 // Restore callee-saved registers with the original value.
4687 set_register(r4, r4_val);
4688 set_register(r5, r5_val);
4689 set_register(r6, r6_val);
4690 set_register(r7, r7_val);
4691 set_register(r8, r8_val);
4692 set_register(r9, r9_val);
4693 set_register(r10, r10_val);
4694 set_register(r11, r11_val);
4695
4696 set_d_register(d8, &d8_val);
4697 set_d_register(d9, &d9_val);
4698 set_d_register(d10, &d10_val);
4699 set_d_register(d11, &d11_val);
4700 set_d_register(d12, &d12_val);
4701 set_d_register(d13, &d13_val);
4702 set_d_register(d14, &d14_val);
4703 set_d_register(d15, &d15_val);
4704 }
4705 }
4706
4707 int32_t Simulator::call(uint8_t* entry, int argument_count, ...) {
4708 va_list parameters;
4709 va_start(parameters, argument_count);
4710
4711 // First four arguments passed in registers.
4712 if (argument_count >= 1) {
4713 set_register(r0, va_arg(parameters, int32_t));
4714 }
4715 if (argument_count >= 2) {
4716 set_register(r1, va_arg(parameters, int32_t));
4717 }
4718 if (argument_count >= 3) {
4719 set_register(r2, va_arg(parameters, int32_t));
4720 }
4721 if (argument_count >= 4) {
4722 set_register(r3, va_arg(parameters, int32_t));
4723 }
4724
4725 // Remaining arguments passed on stack.
4726 int original_stack = get_register(sp);
4727 int entry_stack = original_stack;
4728 if (argument_count >= 4) {
4729 entry_stack -= (argument_count - 4) * sizeof(int32_t);
4730 }
4731
4732 entry_stack &= ~ABIStackAlignment;
4733
4734 // Store remaining arguments on stack, from low to high memory.
4735 intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack);
4736 for (int i = 4; i < argument_count; i++) {
4737 stack_argument[i - 4] = va_arg(parameters, int32_t);
4738 }
4739 va_end(parameters);
4740 set_register(sp, entry_stack);
4741
4742 callInternal(entry);
4743
4744 // Pop stack passed arguments.
4745 MOZ_ASSERT(entry_stack == get_register(sp));
4746 set_register(sp, original_stack);
4747
4748 int32_t result = get_register(r0);
4749 return result;
4750 }
4751
4752 Simulator* Simulator::Current() {
4753 JSContext* cx = TlsContext.get();
4754 MOZ_ASSERT(CurrentThreadCanAccessRuntime(cx->runtime()));
4755 return cx->simulator();
4756 }
4757
4758 } // namespace jit
4759 } // namespace js
4760
4761 js::jit::Simulator* JSContext::simulator() const { return simulator_; }