From c8d2615ea1cc6dd12e127598430a0372c26f25d7 Mon Sep 17 00:00:00 2001 From: MunyDev Date: Mon, 19 Dec 2022 15:54:29 -0500 Subject: [PATCH] First Release! --- .cargo/config | 2 + .editorconfig | 6 + .gitattributes | 2 + .github/workflows/main.yml | 82 + .github/workflows/release.yml | 38 + .gitignore | 27 + .jshint.json | 25 + .rustfmt.toml | 9 + Cargo.toml | 29 + LICENSE | 22 + Makefile | 339 + Readme.md | 184 + bios/.gitignore | 1 + bios/COPYING.LESSER | 165 + bios/fetch-and-build-seabios.sh | 13 + bios/seabios-debug.config | 117 + bios/seabios.config | 114 + debug.html | 363 + docs/.gitignore | 1 + docs/archlinux.md | 490 + docs/filesystem.md | 27 + docs/linux-9p-image.md | 58 + docs/networking.md | 15 + docs/sse-shifts.txt | 39 + docs/windows-xp.md | 75 + examples/arch.html | 78 + examples/async_load.html | 43 + examples/basic.html | 33 + examples/debian.html | 26 + examples/destroy.html | 34 + examples/lang.html | 77 + examples/lua.html | 121 + examples/nodejs.js | 47 + examples/nodejs_state.js | 66 + examples/save_restore.html | 94 + examples/serial.html | 87 + examples/two_instances.html | 88 + examples/worker.html | 34 + examples/worker.js | 29 + gen/generate_analyzer.js | 486 + gen/generate_interpreter.js | 492 + gen/generate_jit.js | 563 + gen/rust_ast.js | 83 + gen/util.js | 54 + gen/x86_table.js | 976 + index.html | 290 + lib/9p.js | 856 + lib/filesystem.js | 2001 + lib/jor1k.js | 107 + lib/marshall.js | 133 + lib/softfloat/softfloat.c | 32501 ++++++++++++++++ lib/utf8.js | 63 + lib/zstd/zstddeclib.c | 13520 +++++++ src/acpi.js | 207 + src/apic.js | 630 + src/browser/dummy_screen.js | 180 + src/browser/filestorage.js | 161 + src/browser/keyboard.js | 445 + src/browser/main.js | 2096 + src/browser/mouse.js | 297 + src/browser/network.js | 142 + src/browser/print_stats.js | 287 + src/browser/screen.js | 565 + src/browser/serial.js | 251 + src/browser/speaker.js | 1119 + src/browser/starter.js | 1353 + src/browser/worker_bus.js | 64 + src/buffer.js | 748 + src/bus.js | 104 + src/config.js | 64 + src/const.js | 163 + src/cpu.js | 1529 + src/debug.js | 664 + src/dma.js | 424 + src/elf.js | 221 + src/externs.js | 31 + src/floppy.js | 459 + src/hpet.js | 295 + src/ide.js | 2092 + src/io.js | 461 + src/ioapic.js | 364 + src/kernel.js | 235 + src/lib.js | 703 + src/log.js | 129 + src/main.js | 228 + src/memory.js | 98 + src/ne2k.js | 1291 + src/pci.js | 618 + src/pic.js | 574 + src/pit.js | 352 + src/ps2.js | 813 + src/rtc.js | 359 + src/rust/analysis.rs | 99 + src/rust/codegen.rs | 2648 ++ src/rust/config.rs | 4 + src/rust/control_flow.rs | 420 + src/rust/cpu/arith.rs | 1202 + src/rust/cpu/call_indirect.rs | 2 + src/rust/cpu/cpu.rs | 4330 ++ src/rust/cpu/fpu.rs | 909 + src/rust/cpu/global_pointers.rs | 109 + src/rust/cpu/instructions.rs | 2524 ++ src/rust/cpu/instructions_0f.rs | 5147 +++ src/rust/cpu/memory.rs | 301 + src/rust/cpu/misc_instr.rs | 593 + src/rust/cpu/mod.rs | 13 + src/rust/cpu/modrm.rs | 202 + src/rust/cpu/sse_instr.rs | 361 + src/rust/cpu/string.rs | 696 + src/rust/cpu/vga.rs | 169 + src/rust/cpu_context.rs | 59 + src/rust/dbg.rs | 98 + src/rust/gen/mod.rs | 8 + src/rust/jit.rs | 2419 ++ src/rust/jit_instructions.rs | 7791 ++++ src/rust/js_api.rs | 6 + src/rust/leb.rs | 46 + src/rust/lib.rs | 32 + src/rust/modrm.rs | 320 + src/rust/opstats.rs | 249 + src/rust/page.rs | 15 + src/rust/paging.rs | 25 + src/rust/prefix.rs | 14 + src/rust/profiler.rs | 152 + src/rust/regs.rs | 38 + src/rust/softfloat.rs | 305 + src/rust/state_flags.rs | 27 + src/rust/util.rs | 115 + src/rust/wasmgen/mod.rs | 2 + src/rust/wasmgen/wasm_builder.rs | 1029 + src/rust/wasmgen/wasm_opcodes.rs | 221 + src/rust/zstd.rs | 105 + src/sb16.js | 1857 + src/state.js | 325 + src/uart.js | 364 + src/vga.js | 2376 ++ src/virtio.js | 1494 + tests/Readme.md | 25 + tests/api/clean-shutdown.js | 33 + tests/api/reset.js | 46 + tests/api/state.js | 76 + tests/benchmark/arch-bytemark.js | 79 + tests/benchmark/linux-boot.js | 80 + tests/devices/testfs.json | 1 + ...a5e8149b479c813ab4ceea0bcf8b01f78eac84fd25 | 1 + ...afca942d0fb89d7c9ac0c99bafc3749504ded97730 | 1 + tests/devices/virtio_9p.js | 1841 + tests/expect/readme.md | 24 + tests/expect/run.js | 209 + tests/expect/tests/Makefile | 16 + tests/expect/tests/add.asm | 3 + tests/expect/tests/add.wast | 209 + tests/expect/tests/call-ret.asm | 7 + tests/expect/tests/call-ret.wast | 366 + tests/expect/tests/do-while.asm | 8 + tests/expect/tests/do-while.wast | 274 + tests/expect/tests/if.asm | 8 + tests/expect/tests/if.wast | 310 + tests/expect/tests/inc.asm | 3 + tests/expect/tests/inc.wast | 241 + tests/expect/tests/indirect-call.asm | 3 + tests/expect/tests/indirect-call.wast | 324 + tests/expect/tests/loop.asm | 6 + tests/expect/tests/loop.wast | 220 + tests/expect/tests/mem32r.asm | 3 + tests/expect/tests/mem32r.wast | 246 + tests/expect/tests/mem32rmw.asm | 3 + tests/expect/tests/mem32rmw.wast | 315 + tests/expect/tests/mem32w.asm | 3 + tests/expect/tests/mem32w.wast | 247 + tests/expect/tests/mov-immoffs.asm | 3 + tests/expect/tests/mov-immoffs.wast | 244 + tests/expect/tests/pop.asm | 3 + tests/expect/tests/pop.wast | 239 + tests/expect/tests/push.asm | 3 + tests/expect/tests/push.wast | 241 + tests/expect/tests/sti.asm | 8 + tests/expect/tests/sti.wast | 267 + tests/expect/tests/task_switch_test.asm | 3 + tests/expect/tests/task_switch_test.wast | 219 + tests/expect/tests/task_switch_test_sse.asm | 3 + tests/expect/tests/task_switch_test_sse.wast | 218 + tests/expect/tests/while-do.asm | 10 + tests/expect/tests/while-do.wast | 247 + tests/full/run.js | 1248 + tests/jit-paging/Makefile | 11 + tests/jit-paging/README.md | 11 + tests/jit-paging/run.js | 77 + tests/jit-paging/test-jit.c | 205 + tests/kvm-unit-tests/.gitignore | 22 + tests/kvm-unit-tests/COPYRIGHT | 10 + tests/kvm-unit-tests/MAINTAINERS | 91 + tests/kvm-unit-tests/Makefile | 125 + tests/kvm-unit-tests/README.md | 135 + tests/kvm-unit-tests/api/api-sample.cc | 30 + tests/kvm-unit-tests/api/dirty-log-perf.cc | 146 + tests/kvm-unit-tests/api/dirty-log.cc | 84 + tests/kvm-unit-tests/api/exception.cc | 33 + tests/kvm-unit-tests/api/exception.hh | 19 + tests/kvm-unit-tests/api/identity.cc | 120 + tests/kvm-unit-tests/api/identity.hh | 45 + tests/kvm-unit-tests/api/kvmxx.cc | 199 + tests/kvm-unit-tests/api/kvmxx.hh | 86 + tests/kvm-unit-tests/api/memmap.cc | 96 + tests/kvm-unit-tests/api/memmap.hh | 43 + tests/kvm-unit-tests/configure | 199 + tests/kvm-unit-tests/lib/abort.c | 20 + tests/kvm-unit-tests/lib/alloc.c | 179 + tests/kvm-unit-tests/lib/alloc.h | 116 + tests/kvm-unit-tests/lib/argv.c | 146 + tests/kvm-unit-tests/lib/argv.h | 10 + tests/kvm-unit-tests/lib/asm-generic/atomic.h | 21 + .../kvm-unit-tests/lib/asm-generic/barrier.h | 35 + tests/kvm-unit-tests/lib/asm-generic/io.h | 213 + tests/kvm-unit-tests/lib/asm-generic/page.h | 29 + .../lib/asm-generic/pci-host-bridge.h | 28 + tests/kvm-unit-tests/lib/asm-generic/pci.h | 4 + .../kvm-unit-tests/lib/asm-generic/spinlock.h | 18 + tests/kvm-unit-tests/lib/auxinfo.c | 2 + tests/kvm-unit-tests/lib/auxinfo.h | 13 + tests/kvm-unit-tests/lib/bitops.h | 36 + tests/kvm-unit-tests/lib/chr-testdev.c | 72 + tests/kvm-unit-tests/lib/chr-testdev.h | 14 + tests/kvm-unit-tests/lib/devicetree.c | 334 + tests/kvm-unit-tests/lib/devicetree.h | 251 + tests/kvm-unit-tests/lib/errata.h | 47 + tests/kvm-unit-tests/lib/kbuild.h | 8 + tests/kvm-unit-tests/lib/libcflat.h | 159 + .../kvm-unit-tests/lib/libfdt/Makefile.libfdt | 10 + tests/kvm-unit-tests/lib/libfdt/README | 4 + tests/kvm-unit-tests/lib/libfdt/fdt.c | 250 + tests/kvm-unit-tests/lib/libfdt/fdt.h | 111 + .../lib/libfdt/fdt_empty_tree.c | 84 + tests/kvm-unit-tests/lib/libfdt/fdt_ro.c | 573 + tests/kvm-unit-tests/lib/libfdt/fdt_rw.c | 492 + .../kvm-unit-tests/lib/libfdt/fdt_strerror.c | 96 + tests/kvm-unit-tests/lib/libfdt/fdt_sw.c | 256 + tests/kvm-unit-tests/lib/libfdt/fdt_wip.c | 118 + tests/kvm-unit-tests/lib/libfdt/libfdt.h | 1514 + tests/kvm-unit-tests/lib/libfdt/libfdt_env.h | 111 + .../lib/libfdt/libfdt_internal.h | 95 + tests/kvm-unit-tests/lib/libfdt/version.lds | 60 + tests/kvm-unit-tests/lib/linux/const.h | 27 + tests/kvm-unit-tests/lib/linux/pci_regs.h | 949 + tests/kvm-unit-tests/lib/linux/psci.h | 108 + tests/kvm-unit-tests/lib/pci-edu.c | 73 + tests/kvm-unit-tests/lib/pci-edu.h | 86 + tests/kvm-unit-tests/lib/pci-host-generic.c | 320 + tests/kvm-unit-tests/lib/pci-host-generic.h | 46 + tests/kvm-unit-tests/lib/pci-testdev.c | 194 + tests/kvm-unit-tests/lib/pci.c | 386 + tests/kvm-unit-tests/lib/pci.h | 105 + tests/kvm-unit-tests/lib/printf.c | 322 + tests/kvm-unit-tests/lib/report.c | 180 + tests/kvm-unit-tests/lib/setjmp.h | 18 + tests/kvm-unit-tests/lib/stack.c | 103 + tests/kvm-unit-tests/lib/stack.h | 27 + tests/kvm-unit-tests/lib/string.c | 223 + tests/kvm-unit-tests/lib/string.h | 23 + tests/kvm-unit-tests/lib/util.c | 19 + tests/kvm-unit-tests/lib/util.h | 23 + tests/kvm-unit-tests/lib/virtio-mmio.c | 177 + tests/kvm-unit-tests/lib/virtio-mmio.h | 65 + tests/kvm-unit-tests/lib/virtio.c | 130 + tests/kvm-unit-tests/lib/virtio.h | 150 + tests/kvm-unit-tests/lib/x86/acpi.c | 52 + tests/kvm-unit-tests/lib/x86/acpi.h | 104 + tests/kvm-unit-tests/lib/x86/apic-defs.h | 138 + tests/kvm-unit-tests/lib/x86/apic.c | 208 + tests/kvm-unit-tests/lib/x86/apic.h | 50 + tests/kvm-unit-tests/lib/x86/asm/barrier.h | 27 + tests/kvm-unit-tests/lib/x86/asm/bitops.h | 14 + tests/kvm-unit-tests/lib/x86/asm/io.h | 65 + tests/kvm-unit-tests/lib/x86/asm/page.h | 50 + tests/kvm-unit-tests/lib/x86/asm/pci.h | 59 + tests/kvm-unit-tests/lib/x86/asm/spinlock.h | 6 + tests/kvm-unit-tests/lib/x86/asm/stack.h | 11 + tests/kvm-unit-tests/lib/x86/atomic.c | 37 + tests/kvm-unit-tests/lib/x86/atomic.h | 166 + tests/kvm-unit-tests/lib/x86/desc.c | 399 + tests/kvm-unit-tests/lib/x86/desc.h | 201 + tests/kvm-unit-tests/lib/x86/fake-apic.h | 14 + tests/kvm-unit-tests/lib/x86/fwcfg.c | 45 + tests/kvm-unit-tests/lib/x86/fwcfg.h | 44 + tests/kvm-unit-tests/lib/x86/intel-iommu.c | 372 + tests/kvm-unit-tests/lib/x86/intel-iommu.h | 149 + tests/kvm-unit-tests/lib/x86/io.c | 99 + tests/kvm-unit-tests/lib/x86/isr.c | 124 + tests/kvm-unit-tests/lib/x86/isr.h | 14 + tests/kvm-unit-tests/lib/x86/msr.h | 412 + tests/kvm-unit-tests/lib/x86/processor.h | 443 + tests/kvm-unit-tests/lib/x86/setjmp32.S | 25 + tests/kvm-unit-tests/lib/x86/setjmp64.S | 27 + tests/kvm-unit-tests/lib/x86/setup.c | 47 + tests/kvm-unit-tests/lib/x86/smp.c | 130 + tests/kvm-unit-tests/lib/x86/smp.h | 14 + tests/kvm-unit-tests/lib/x86/stack.c | 31 + tests/kvm-unit-tests/lib/x86/vm.c | 361 + tests/kvm-unit-tests/lib/x86/vm.h | 59 + tests/kvm-unit-tests/run.js | 56 + tests/kvm-unit-tests/x86/Makefile | 1 + tests/kvm-unit-tests/x86/Makefile.common | 92 + tests/kvm-unit-tests/x86/Makefile.i386 | 33 + tests/kvm-unit-tests/x86/Makefile.x86_64 | 25 + tests/kvm-unit-tests/x86/README | 49 + tests/kvm-unit-tests/x86/access.c | 991 + tests/kvm-unit-tests/x86/apic.c | 486 + tests/kvm-unit-tests/x86/asyncpf.c | 109 + tests/kvm-unit-tests/x86/cmpxchg8b.c | 27 + tests/kvm-unit-tests/x86/cstart.S | 212 + tests/kvm-unit-tests/x86/cstart64.S | 256 + tests/kvm-unit-tests/x86/debug.c | 181 + tests/kvm-unit-tests/x86/emulator.c | 1168 + tests/kvm-unit-tests/x86/eventinj.c | 421 + tests/kvm-unit-tests/x86/flat.lds | 21 + tests/kvm-unit-tests/x86/hypercall.c | 80 + tests/kvm-unit-tests/x86/hyperv.c | 70 + tests/kvm-unit-tests/x86/hyperv.h | 217 + tests/kvm-unit-tests/x86/hyperv_clock.c | 194 + tests/kvm-unit-tests/x86/hyperv_connections.c | 336 + tests/kvm-unit-tests/x86/hyperv_stimer.c | 373 + tests/kvm-unit-tests/x86/hyperv_synic.c | 185 + tests/kvm-unit-tests/x86/idt_test.c | 41 + tests/kvm-unit-tests/x86/init.c | 130 + tests/kvm-unit-tests/x86/intel-iommu.c | 163 + tests/kvm-unit-tests/x86/ioapic.c | 438 + tests/kvm-unit-tests/x86/ioram.h | 7 + tests/kvm-unit-tests/x86/kvmclock.c | 288 + tests/kvm-unit-tests/x86/kvmclock.h | 44 + tests/kvm-unit-tests/x86/kvmclock_test.c | 157 + tests/kvm-unit-tests/x86/memory.c | 88 + tests/kvm-unit-tests/x86/msr.c | 112 + tests/kvm-unit-tests/x86/pae.c | 101 + tests/kvm-unit-tests/x86/pcid.c | 167 + tests/kvm-unit-tests/x86/pku.c | 138 + tests/kvm-unit-tests/x86/pmu.c | 413 + tests/kvm-unit-tests/x86/port80.c | 12 + tests/kvm-unit-tests/x86/realmode.c | 1894 + tests/kvm-unit-tests/x86/realmode.lds | 12 + tests/kvm-unit-tests/x86/rmap_chain.c | 45 + tests/kvm-unit-tests/x86/s3.c | 89 + tests/kvm-unit-tests/x86/setjmp.c | 19 + tests/kvm-unit-tests/x86/sieve.c | 51 + tests/kvm-unit-tests/x86/smap.c | 187 + tests/kvm-unit-tests/x86/smptest.c | 31 + tests/kvm-unit-tests/x86/svm.c | 1081 + tests/kvm-unit-tests/x86/svm.h | 328 + tests/kvm-unit-tests/x86/syscall.c | 108 + tests/kvm-unit-tests/x86/taskswitch.c | 50 + tests/kvm-unit-tests/x86/taskswitch2.c | 294 + tests/kvm-unit-tests/x86/tsc.c | 47 + tests/kvm-unit-tests/x86/tsc_adjust.c | 42 + .../kvm-unit-tests/x86/tscdeadline_latency.c | 132 + tests/kvm-unit-tests/x86/types.h | 20 + tests/kvm-unit-tests/x86/vmexit.c | 556 + tests/kvm-unit-tests/x86/vmx.c | 1852 + tests/kvm-unit-tests/x86/vmx.h | 807 + tests/kvm-unit-tests/x86/vmx_tests.c | 3458 ++ tests/kvm-unit-tests/x86/xsave.c | 178 + tests/manual/gc.html | 33 + tests/nasm/Makefile | 28 + tests/nasm/Readme.md | 8 + tests/nasm/arith-optimisations.asm | 17 + tests/nasm/btc-imm.asm | 32 + tests/nasm/btc-reg16.asm | 29 + tests/nasm/btc-reg32.asm | 29 + tests/nasm/btr-imm.asm | 32 + tests/nasm/btr-reg16.asm | 29 + tests/nasm/btr-reg32.asm | 29 + tests/nasm/bts-imm.asm | 32 + tests/nasm/bts-reg16.asm | 29 + tests/nasm/bts-reg32.asm | 29 + tests/nasm/cmp16-setbe.asm | 9 + tests/nasm/cmpxchg-setbe.asm | 10 + tests/nasm/cmpxchg.asm | 32 + tests/nasm/cmpxchg8b.asm | 21 + tests/nasm/comiss.asm | 57 + tests/nasm/create_tests.js | 433 + tests/nasm/cvtpi2ps.asm | 22 + tests/nasm/cvtps2pi.asm | 41 + tests/nasm/cvttps2pi.asm | 31 + tests/nasm/emms.asm | 17 + tests/nasm/f2xm1.asm | 18 + tests/nasm/fchs.asm | 8 + tests/nasm/fdecstp.asm | 7 + tests/nasm/fdiv-zero.asm | 14 + tests/nasm/fdiv.asm | 9 + tests/nasm/fdivr.asm | 9 + tests/nasm/fincstp.asm | 7 + tests/nasm/footer.inc | 3 + tests/nasm/fprem.asm | 21 + tests/nasm/fprem1.asm | 21 + tests/nasm/fptan.asm | 12 + tests/nasm/fpu_m80.asm | 13 + tests/nasm/frndint.asm | 17 + tests/nasm/fsave_frstor.asm | 12 + tests/nasm/fscale.asm | 9 + tests/nasm/fsincos.asm | 20 + tests/nasm/fsqrt.asm | 8 + tests/nasm/fstenv.asm | 16 + tests/nasm/fstm80.asm | 15 + tests/nasm/fxtract-zero.asm | 12 + tests/nasm/fxtract.asm | 12 + tests/nasm/fyl2x-zero.asm | 14 + tests/nasm/fyl2x.asm | 9 + tests/nasm/fyl2xp1.asm | 9 + tests/nasm/gdb-extract-def | 145 + tests/nasm/gen_fixtures.js | 144 + tests/nasm/header.inc | 37 + tests/nasm/idiv16-overflow.asm | 10 + tests/nasm/idiv32-overflow.asm | 10 + tests/nasm/idiv8-overflow.asm | 9 + tests/nasm/indirect-call.asm | 14 + tests/nasm/indirect-jump.asm | 12 + tests/nasm/jcxz.asm | 25 + tests/nasm/jump.asm | 60 + tests/nasm/lea-nop.asm | 17 + tests/nasm/leave16.asm | 10 + tests/nasm/leave32.asm | 9 + tests/nasm/loop.asm | 18 + tests/nasm/loopnz.asm | 24 + tests/nasm/loopz.asm | 24 + tests/nasm/maskmovdqu.asm | 47 + tests/nasm/maskmovq.asm | 43 + tests/nasm/mov16.asm | 45 + tests/nasm/mov_sreg.asm | 32 + tests/nasm/mov_sreg_ud1.asm | 8 + tests/nasm/mov_sreg_ud2.asm | 8 + tests/nasm/movaps.asm | 21 + tests/nasm/movd.asm | 23 + tests/nasm/movntpd.asm | 21 + tests/nasm/movntps.asm | 21 + tests/nasm/movq.asm | 19 + tests/nasm/packssdw.asm | 30 + tests/nasm/packsswb.asm | 30 + tests/nasm/packuswb.asm | 44 + tests/nasm/paddb.asm | 34 + tests/nasm/paddd.asm | 34 + tests/nasm/paddsb.asm | 30 + tests/nasm/paddsw.asm | 30 + tests/nasm/paddusb.asm | 30 + tests/nasm/paddusw.asm | 30 + tests/nasm/paddw.asm | 17 + tests/nasm/pand.asm | 35 + tests/nasm/pandn.asm | 30 + tests/nasm/pcmpeqb.asm | 37 + tests/nasm/pcmpeqd.asm | 30 + tests/nasm/pcmpeqw.asm | 30 + tests/nasm/pcmpgtb.asm | 42 + tests/nasm/pcmpgtd.asm | 31 + tests/nasm/pcmpgtw.asm | 30 + tests/nasm/pmaddwd.asm | 34 + tests/nasm/pmulhw.asm | 30 + tests/nasm/pmullw.asm | 30 + tests/nasm/pmuludq.asm | 43 + tests/nasm/pop_esp.asm | 12 + tests/nasm/pop_esp2.asm | 12 + tests/nasm/por.asm | 30 + tests/nasm/prand.js | 21 + tests/nasm/pshufw.asm | 20 + tests/nasm/pslld.asm | 48 + tests/nasm/psllq.asm | 53 + tests/nasm/psllw.asm | 56 + tests/nasm/psrad.asm | 44 + tests/nasm/psraw.asm | 44 + tests/nasm/psrld.asm | 44 + tests/nasm/psrlq.asm | 58 + tests/nasm/psrlw.asm | 48 + tests/nasm/psubb.asm | 34 + tests/nasm/psubd.asm | 34 + tests/nasm/psubsb.asm | 30 + tests/nasm/psubsw.asm | 30 + tests/nasm/psubusb.asm | 30 + tests/nasm/psubusw.asm | 30 + tests/nasm/psubw.asm | 39 + tests/nasm/punpckhbw.asm | 31 + tests/nasm/punpckhdq.asm | 31 + tests/nasm/punpckhwd.asm | 31 + tests/nasm/punpcklbw.asm | 44 + tests/nasm/punpckldq.asm | 42 + tests/nasm/punpcklwd.asm | 42 + tests/nasm/push.asm | 44 + tests/nasm/pushf.asm | 12 + tests/nasm/pxor.asm | 44 + tests/nasm/ret-imm.asm | 15 + tests/nasm/run.js | 538 + tests/nasm/shufps-edgecase.asm | 12 + tests/nasm/ucomiss.asm | 57 + tests/qemu/LICENSE | 16 + tests/qemu/Makefile | 14 + tests/qemu/Readme.md | 7 + tests/qemu/compiler.h | 114 + tests/qemu/config-host.h | 66 + tests/qemu/run-qemu.js | 67 + tests/qemu/run.js | 68 + tests/qemu/test-i386-code16.S | 79 + tests/qemu/test-i386-muldiv.h | 76 + tests/qemu/test-i386-shift.h | 195 + tests/qemu/test-i386-vm86.S | 103 + tests/qemu/test-i386.c | 3473 ++ tests/qemu/test-i386.h | 168 + tests/rust/verify-wasmgen-dummy-output.js | 34 + tools/copy-to-sha256.py | 94 + tools/docker/README.md | 15 + tools/docker/debian/Dockerfile | 68 + tools/docker/debian/Readme.md | 25 + tools/docker/debian/boot-9p | 33 + tools/docker/debian/build-container.sh | 24 + tools/docker/debian/build-state.js | 92 + .../docker/debian/getty-autologin-serial.conf | 3 + tools/docker/debian/getty-noclear.conf | 2 + tools/docker/debian/getty-override.conf | 3 + tools/docker/debian/logind.conf | 37 + tools/docker/debian/networking.sh | 4 + tools/docker/debian/xorg.conf | 67 + tools/docker/exec/Dockerfile | 20 + tools/docker/exec/build.sh | 5 + tools/docker/test-image/Dockerfile | 12 + tools/fs2json.py | 272 + tools/rust-lld-wrapper | 65 + v86.css | 259 + 521 files changed, 167810 insertions(+) create mode 100644 .cargo/config create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/workflows/main.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 .jshint.json create mode 100644 .rustfmt.toml create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 Readme.md create mode 100644 bios/.gitignore create mode 100644 bios/COPYING.LESSER create mode 100755 bios/fetch-and-build-seabios.sh create mode 100644 bios/seabios-debug.config create mode 100644 bios/seabios.config create mode 100644 debug.html create mode 100644 docs/.gitignore create mode 100644 docs/archlinux.md create mode 100644 docs/filesystem.md create mode 100644 docs/linux-9p-image.md create mode 100644 docs/networking.md create mode 100644 docs/sse-shifts.txt create mode 100644 docs/windows-xp.md create mode 100644 examples/arch.html create mode 100644 examples/async_load.html create mode 100644 examples/basic.html create mode 100644 examples/debian.html create mode 100644 examples/destroy.html create mode 100644 examples/lang.html create mode 100644 examples/lua.html create mode 100755 examples/nodejs.js create mode 100755 examples/nodejs_state.js create mode 100644 examples/save_restore.html create mode 100644 examples/serial.html create mode 100644 examples/two_instances.html create mode 100644 examples/worker.html create mode 100644 examples/worker.js create mode 100755 gen/generate_analyzer.js create mode 100755 gen/generate_interpreter.js create mode 100755 gen/generate_jit.js create mode 100644 gen/rust_ast.js create mode 100644 gen/util.js create mode 100644 gen/x86_table.js create mode 100644 index.html create mode 100644 lib/9p.js create mode 100644 lib/filesystem.js create mode 100644 lib/jor1k.js create mode 100644 lib/marshall.js create mode 100644 lib/softfloat/softfloat.c create mode 100644 lib/utf8.js create mode 100644 lib/zstd/zstddeclib.c create mode 100644 src/acpi.js create mode 100644 src/apic.js create mode 100644 src/browser/dummy_screen.js create mode 100644 src/browser/filestorage.js create mode 100644 src/browser/keyboard.js create mode 100644 src/browser/main.js create mode 100644 src/browser/mouse.js create mode 100644 src/browser/network.js create mode 100644 src/browser/print_stats.js create mode 100644 src/browser/screen.js create mode 100644 src/browser/serial.js create mode 100644 src/browser/speaker.js create mode 100644 src/browser/starter.js create mode 100644 src/browser/worker_bus.js create mode 100644 src/buffer.js create mode 100644 src/bus.js create mode 100644 src/config.js create mode 100644 src/const.js create mode 100644 src/cpu.js create mode 100644 src/debug.js create mode 100644 src/dma.js create mode 100644 src/elf.js create mode 100644 src/externs.js create mode 100644 src/floppy.js create mode 100644 src/hpet.js create mode 100644 src/ide.js create mode 100644 src/io.js create mode 100644 src/ioapic.js create mode 100644 src/kernel.js create mode 100644 src/lib.js create mode 100644 src/log.js create mode 100644 src/main.js create mode 100644 src/memory.js create mode 100644 src/ne2k.js create mode 100644 src/pci.js create mode 100644 src/pic.js create mode 100644 src/pit.js create mode 100644 src/ps2.js create mode 100644 src/rtc.js create mode 100644 src/rust/analysis.rs create mode 100644 src/rust/codegen.rs create mode 100644 src/rust/config.rs create mode 100644 src/rust/control_flow.rs create mode 100644 src/rust/cpu/arith.rs create mode 100644 src/rust/cpu/call_indirect.rs create mode 100644 src/rust/cpu/cpu.rs create mode 100644 src/rust/cpu/fpu.rs create mode 100644 src/rust/cpu/global_pointers.rs create mode 100644 src/rust/cpu/instructions.rs create mode 100644 src/rust/cpu/instructions_0f.rs create mode 100644 src/rust/cpu/memory.rs create mode 100644 src/rust/cpu/misc_instr.rs create mode 100644 src/rust/cpu/mod.rs create mode 100644 src/rust/cpu/modrm.rs create mode 100644 src/rust/cpu/sse_instr.rs create mode 100644 src/rust/cpu/string.rs create mode 100644 src/rust/cpu/vga.rs create mode 100644 src/rust/cpu_context.rs create mode 100644 src/rust/dbg.rs create mode 100644 src/rust/gen/mod.rs create mode 100644 src/rust/jit.rs create mode 100644 src/rust/jit_instructions.rs create mode 100644 src/rust/js_api.rs create mode 100644 src/rust/leb.rs create mode 100644 src/rust/lib.rs create mode 100644 src/rust/modrm.rs create mode 100644 src/rust/opstats.rs create mode 100644 src/rust/page.rs create mode 100644 src/rust/paging.rs create mode 100644 src/rust/prefix.rs create mode 100644 src/rust/profiler.rs create mode 100644 src/rust/regs.rs create mode 100644 src/rust/softfloat.rs create mode 100644 src/rust/state_flags.rs create mode 100644 src/rust/util.rs create mode 100644 src/rust/wasmgen/mod.rs create mode 100644 src/rust/wasmgen/wasm_builder.rs create mode 100644 src/rust/wasmgen/wasm_opcodes.rs create mode 100644 src/rust/zstd.rs create mode 100644 src/sb16.js create mode 100644 src/state.js create mode 100644 src/uart.js create mode 100644 src/vga.js create mode 100644 src/virtio.js create mode 100644 tests/Readme.md create mode 100755 tests/api/clean-shutdown.js create mode 100755 tests/api/reset.js create mode 100755 tests/api/state.js create mode 100755 tests/benchmark/arch-bytemark.js create mode 100755 tests/benchmark/linux-boot.js create mode 100644 tests/devices/testfs.json create mode 100644 tests/devices/testfs/5d70f436aa013f4f1d5af4a5e8149b479c813ab4ceea0bcf8b01f78eac84fd25 create mode 100644 tests/devices/testfs/7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730 create mode 100755 tests/devices/virtio_9p.js create mode 100644 tests/expect/readme.md create mode 100755 tests/expect/run.js create mode 100644 tests/expect/tests/Makefile create mode 100644 tests/expect/tests/add.asm create mode 100644 tests/expect/tests/add.wast create mode 100644 tests/expect/tests/call-ret.asm create mode 100644 tests/expect/tests/call-ret.wast create mode 100644 tests/expect/tests/do-while.asm create mode 100644 tests/expect/tests/do-while.wast create mode 100644 tests/expect/tests/if.asm create mode 100644 tests/expect/tests/if.wast create mode 100644 tests/expect/tests/inc.asm create mode 100644 tests/expect/tests/inc.wast create mode 100644 tests/expect/tests/indirect-call.asm create mode 100644 tests/expect/tests/indirect-call.wast create mode 100644 tests/expect/tests/loop.asm create mode 100644 tests/expect/tests/loop.wast create mode 100644 tests/expect/tests/mem32r.asm create mode 100644 tests/expect/tests/mem32r.wast create mode 100644 tests/expect/tests/mem32rmw.asm create mode 100644 tests/expect/tests/mem32rmw.wast create mode 100644 tests/expect/tests/mem32w.asm create mode 100644 tests/expect/tests/mem32w.wast create mode 100644 tests/expect/tests/mov-immoffs.asm create mode 100644 tests/expect/tests/mov-immoffs.wast create mode 100644 tests/expect/tests/pop.asm create mode 100644 tests/expect/tests/pop.wast create mode 100644 tests/expect/tests/push.asm create mode 100644 tests/expect/tests/push.wast create mode 100644 tests/expect/tests/sti.asm create mode 100644 tests/expect/tests/sti.wast create mode 100644 tests/expect/tests/task_switch_test.asm create mode 100644 tests/expect/tests/task_switch_test.wast create mode 100644 tests/expect/tests/task_switch_test_sse.asm create mode 100644 tests/expect/tests/task_switch_test_sse.wast create mode 100644 tests/expect/tests/while-do.asm create mode 100644 tests/expect/tests/while-do.wast create mode 100755 tests/full/run.js create mode 100644 tests/jit-paging/Makefile create mode 100644 tests/jit-paging/README.md create mode 100755 tests/jit-paging/run.js create mode 100644 tests/jit-paging/test-jit.c create mode 100644 tests/kvm-unit-tests/.gitignore create mode 100644 tests/kvm-unit-tests/COPYRIGHT create mode 100644 tests/kvm-unit-tests/MAINTAINERS create mode 100644 tests/kvm-unit-tests/Makefile create mode 100644 tests/kvm-unit-tests/README.md create mode 100644 tests/kvm-unit-tests/api/api-sample.cc create mode 100644 tests/kvm-unit-tests/api/dirty-log-perf.cc create mode 100644 tests/kvm-unit-tests/api/dirty-log.cc create mode 100644 tests/kvm-unit-tests/api/exception.cc create mode 100644 tests/kvm-unit-tests/api/exception.hh create mode 100644 tests/kvm-unit-tests/api/identity.cc create mode 100644 tests/kvm-unit-tests/api/identity.hh create mode 100644 tests/kvm-unit-tests/api/kvmxx.cc create mode 100644 tests/kvm-unit-tests/api/kvmxx.hh create mode 100644 tests/kvm-unit-tests/api/memmap.cc create mode 100644 tests/kvm-unit-tests/api/memmap.hh create mode 100755 tests/kvm-unit-tests/configure create mode 100644 tests/kvm-unit-tests/lib/abort.c create mode 100644 tests/kvm-unit-tests/lib/alloc.c create mode 100644 tests/kvm-unit-tests/lib/alloc.h create mode 100644 tests/kvm-unit-tests/lib/argv.c create mode 100644 tests/kvm-unit-tests/lib/argv.h create mode 100644 tests/kvm-unit-tests/lib/asm-generic/atomic.h create mode 100644 tests/kvm-unit-tests/lib/asm-generic/barrier.h create mode 100644 tests/kvm-unit-tests/lib/asm-generic/io.h create mode 100644 tests/kvm-unit-tests/lib/asm-generic/page.h create mode 100644 tests/kvm-unit-tests/lib/asm-generic/pci-host-bridge.h create mode 100644 tests/kvm-unit-tests/lib/asm-generic/pci.h create mode 100644 tests/kvm-unit-tests/lib/asm-generic/spinlock.h create mode 100644 tests/kvm-unit-tests/lib/auxinfo.c create mode 100644 tests/kvm-unit-tests/lib/auxinfo.h create mode 100644 tests/kvm-unit-tests/lib/bitops.h create mode 100644 tests/kvm-unit-tests/lib/chr-testdev.c create mode 100644 tests/kvm-unit-tests/lib/chr-testdev.h create mode 100644 tests/kvm-unit-tests/lib/devicetree.c create mode 100644 tests/kvm-unit-tests/lib/devicetree.h create mode 100644 tests/kvm-unit-tests/lib/errata.h create mode 100644 tests/kvm-unit-tests/lib/kbuild.h create mode 100644 tests/kvm-unit-tests/lib/libcflat.h create mode 100644 tests/kvm-unit-tests/lib/libfdt/Makefile.libfdt create mode 100644 tests/kvm-unit-tests/lib/libfdt/README create mode 100644 tests/kvm-unit-tests/lib/libfdt/fdt.c create mode 100644 tests/kvm-unit-tests/lib/libfdt/fdt.h create mode 100644 tests/kvm-unit-tests/lib/libfdt/fdt_empty_tree.c create mode 100644 tests/kvm-unit-tests/lib/libfdt/fdt_ro.c create mode 100644 tests/kvm-unit-tests/lib/libfdt/fdt_rw.c create mode 100644 tests/kvm-unit-tests/lib/libfdt/fdt_strerror.c create mode 100644 tests/kvm-unit-tests/lib/libfdt/fdt_sw.c create mode 100644 tests/kvm-unit-tests/lib/libfdt/fdt_wip.c create mode 100644 tests/kvm-unit-tests/lib/libfdt/libfdt.h create mode 100644 tests/kvm-unit-tests/lib/libfdt/libfdt_env.h create mode 100644 tests/kvm-unit-tests/lib/libfdt/libfdt_internal.h create mode 100644 tests/kvm-unit-tests/lib/libfdt/version.lds create mode 100644 tests/kvm-unit-tests/lib/linux/const.h create mode 100644 tests/kvm-unit-tests/lib/linux/pci_regs.h create mode 100644 tests/kvm-unit-tests/lib/linux/psci.h create mode 100644 tests/kvm-unit-tests/lib/pci-edu.c create mode 100644 tests/kvm-unit-tests/lib/pci-edu.h create mode 100644 tests/kvm-unit-tests/lib/pci-host-generic.c create mode 100644 tests/kvm-unit-tests/lib/pci-host-generic.h create mode 100644 tests/kvm-unit-tests/lib/pci-testdev.c create mode 100644 tests/kvm-unit-tests/lib/pci.c create mode 100644 tests/kvm-unit-tests/lib/pci.h create mode 100644 tests/kvm-unit-tests/lib/printf.c create mode 100644 tests/kvm-unit-tests/lib/report.c create mode 100644 tests/kvm-unit-tests/lib/setjmp.h create mode 100644 tests/kvm-unit-tests/lib/stack.c create mode 100644 tests/kvm-unit-tests/lib/stack.h create mode 100644 tests/kvm-unit-tests/lib/string.c create mode 100644 tests/kvm-unit-tests/lib/string.h create mode 100644 tests/kvm-unit-tests/lib/util.c create mode 100644 tests/kvm-unit-tests/lib/util.h create mode 100644 tests/kvm-unit-tests/lib/virtio-mmio.c create mode 100644 tests/kvm-unit-tests/lib/virtio-mmio.h create mode 100644 tests/kvm-unit-tests/lib/virtio.c create mode 100644 tests/kvm-unit-tests/lib/virtio.h create mode 100644 tests/kvm-unit-tests/lib/x86/acpi.c create mode 100644 tests/kvm-unit-tests/lib/x86/acpi.h create mode 100644 tests/kvm-unit-tests/lib/x86/apic-defs.h create mode 100644 tests/kvm-unit-tests/lib/x86/apic.c create mode 100644 tests/kvm-unit-tests/lib/x86/apic.h create mode 100644 tests/kvm-unit-tests/lib/x86/asm/barrier.h create mode 100644 tests/kvm-unit-tests/lib/x86/asm/bitops.h create mode 100644 tests/kvm-unit-tests/lib/x86/asm/io.h create mode 100644 tests/kvm-unit-tests/lib/x86/asm/page.h create mode 100644 tests/kvm-unit-tests/lib/x86/asm/pci.h create mode 100644 tests/kvm-unit-tests/lib/x86/asm/spinlock.h create mode 100644 tests/kvm-unit-tests/lib/x86/asm/stack.h create mode 100644 tests/kvm-unit-tests/lib/x86/atomic.c create mode 100644 tests/kvm-unit-tests/lib/x86/atomic.h create mode 100644 tests/kvm-unit-tests/lib/x86/desc.c create mode 100644 tests/kvm-unit-tests/lib/x86/desc.h create mode 100644 tests/kvm-unit-tests/lib/x86/fake-apic.h create mode 100644 tests/kvm-unit-tests/lib/x86/fwcfg.c create mode 100644 tests/kvm-unit-tests/lib/x86/fwcfg.h create mode 100644 tests/kvm-unit-tests/lib/x86/intel-iommu.c create mode 100644 tests/kvm-unit-tests/lib/x86/intel-iommu.h create mode 100644 tests/kvm-unit-tests/lib/x86/io.c create mode 100644 tests/kvm-unit-tests/lib/x86/isr.c create mode 100644 tests/kvm-unit-tests/lib/x86/isr.h create mode 100644 tests/kvm-unit-tests/lib/x86/msr.h create mode 100644 tests/kvm-unit-tests/lib/x86/processor.h create mode 100644 tests/kvm-unit-tests/lib/x86/setjmp32.S create mode 100644 tests/kvm-unit-tests/lib/x86/setjmp64.S create mode 100644 tests/kvm-unit-tests/lib/x86/setup.c create mode 100644 tests/kvm-unit-tests/lib/x86/smp.c create mode 100644 tests/kvm-unit-tests/lib/x86/smp.h create mode 100644 tests/kvm-unit-tests/lib/x86/stack.c create mode 100644 tests/kvm-unit-tests/lib/x86/vm.c create mode 100644 tests/kvm-unit-tests/lib/x86/vm.h create mode 100755 tests/kvm-unit-tests/run.js create mode 100644 tests/kvm-unit-tests/x86/Makefile create mode 100644 tests/kvm-unit-tests/x86/Makefile.common create mode 100644 tests/kvm-unit-tests/x86/Makefile.i386 create mode 100644 tests/kvm-unit-tests/x86/Makefile.x86_64 create mode 100644 tests/kvm-unit-tests/x86/README create mode 100644 tests/kvm-unit-tests/x86/access.c create mode 100644 tests/kvm-unit-tests/x86/apic.c create mode 100644 tests/kvm-unit-tests/x86/asyncpf.c create mode 100644 tests/kvm-unit-tests/x86/cmpxchg8b.c create mode 100644 tests/kvm-unit-tests/x86/cstart.S create mode 100644 tests/kvm-unit-tests/x86/cstart64.S create mode 100644 tests/kvm-unit-tests/x86/debug.c create mode 100644 tests/kvm-unit-tests/x86/emulator.c create mode 100644 tests/kvm-unit-tests/x86/eventinj.c create mode 100644 tests/kvm-unit-tests/x86/flat.lds create mode 100644 tests/kvm-unit-tests/x86/hypercall.c create mode 100644 tests/kvm-unit-tests/x86/hyperv.c create mode 100644 tests/kvm-unit-tests/x86/hyperv.h create mode 100644 tests/kvm-unit-tests/x86/hyperv_clock.c create mode 100644 tests/kvm-unit-tests/x86/hyperv_connections.c create mode 100644 tests/kvm-unit-tests/x86/hyperv_stimer.c create mode 100644 tests/kvm-unit-tests/x86/hyperv_synic.c create mode 100644 tests/kvm-unit-tests/x86/idt_test.c create mode 100644 tests/kvm-unit-tests/x86/init.c create mode 100644 tests/kvm-unit-tests/x86/intel-iommu.c create mode 100644 tests/kvm-unit-tests/x86/ioapic.c create mode 100644 tests/kvm-unit-tests/x86/ioram.h create mode 100644 tests/kvm-unit-tests/x86/kvmclock.c create mode 100644 tests/kvm-unit-tests/x86/kvmclock.h create mode 100644 tests/kvm-unit-tests/x86/kvmclock_test.c create mode 100644 tests/kvm-unit-tests/x86/memory.c create mode 100644 tests/kvm-unit-tests/x86/msr.c create mode 100644 tests/kvm-unit-tests/x86/pae.c create mode 100644 tests/kvm-unit-tests/x86/pcid.c create mode 100644 tests/kvm-unit-tests/x86/pku.c create mode 100644 tests/kvm-unit-tests/x86/pmu.c create mode 100644 tests/kvm-unit-tests/x86/port80.c create mode 100644 tests/kvm-unit-tests/x86/realmode.c create mode 100644 tests/kvm-unit-tests/x86/realmode.lds create mode 100644 tests/kvm-unit-tests/x86/rmap_chain.c create mode 100644 tests/kvm-unit-tests/x86/s3.c create mode 100644 tests/kvm-unit-tests/x86/setjmp.c create mode 100644 tests/kvm-unit-tests/x86/sieve.c create mode 100644 tests/kvm-unit-tests/x86/smap.c create mode 100644 tests/kvm-unit-tests/x86/smptest.c create mode 100644 tests/kvm-unit-tests/x86/svm.c create mode 100644 tests/kvm-unit-tests/x86/svm.h create mode 100644 tests/kvm-unit-tests/x86/syscall.c create mode 100644 tests/kvm-unit-tests/x86/taskswitch.c create mode 100644 tests/kvm-unit-tests/x86/taskswitch2.c create mode 100644 tests/kvm-unit-tests/x86/tsc.c create mode 100644 tests/kvm-unit-tests/x86/tsc_adjust.c create mode 100644 tests/kvm-unit-tests/x86/tscdeadline_latency.c create mode 100644 tests/kvm-unit-tests/x86/types.h create mode 100644 tests/kvm-unit-tests/x86/vmexit.c create mode 100644 tests/kvm-unit-tests/x86/vmx.c create mode 100644 tests/kvm-unit-tests/x86/vmx.h create mode 100644 tests/kvm-unit-tests/x86/vmx_tests.c create mode 100644 tests/kvm-unit-tests/x86/xsave.c create mode 100644 tests/manual/gc.html create mode 100644 tests/nasm/Makefile create mode 100644 tests/nasm/Readme.md create mode 100644 tests/nasm/arith-optimisations.asm create mode 100644 tests/nasm/btc-imm.asm create mode 100644 tests/nasm/btc-reg16.asm create mode 100644 tests/nasm/btc-reg32.asm create mode 100644 tests/nasm/btr-imm.asm create mode 100644 tests/nasm/btr-reg16.asm create mode 100644 tests/nasm/btr-reg32.asm create mode 100644 tests/nasm/bts-imm.asm create mode 100644 tests/nasm/bts-reg16.asm create mode 100644 tests/nasm/bts-reg32.asm create mode 100644 tests/nasm/cmp16-setbe.asm create mode 100644 tests/nasm/cmpxchg-setbe.asm create mode 100644 tests/nasm/cmpxchg.asm create mode 100644 tests/nasm/cmpxchg8b.asm create mode 100644 tests/nasm/comiss.asm create mode 100755 tests/nasm/create_tests.js create mode 100644 tests/nasm/cvtpi2ps.asm create mode 100644 tests/nasm/cvtps2pi.asm create mode 100644 tests/nasm/cvttps2pi.asm create mode 100644 tests/nasm/emms.asm create mode 100644 tests/nasm/f2xm1.asm create mode 100644 tests/nasm/fchs.asm create mode 100644 tests/nasm/fdecstp.asm create mode 100644 tests/nasm/fdiv-zero.asm create mode 100644 tests/nasm/fdiv.asm create mode 100644 tests/nasm/fdivr.asm create mode 100644 tests/nasm/fincstp.asm create mode 100644 tests/nasm/footer.inc create mode 100644 tests/nasm/fprem.asm create mode 100644 tests/nasm/fprem1.asm create mode 100644 tests/nasm/fptan.asm create mode 100644 tests/nasm/fpu_m80.asm create mode 100644 tests/nasm/frndint.asm create mode 100644 tests/nasm/fsave_frstor.asm create mode 100644 tests/nasm/fscale.asm create mode 100644 tests/nasm/fsincos.asm create mode 100644 tests/nasm/fsqrt.asm create mode 100644 tests/nasm/fstenv.asm create mode 100644 tests/nasm/fstm80.asm create mode 100644 tests/nasm/fxtract-zero.asm create mode 100644 tests/nasm/fxtract.asm create mode 100644 tests/nasm/fyl2x-zero.asm create mode 100644 tests/nasm/fyl2x.asm create mode 100644 tests/nasm/fyl2xp1.asm create mode 100644 tests/nasm/gdb-extract-def create mode 100755 tests/nasm/gen_fixtures.js create mode 100644 tests/nasm/header.inc create mode 100644 tests/nasm/idiv16-overflow.asm create mode 100644 tests/nasm/idiv32-overflow.asm create mode 100644 tests/nasm/idiv8-overflow.asm create mode 100644 tests/nasm/indirect-call.asm create mode 100644 tests/nasm/indirect-jump.asm create mode 100644 tests/nasm/jcxz.asm create mode 100644 tests/nasm/jump.asm create mode 100644 tests/nasm/lea-nop.asm create mode 100644 tests/nasm/leave16.asm create mode 100644 tests/nasm/leave32.asm create mode 100644 tests/nasm/loop.asm create mode 100644 tests/nasm/loopnz.asm create mode 100644 tests/nasm/loopz.asm create mode 100644 tests/nasm/maskmovdqu.asm create mode 100644 tests/nasm/maskmovq.asm create mode 100644 tests/nasm/mov16.asm create mode 100644 tests/nasm/mov_sreg.asm create mode 100644 tests/nasm/mov_sreg_ud1.asm create mode 100644 tests/nasm/mov_sreg_ud2.asm create mode 100644 tests/nasm/movaps.asm create mode 100644 tests/nasm/movd.asm create mode 100644 tests/nasm/movntpd.asm create mode 100644 tests/nasm/movntps.asm create mode 100644 tests/nasm/movq.asm create mode 100644 tests/nasm/packssdw.asm create mode 100644 tests/nasm/packsswb.asm create mode 100644 tests/nasm/packuswb.asm create mode 100644 tests/nasm/paddb.asm create mode 100644 tests/nasm/paddd.asm create mode 100644 tests/nasm/paddsb.asm create mode 100644 tests/nasm/paddsw.asm create mode 100644 tests/nasm/paddusb.asm create mode 100644 tests/nasm/paddusw.asm create mode 100644 tests/nasm/paddw.asm create mode 100644 tests/nasm/pand.asm create mode 100644 tests/nasm/pandn.asm create mode 100644 tests/nasm/pcmpeqb.asm create mode 100644 tests/nasm/pcmpeqd.asm create mode 100644 tests/nasm/pcmpeqw.asm create mode 100644 tests/nasm/pcmpgtb.asm create mode 100644 tests/nasm/pcmpgtd.asm create mode 100644 tests/nasm/pcmpgtw.asm create mode 100644 tests/nasm/pmaddwd.asm create mode 100644 tests/nasm/pmulhw.asm create mode 100644 tests/nasm/pmullw.asm create mode 100644 tests/nasm/pmuludq.asm create mode 100644 tests/nasm/pop_esp.asm create mode 100644 tests/nasm/pop_esp2.asm create mode 100644 tests/nasm/por.asm create mode 100644 tests/nasm/prand.js create mode 100644 tests/nasm/pshufw.asm create mode 100644 tests/nasm/pslld.asm create mode 100644 tests/nasm/psllq.asm create mode 100644 tests/nasm/psllw.asm create mode 100644 tests/nasm/psrad.asm create mode 100644 tests/nasm/psraw.asm create mode 100644 tests/nasm/psrld.asm create mode 100644 tests/nasm/psrlq.asm create mode 100644 tests/nasm/psrlw.asm create mode 100644 tests/nasm/psubb.asm create mode 100644 tests/nasm/psubd.asm create mode 100644 tests/nasm/psubsb.asm create mode 100644 tests/nasm/psubsw.asm create mode 100644 tests/nasm/psubusb.asm create mode 100644 tests/nasm/psubusw.asm create mode 100644 tests/nasm/psubw.asm create mode 100644 tests/nasm/punpckhbw.asm create mode 100644 tests/nasm/punpckhdq.asm create mode 100644 tests/nasm/punpckhwd.asm create mode 100644 tests/nasm/punpcklbw.asm create mode 100644 tests/nasm/punpckldq.asm create mode 100644 tests/nasm/punpcklwd.asm create mode 100644 tests/nasm/push.asm create mode 100644 tests/nasm/pushf.asm create mode 100644 tests/nasm/pxor.asm create mode 100644 tests/nasm/ret-imm.asm create mode 100755 tests/nasm/run.js create mode 100644 tests/nasm/shufps-edgecase.asm create mode 100644 tests/nasm/ucomiss.asm create mode 100644 tests/qemu/LICENSE create mode 100644 tests/qemu/Makefile create mode 100644 tests/qemu/Readme.md create mode 100644 tests/qemu/compiler.h create mode 100644 tests/qemu/config-host.h create mode 100755 tests/qemu/run-qemu.js create mode 100755 tests/qemu/run.js create mode 100644 tests/qemu/test-i386-code16.S create mode 100644 tests/qemu/test-i386-muldiv.h create mode 100644 tests/qemu/test-i386-shift.h create mode 100644 tests/qemu/test-i386-vm86.S create mode 100644 tests/qemu/test-i386.c create mode 100644 tests/qemu/test-i386.h create mode 100755 tests/rust/verify-wasmgen-dummy-output.js create mode 100755 tools/copy-to-sha256.py create mode 100644 tools/docker/README.md create mode 100644 tools/docker/debian/Dockerfile create mode 100644 tools/docker/debian/Readme.md create mode 100644 tools/docker/debian/boot-9p create mode 100755 tools/docker/debian/build-container.sh create mode 100755 tools/docker/debian/build-state.js create mode 100644 tools/docker/debian/getty-autologin-serial.conf create mode 100644 tools/docker/debian/getty-noclear.conf create mode 100644 tools/docker/debian/getty-override.conf create mode 100644 tools/docker/debian/logind.conf create mode 100644 tools/docker/debian/networking.sh create mode 100644 tools/docker/debian/xorg.conf create mode 100644 tools/docker/exec/Dockerfile create mode 100755 tools/docker/exec/build.sh create mode 100644 tools/docker/test-image/Dockerfile create mode 100755 tools/fs2json.py create mode 100755 tools/rust-lld-wrapper create mode 100644 v86.css diff --git a/.cargo/config b/.cargo/config new file mode 100644 index 0000000..fcd3355 --- /dev/null +++ b/.cargo/config @@ -0,0 +1,2 @@ +[build] +target-dir = "build" diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..d9668d8 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,6 @@ +root=true + +[*.js] +charset = utf-8 +indent_style = space +indent_size = 4 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..9b40d26 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +lib/zstd/* linguist-vendored +lib/softfloat/* linguist-vendored diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..78c4ca4 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,82 @@ +name: main +on: + push: + pull_request: +jobs: + jshint: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v2 + - run: sudo npm install -g jshint; make jshint + test: + runs-on: ubuntu-22.04 + steps: + - name: checkout + uses: actions/checkout@v2 + + - uses: actions/cache@v2 + id: cache-rustup + with: + path: ~/.cache/rustup/ + key: ${{ runner.os }}-rustup + - name: rustup + run: | + rustup toolchain install stable + rustup target add wasm32-unknown-unknown + rustup component add rustfmt + + - name: apt install + run: sudo apt update -qq; sudo apt install nasm gdb qemu-system-x86 libc6-dev-i386 + - name: make all-debug + run: make all-debug + - name: make all + run: make all + + - uses: actions/cache@v2 + id: cache-kvm-unit-test + with: + path: tests/kvm-unit-tests/ + key: ${{ runner.os }}-kvm-unit-test + - name: build kvm-unit-test + if: steps.cache-kvm-unit-test.outputs.cache-hit != 'true' + run: (cd tests/kvm-unit-tests && ./configure && make x86/realmode.flat) + - name: kvm-unit-test + run: tests/kvm-unit-tests/run.js tests/kvm-unit-tests/x86/realmode.flat + + - uses: actions/cache@v2 + id: cache-nasmtests + with: + path: tests/nasm/build/ + key: ${{ runner.os }}-nasmtests + - name: build namsmtests + if: steps.cache-nasmtests.outputs.cache-hit != 'true' + run: tests/nasm/create_tests.js; make -C tests/nasm all; ./tests/nasm/gen_fixtures.js + - name: nasmtests + run: MAX_PARALLEL_TESTS=1 ./tests/nasm/run.js + - name: nasmtests-force-jit + run: MAX_PARALLEL_TESTS=1 ./tests/nasm/run.js --force-jit + + - name: rust-test + run: make rust-test + + - uses: actions/cache@v2 + id: cache-images + with: + path: images/ + key: ${{ runner.os }}-images-v2 + - name: get images + if: steps.cache-images.outputs.cache-hit != 'true' + run: wget -nv -P images/ https://k.copy.sh/{linux.iso,linux3.iso,linux4.iso,buildroot-bzimage.bin,TinyCore-11.0.iso,oberon.img,msdos.img,openbsd-floppy.img,kolibri.img,windows101.img,os8.img,freedos722.img,mobius-fd-release5.img} + + - name: api-tests + run: make api-tests + - name: qemutests + run: make qemutests + - name: qemutests-release + run: make qemutests-release + - name: jitpagingtests + run: make jitpagingtests + - name: integration tests + run: MAX_PARALLEL_TESTS=1 make tests + - name: expect tests + run: make expect-tests diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..a09c216 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,38 @@ +on: + push: + branches: + - master + +jobs: + release: + name: Release to GitHub + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - uses: actions/cache@v2 + id: cache-rustup + with: + path: ~/.cache/rustup/ + key: ${{ runner.os }}-rustup + - name: rustup + run: | + rustup toolchain install stable + rustup target add wasm32-unknown-unknown + rustup component add rustfmt + + - name: Build v86 + run: make build/libv86.js build/v86.wasm build/v86-fallback.wasm + + - name: Release to GitHub + uses: marvinpinto/action-automatic-releases@latest + with: + title: Latest Release + automatic_release_tag: latest + repo_token: "${{ secrets.GITHUB_TOKEN }}" + files: | + build/*.js + build/*.js.map + build/*.wasm diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0b942c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +*.swp +*.swo +tests/qemu/test-i386 +tests/jit-paging/test-jit +*.map +build/ +closure-compiler/ +images/ +*.bak +*.orig +*.wasm +*.o +*.bin +*.img +*.fixture +*.fuse_hidden* +*.DS_Store +node_modules/ +Cargo.lock +build-head +src/rust/gen/interpreter.rs +src/rust/gen/interpreter0f.rs +src/rust/gen/analyzer.rs +src/rust/gen/analyzer0f.rs +src/rust/gen/jit.rs +src/rust/gen/jit0f.rs +bios/seabios diff --git a/.jshint.json b/.jshint.json new file mode 100644 index 0000000..ac873d6 --- /dev/null +++ b/.jshint.json @@ -0,0 +1,25 @@ +{ + "esversion": 8, + "globalstrict": true, + "sub": true, + "expr": true, + "-W058": true, + "-W080": true, + "-W082": true, + "-W079": true, + "-W117": true, + "-W054": true, + "-W027": true, + "-W040": true, + "-W087": true, + "-W008": true, + "loopfunc": true, + "shadow": true, + "funcscope": true, + "globals": { + "Blob": false, + "alert": false, + "console": false + }, + "browser": true +} diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000..6c4973c --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1,9 @@ +use_field_init_shorthand = true +match_block_trailing_comma = true +fn_single_line = true +imports_indent = "Block" +control_brace_style = "ClosingNextLine" +single_line_if_else_max_width = 92 +ignore = [ + "src/rust/gen" +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..326bb5e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "v86" +version = "0.1.0" +publish = false + +[features] +default = [] +profiler = [] + +[lib] +crate-type = ["cdylib"] +path = "src/rust/lib.rs" + +[profile.test] +lto = false +opt-level = 2 +overflow-checks = false + +[profile.dev] +lto = false +opt-level = 2 +panic = "abort" +overflow-checks = false + +[profile.release] +lto = true +opt-level = 3 +incremental = false +panic = "abort" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5033d6d --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012, The v86 contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..163e835 --- /dev/null +++ b/Makefile @@ -0,0 +1,339 @@ +CLOSURE_DIR=closure-compiler +CLOSURE=$(CLOSURE_DIR)/compiler.jar +NASM_TEST_DIR=./tests/nasm + +INSTRUCTION_TABLES=src/rust/gen/jit.rs src/rust/gen/jit0f.rs \ + src/rust/gen/interpreter.rs src/rust/gen/interpreter0f.rs \ + src/rust/gen/analyzer.rs src/rust/gen/analyzer0f.rs \ + +# Only the dependencies common to both generate_{jit,interpreter}.js +GEN_DEPENDENCIES=$(filter-out gen/generate_interpreter.js gen/generate_jit.js gen/generate_analyzer.js, $(wildcard gen/*.js)) +JIT_DEPENDENCIES=$(GEN_DEPENDENCIES) gen/generate_jit.js +INTERPRETER_DEPENDENCIES=$(GEN_DEPENDENCIES) gen/generate_interpreter.js +ANALYZER_DEPENDENCIES=$(GEN_DEPENDENCIES) gen/generate_analyzer.js + +STRIP_DEBUG_FLAG= +ifeq ($(STRIP_DEBUG),true) +STRIP_DEBUG_FLAG=--v86-strip-debug +endif + +WASM_OPT ?= false + +default: build/v86-debug.wasm +all: build/v86_all.js build/libv86.js build/v86.wasm +all-debug: build/libv86-debug.js build/v86-debug.wasm +browser: build/v86_all.js + +# Used for nodejs builds and in order to profile code. +# `debug` gives identifiers a readable name, make sure it doesn't have any side effects. +CLOSURE_READABLE=--formatting PRETTY_PRINT --debug + +CLOSURE_SOURCE_MAP=\ + --source_map_format V3\ + --create_source_map '%outname%.map' + +CLOSURE_FLAGS=\ + --generate_exports\ + --externs src/externs.js\ + --warning_level VERBOSE\ + --jscomp_error accessControls\ + --jscomp_error checkRegExp\ + --jscomp_error checkTypes\ + --jscomp_error checkVars\ + --jscomp_error conformanceViolations\ + --jscomp_error const\ + --jscomp_error constantProperty\ + --jscomp_error deprecated\ + --jscomp_error deprecatedAnnotations\ + --jscomp_error duplicateMessage\ + --jscomp_error es5Strict\ + --jscomp_error externsValidation\ + --jscomp_error globalThis\ + --jscomp_error invalidCasts\ + --jscomp_error misplacedTypeAnnotation\ + --jscomp_error missingProperties\ + --jscomp_error missingReturn\ + --jscomp_error msgDescriptions\ + --jscomp_error nonStandardJsDocs\ + --jscomp_error suspiciousCode\ + --jscomp_error strictModuleDepCheck\ + --jscomp_error typeInvalidation\ + --jscomp_error undefinedVars\ + --jscomp_error unknownDefines\ + --jscomp_error visibility\ + --use_types_for_optimization\ + --summary_detail_level 3\ + --language_in ECMASCRIPT_2017\ + --language_out ECMASCRIPT_2017 + +CARGO_FLAGS_SAFE=\ + --target wasm32-unknown-unknown \ + -- \ + -C linker=tools/rust-lld-wrapper \ + -C link-args="--import-table --global-base=4096 $(STRIP_DEBUG_FLAG)" \ + -C link-args="build/softfloat.o" \ + -C link-args="build/zstddeclib.o" \ + --verbose + +CARGO_FLAGS=$(CARGO_FLAGS_SAFE) -C target-feature=+bulk-memory + +CORE_FILES=const.js config.js io.js main.js lib.js buffer.js ide.js pci.js floppy.js \ + memory.js dma.js pit.js vga.js ps2.js pic.js rtc.js uart.js hpet.js \ + acpi.js apic.js ioapic.js \ + state.js ne2k.js sb16.js virtio.js bus.js log.js \ + cpu.js debug.js \ + elf.js kernel.js +LIB_FILES=9p.js filesystem.js jor1k.js marshall.js utf8.js +BROWSER_FILES=screen.js keyboard.js mouse.js speaker.js serial.js \ + network.js starter.js worker_bus.js dummy_screen.js \ + print_stats.js filestorage.js + +RUST_FILES=$(shell find src/rust/ -name '*.rs') \ + src/rust/gen/interpreter.rs src/rust/gen/interpreter0f.rs \ + src/rust/gen/jit.rs src/rust/gen/jit0f.rs \ + src/rust/gen/analyzer.rs src/rust/gen/analyzer0f.rs + +CORE_FILES:=$(addprefix src/,$(CORE_FILES)) +LIB_FILES:=$(addprefix lib/,$(LIB_FILES)) +BROWSER_FILES:=$(addprefix src/browser/,$(BROWSER_FILES)) + +build/v86_all.js: $(CLOSURE) src/*.js src/browser/*.js lib/*.js + mkdir -p build + -ls -lh build/v86_all.js + java -jar $(CLOSURE) \ + --js_output_file build/v86_all.js\ + --define=DEBUG=false\ + $(CLOSURE_SOURCE_MAP)\ + $(CLOSURE_FLAGS)\ + --compilation_level ADVANCED\ + --js $(CORE_FILES)\ + --js $(LIB_FILES)\ + --js $(BROWSER_FILES)\ + --js src/browser/main.js + ls -lh build/v86_all.js + +build/v86_all_debug.js: $(CLOSURE) src/*.js src/browser/*.js lib/*.js + mkdir -p build + java -jar $(CLOSURE) \ + --js_output_file build/v86_all_debug.js\ + --define=DEBUG=true\ + $(CLOSURE_SOURCE_MAP)\ + $(CLOSURE_FLAGS)\ + --compilation_level ADVANCED\ + --js $(CORE_FILES)\ + --js $(LIB_FILES)\ + --js $(BROWSER_FILES)\ + --js src/browser/main.js + +build/libv86.js: $(CLOSURE) src/*.js lib/*.js src/browser/*.js + mkdir -p build + -ls -lh build/libv86.js + java -jar $(CLOSURE) \ + --js_output_file build/libv86.js\ + --define=DEBUG=false\ + $(CLOSURE_FLAGS)\ + --compilation_level SIMPLE\ + --jscomp_off=missingProperties\ + --output_wrapper ';(function(){%output%}).call(this);'\ + --js $(CORE_FILES)\ + --js $(BROWSER_FILES)\ + --js $(LIB_FILES) + ls -lh build/libv86.js + +build/libv86-debug.js: $(CLOSURE) src/*.js lib/*.js src/browser/*.js + mkdir -p build + java -jar $(CLOSURE) \ + --js_output_file build/libv86-debug.js\ + --define=DEBUG=true\ + $(CLOSURE_FLAGS)\ + $(CLOSURE_READABLE)\ + --compilation_level SIMPLE\ + --jscomp_off=missingProperties\ + --output_wrapper ';(function(){%output%}).call(this);'\ + --js $(CORE_FILES)\ + --js $(BROWSER_FILES)\ + --js $(LIB_FILES) + +src/rust/gen/jit.rs: $(JIT_DEPENDENCIES) + ./gen/generate_jit.js --output-dir build/ --table jit +src/rust/gen/jit0f.rs: $(JIT_DEPENDENCIES) + ./gen/generate_jit.js --output-dir build/ --table jit0f + +src/rust/gen/interpreter.rs: $(INTERPRETER_DEPENDENCIES) + ./gen/generate_interpreter.js --output-dir build/ --table interpreter +src/rust/gen/interpreter0f.rs: $(INTERPRETER_DEPENDENCIES) + ./gen/generate_interpreter.js --output-dir build/ --table interpreter0f + +src/rust/gen/analyzer.rs: $(ANALYZER_DEPENDENCIES) + ./gen/generate_analyzer.js --output-dir build/ --table analyzer +src/rust/gen/analyzer0f.rs: $(ANALYZER_DEPENDENCIES) + ./gen/generate_analyzer.js --output-dir build/ --table analyzer0f + +build/v86.wasm: $(RUST_FILES) build/softfloat.o build/zstddeclib.o Cargo.toml + mkdir -p build/ + -BLOCK_SIZE=K ls -l build/v86.wasm + cargo rustc --release $(CARGO_FLAGS) + cp build/wasm32-unknown-unknown/release/v86.wasm build/v86.wasm + -$(WASM_OPT) && wasm-opt -O2 --strip-debug build/v86.wasm -o build/v86.wasm + BLOCK_SIZE=K ls -l build/v86.wasm + +build/v86-debug.wasm: $(RUST_FILES) build/softfloat.o build/zstddeclib.o Cargo.toml + mkdir -p build/ + -BLOCK_SIZE=K ls -l build/v86-debug.wasm + cargo rustc $(CARGO_FLAGS) + cp build/wasm32-unknown-unknown/debug/v86.wasm build/v86-debug.wasm + BLOCK_SIZE=K ls -l build/v86-debug.wasm + +build/v86-fallback.wasm: $(RUST_FILES) build/softfloat.o build/zstddeclib.o Cargo.toml + mkdir -p build/ + cargo rustc --release $(CARGO_FLAGS_SAFE) + cp build/wasm32-unknown-unknown/release/v86.wasm build/v86-fallback.wasm || true + +debug-with-profiler: $(RUST_FILES) build/softfloat.o build/zstddeclib.o Cargo.toml + mkdir -p build/ + cargo rustc --features profiler $(CARGO_FLAGS) + cp build/wasm32-unknown-unknown/debug/v86.wasm build/v86-debug.wasm || true + +with-profiler: $(RUST_FILES) build/softfloat.o build/zstddeclib.o Cargo.toml + mkdir -p build/ + cargo rustc --release --features profiler $(CARGO_FLAGS) + cp build/wasm32-unknown-unknown/release/v86.wasm build/v86.wasm || true + +build/softfloat.o: lib/softfloat/softfloat.c + mkdir -p build + clang -c -Wall \ + --target=wasm32 -O3 -flto -nostdlib -fvisibility=hidden -ffunction-sections -fdata-sections \ + -DSOFTFLOAT_FAST_INT64 -DINLINE_LEVEL=5 -DSOFTFLOAT_FAST_DIV32TO16 -DSOFTFLOAT_FAST_DIV64TO32 \ + -o build/softfloat.o \ + lib/softfloat/softfloat.c + +build/zstddeclib.o: lib/zstd/zstddeclib.c + mkdir -p build + clang -c -Wall \ + --target=wasm32 -O3 -flto -nostdlib -fvisibility=hidden -ffunction-sections -fdata-sections \ + -DZSTDLIB_VISIBILITY="" \ + -o build/zstddeclib.o \ + lib/zstd/zstddeclib.c + +clean: + -rm build/libv86.js + -rm build/libv86-debug.js + -rm build/v86_all.js + -rm build/v86.wasm + -rm build/v86-debug.wasm + -rm $(INSTRUCTION_TABLES) + -rm build/*.map + -rm build/*.wast + -rm build/*.o + $(MAKE) -C $(NASM_TEST_DIR) clean + +run: + python3 -m http.server 2> /dev/null + +update_version: + set -e ;\ + COMMIT=`git log --format="%h" -n 1` ;\ + DATE=`git log --date="format:%b %e, %Y %H:%m" --format="%cd" -n 1` ;\ + SEARCH='Version: [a-f0-9]\+ ([^(]\+)' ;\ + REPLACE='Version: '$$COMMIT' ('$$DATE')' ;\ + sed -i "s@$$SEARCH@$$REPLACE@g" index.html ;\ + grep $$COMMIT index.html + + +$(CLOSURE): + mkdir -p $(CLOSURE_DIR) + # don't upgrade until https://github.com/google/closure-compiler/issues/3972 is fixed + wget -nv -O $(CLOSURE) https://repo1.maven.org/maven2/com/google/javascript/closure-compiler/v20210601/closure-compiler-v20210601.jar + +build/integration-test-fs/fs.json: + mkdir -p build/integration-test-fs/flat + cp images/buildroot-bzimage.bin build/integration-test-fs/bzImage + touch build/integration-test-fs/initrd + cd build/integration-test-fs && tar cfv fs.tar bzImage initrd + ./tools/fs2json.py build/integration-test-fs/fs.tar --out build/integration-test-fs/fs.json + ./tools/copy-to-sha256.py build/integration-test-fs/fs.tar build/integration-test-fs/flat + rm build/integration-test-fs/fs.tar build/integration-test-fs/bzImage build/integration-test-fs/initrd + +tests: all-debug build/integration-test-fs/fs.json + ./tests/full/run.js + +tests-release: build/libv86.js build/v86.wasm build/integration-test-fs/fs.json + TEST_RELEASE_BUILD=1 ./tests/full/run.js + +nasmtests: all-debug + $(MAKE) -C $(NASM_TEST_DIR) all + $(NASM_TEST_DIR)/gen_fixtures.js + $(NASM_TEST_DIR)/run.js + +nasmtests-force-jit: all-debug + $(MAKE) -C $(NASM_TEST_DIR) all + $(NASM_TEST_DIR)/gen_fixtures.js + $(NASM_TEST_DIR)/run.js --force-jit + +jitpagingtests: all-debug + $(MAKE) -C tests/jit-paging test-jit + ./tests/jit-paging/run.js + +qemutests: all-debug + $(MAKE) -C tests/qemu test-i386 + ./tests/qemu/run.js > build/qemu-test-result + ./tests/qemu/run-qemu.js > build/qemu-test-reference + diff build/qemu-test-result build/qemu-test-reference + +qemutests-release: build/libv86.js build/v86.wasm + $(MAKE) -C tests/qemu test-i386 + TEST_RELEASE_BUILD=1 time ./tests/qemu/run.js > build/qemu-test-result + ./tests/qemu/run-qemu.js > build/qemu-test-reference + diff build/qemu-test-result build/qemu-test-reference + +kvm-unit-test: all-debug + (cd tests/kvm-unit-tests && ./configure && make x86/realmode.flat) + tests/kvm-unit-tests/run.js tests/kvm-unit-tests/x86/realmode.flat + +kvm-unit-test-release: build/libv86.js build/v86.wasm + (cd tests/kvm-unit-tests && ./configure && make x86/realmode.flat) + TEST_RELEASE_BUILD=1 tests/kvm-unit-tests/run.js tests/kvm-unit-tests/x86/realmode.flat + +expect-tests: all-debug build/libwabt.js + make -C tests/expect/tests + ./tests/expect/run.js + +devices-test: all-debug + ./tests/devices/virtio_9p.js + +rust-test: $(RUST_FILES) + env RUSTFLAGS="-D warnings" RUST_BACKTRACE=full RUST_TEST_THREADS=1 cargo test -- --nocapture + ./tests/rust/verify-wasmgen-dummy-output.js + +rust-test-intensive: + QUICKCHECK_TESTS=100000000 make rust-test + +api-tests: all-debug + ./tests/api/clean-shutdown.js + ./tests/api/state.js + ./tests/api/reset.js + +all-tests: jshint kvm-unit-test qemutests qemutests-release jitpagingtests api-tests nasmtests nasmtests-force-jit tests expect-tests + # Skipping: + # - devices-test (hangs) + +jshint: + jshint --config=./.jshint.json src tests gen lib + +rustfmt: $(RUST_FILES) + cargo fmt --all -- --check + +build/capstone-x86.min.js: + mkdir -p build + wget -nv -P build https://github.com/AlexAltea/capstone.js/releases/download/v3.0.5-rc1/capstone-x86.min.js + +build/libwabt.js: + mkdir -p build + wget -nv -P build https://github.com/WebAssembly/wabt/archive/1.0.6.zip + unzip -j -d build/ build/1.0.6.zip wabt-1.0.6/demo/libwabt.js + rm build/1.0.6.zip + +build/xterm.js: + curl https://cdn.jsdelivr.net/npm/xterm@4.9.0/lib/xterm.js > build/xterm.js + curl https://cdn.jsdelivr.net/npm/xterm@4.9.0/lib/xterm.js.map > build/xterm.js.map + curl https://cdn.jsdelivr.net/npm/xterm@4.9.0/css/xterm.css > build/xterm.css diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..cb20f00 --- /dev/null +++ b/Readme.md @@ -0,0 +1,184 @@ +[![Join the chat at https://gitter.im/copy/v86](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/copy/v86) or #v86 on [irc.libera.chat](https://libera.chat/) + +v86 emulates an x86-compatible CPU and hardware. Machine code is translated to +WebAssembly modules at runtime in order to achieve decent performance. Here's a +list of emulated hardware: + +- An x86-compatible CPU. The instruction set is around Pentium III level, + including full SSE2 support. Some features are missing, in particular: + - Task gates, far calls in protected mode + - Some 16 bit protected mode features + - Single stepping (trap flag, debug registers) + - Some exceptions, especially floating point and SSE + - Multicore + - 64-bit extensions +- A floating point unit (FPU). Calculations are done using the Berkeley + SoftFloat library and therefore should be precise (but slow). Trigonometric + and log functions are emulated using 64-bit floats and may be less precise. + Not all FPU exceptions are supported. +- A floppy disk controller (8272A). +- An 8042 Keyboard Controller, PS2. With mouse support. +- An 8254 Programmable Interval Timer (PIT). +- An 8259 Programmable Interrupt Controller (PIC). +- Partial APIC support. +- A CMOS Real Time Clock (RTC). +- A generic VGA card with SVGA support and Bochs VBE Extensions. +- A PCI bus. This one is partly incomplete and not used by every device. +- An IDE disk controller. +- An NE2000 (8390) PCI network card. +- A virtio filesystem. +- A SoundBlaster 16 sound card. + +## Demos + +[Arch Linux](https://copy.sh/v86/?profile=archlinux) — +[Damn Small Linux](https://copy.sh/v86/?profile=dsl) — +[Buildroot Linux](https://copy.sh/v86/?profile=buildroot) — +[ReactOS](https://copy.sh/v86/?profile=reactos) — +[Windows 2000](https://copy.sh/v86/?profile=windows2000) — +[Windows 98](https://copy.sh/v86/?profile=windows98) — +[Windows 95](https://copy.sh/v86/?profile=windows95) — +[Windows 1.01](https://copy.sh/v86/?profile=windows1) — +[MS-DOS](https://copy.sh/v86/?profile=msdos) — +[FreeDOS](https://copy.sh/v86/?profile=freedos) — +[FreeBSD](https://copy.sh/v86/?profile=freebsd) — +[OpenBSD](https://copy.sh/v86/?profile=openbsd) — +[9front](https://copy.sh/v86/?profile=9front) — +[Haiku](https://copy.sh/v86/?profile=haiku) — +[Oberon](https://copy.sh/v86/?profile=oberon) — +[KolibriOS](https://copy.sh/v86/?profile=kolibrios) — +[QNX](https://copy.sh/v86/?profile=qnx) + +## Compatibility + +Here's an overview of the operating systems supported in v86: + +- Linux works pretty well. 64-bit kernels are not supported. + - Damn Small Linux (2.4 Kernel) works. + - All tested versions of TinyCore work. + - [Buildroot](https://buildroot.uclibc.org) can be used to build a minimal image. + [humphd/browser-vm](https://github.com/humphd/browser-vm) and + [darin755/browser-buildroot](https://github.com/Darin755/browser-buildroot) have some useful scripts for building one. + - [SkiffOS](https://github.com/skiffos/SkiffOS/tree/master/configs/browser/v86) (based on Buildroot) can cross-compile a custom image. + - Archlinux works. See [archlinux.md](docs/archlinux.md) for building an image. + - Debian works. An image can be built from a Dockerfile, see [tools/docker/debian/](tools/docker/debian/). + - Ubuntu up to 16.04 works. + - Alpine Linux works. +- ReactOS works. +- FreeDOS, Windows 1.01 and MS-DOS run very well. +- KolibriOS works. +- Haiku works. +- Android x86 1.6-r2 works if one selects VESA mode at the boot prompt. Newer + versions may work if compiled without SSE3. See [#224](https://github.com/copy/v86/issues/224). +- Windows 1, 3.0, 95, 98, ME and 2000 work. Other versions currently don't (see [#86](https://github.com/copy/v86/issues/86), [#208](https://github.com/copy/v86/issues/208)). + - In Windows 2000 and higher the PC type has to be changed from ACPI PC to Standard PC +- Many hobby operating systems work. +- 9front works. +- Plan 9 doesn't work. +- QNX works. +- OS/2 doesn't work. +- FreeBSD works. +- OpenBSD works with a specific boot configuration. At the `boot>` prompt type + `boot -c`, then at the `UKC>` prompt `disable mpbios` and `exit`. +- NetBSD works only with a custom kernel, see [#350](https://github.com/copy/v86/issues/350). +- SerenityOS works. + +You can get some infos on the disk images here: https://github.com/copy/images. + +## How to build, run and embed? + +You need: + +- make +- Rust with the wasm32-unknown-unknown target +- A version of clang compatible with Rust +- java (for Closure Compiler, not necessary when using `debug.html`) +- nodejs (a recent version is required, v16.11.1 is known to be working) +- To run tests: nasm, gdb, qemu-system, gcc, libc-i386 and rustfmt + +See [tools/docker/test-image/Dockerfile](tools/docker/test-image/Dockerfile) +for a full setup on Debian or +[WSL](https://docs.microsoft.com/en-us/windows/wsl/install). + +- Run `make` to build the debug build (at `debug.html`). +- Run `make all` to build the optimized build (at `index.html`). +- ROM and disk images are loaded via XHR, so if you want to try out `index.html` + locally, make sure to serve it from a local webserver. You can use `make run` + to serve the files using Python's http module. +- If you only want to embed v86 in a webpage you can use libv86.js. For usage, + check out the [examples](examples/). You can download it from the release section. + +### Alternatively, to build using docker + +- If you have docker installed, you can run the whole system inside a container. +- See `tools/docker/exec` to find Dockerfile required for this. +- You can run `docker build -f tools/docker/exec/Dockerfile -t v86:alpine-3.14 .` from the root directory to generate docker image. +- Then you can simply run `docker run -it -p 8000:8000 v86:alpine-3.14` to start the server. +- Check `localhost:8000` for hosted server. + +## Testing + +The disk images for testing are not included in this repository. You can +download them directly from the website using: + +`wget -P images/ https://k.copy.sh/{linux.iso,linux4.iso,buildroot-bzimage.bin,openbsd-floppy.img,kolibri.img,windows101.img,os8.img,freedos722.img}` + +Run all tests: `make jshint rustfmt kvm-unit-test nasmtests nasmtests-force-jit expect-tests jitpagingtests qemutests rust-test tests` + +See [tests/Readme.md](tests/Readme.md) for more infos. + +## API examples + +- [Basic](examples/basic.html) +- [Programatically using the serial terminal](examples/serial.html) +- [A Lua interpreter](examples/lua.html) +- [Two instances in one window](examples/two_instances.html) +- [Saving and restoring emulator state](examples/save_restore.html) + +Using v86 for your own purposes is as easy as: + +```javascript +var emulator = new V86Starter({ + screen_container: document.getElementById("screen_container"), + bios: { + url: "../../bios/seabios.bin", + }, + vga_bios: { + url: "../../bios/vgabios.bin", + }, + cdrom: { + url: "../../images/linux.iso", + }, + autostart: true, +}); +``` + +See [starter.js](src/browser/starter.js). + +## License + +v86 is distributed under the terms of the Simplified BSD License, see +[LICENSE](LICENSE). The following third-party dependencies are included in the +repository under their own licenses: + +- [`lib/softfloat/softfloat.c`](lib/softfloat/softfloat.c) +- [`lib/zstd/zstddeclib.c`](lib/zstd/zstddeclib.c) +- [`tests/kvm-unit-tests/`](tests/kvm-unit-tests) +- [`tests/qemutests/`](tests/qemutests) + +## Credits + +- CPU test cases via [QEMU](https://wiki.qemu.org/Main_Page) +- More tests via [kvm-unit-tests](https://www.linux-kvm.org/page/KVM-unit-tests) +- [zstd](https://github.com/facebook/zstd) support is included for better compression of state images +- [Berkeley SoftFloat](http://www.jhauser.us/arithmetic/SoftFloat.html) is included to precisely emulate 80-bit floating point numbers +- [The jor1k project](https://github.com/s-macke/jor1k) for 9p, filesystem and uart drivers +- [WinWorld](https://winworldpc.com/) sources of some old operating systems + +## More questions? + +Shoot me an email to `copy@copy.sh`. Please report bugs on GitHub. + +## Author + +Fabian Hemmer (https://copy.sh/, `copy@copy.sh`) diff --git a/bios/.gitignore b/bios/.gitignore new file mode 100644 index 0000000..10d00b5 --- /dev/null +++ b/bios/.gitignore @@ -0,0 +1 @@ +*.gz diff --git a/bios/COPYING.LESSER b/bios/COPYING.LESSER new file mode 100644 index 0000000..fc8a5de --- /dev/null +++ b/bios/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/bios/fetch-and-build-seabios.sh b/bios/fetch-and-build-seabios.sh new file mode 100755 index 0000000..3624fe2 --- /dev/null +++ b/bios/fetch-and-build-seabios.sh @@ -0,0 +1,13 @@ +set -e +git clone https://git.seabios.org/seabios.git || true +(cd seabios && git checkout rel-1.12.1) + +cp seabios.config seabios/.config +make -C seabios +cp seabios/out/bios.bin seabios.bin +cp seabios/out/vgabios.bin vgabios.bin + +cp seabios-debug.config seabios/.config +make -C seabios +cp seabios/out/bios.bin seabios-debug.bin +cp seabios/out/vgabios.bin vgabios-debug.bin diff --git a/bios/seabios-debug.config b/bios/seabios-debug.config new file mode 100644 index 0000000..59e4cd7 --- /dev/null +++ b/bios/seabios-debug.config @@ -0,0 +1,117 @@ +# +# Automatically generated file; DO NOT EDIT. +# SeaBIOS Configuration +# + +# +# General Features +# +# CONFIG_COREBOOT is not set +CONFIG_QEMU=y +# CONFIG_CSM is not set +CONFIG_QEMU_HARDWARE=y +CONFIG_XEN=y +CONFIG_THREADS=y +# CONFIG_RELOCATE_INIT is not set +# CONFIG_BOOTMENU is not set +CONFIG_BOOTORDER=y +CONFIG_MULTIBOOT=y +CONFIG_ENTRY_EXTRASTACK=y +CONFIG_MALLOC_UPPERMEMORY=y +CONFIG_ROM_SIZE=0 + +# +# Hardware support +# +CONFIG_ATA=y +CONFIG_ATA_DMA=y +CONFIG_ATA_PIO32=y +CONFIG_AHCI=y +CONFIG_SDCARD=y +CONFIG_VIRTIO_BLK=y +CONFIG_VIRTIO_SCSI=y +CONFIG_PVSCSI=y +CONFIG_ESP_SCSI=y +CONFIG_LSI_SCSI=y +CONFIG_MEGASAS=y +CONFIG_MPT_SCSI=y +CONFIG_FLOPPY=y +CONFIG_FLASH_FLOPPY=y +# CONFIG_NVME is not set +CONFIG_PS2PORT=y +# CONFIG_USB is not set +CONFIG_SERIAL=y +# CONFIG_SERCON is not set +CONFIG_LPT=y +CONFIG_RTC_TIMER=y +CONFIG_HARDWARE_IRQ=y +CONFIG_USE_SMM=y +CONFIG_CALL32_SMM=y +CONFIG_MTRR_INIT=y +CONFIG_PMTIMER=y +CONFIG_TSC_TIMER=y + +# +# BIOS interfaces +# +CONFIG_DRIVES=y +CONFIG_CDROM_BOOT=y +CONFIG_CDROM_EMU=y +CONFIG_PCIBIOS=y +CONFIG_APMBIOS=y +CONFIG_PNPBIOS=y +CONFIG_OPTIONROMS=y +CONFIG_PMM=y +CONFIG_BOOT=y +CONFIG_KEYBOARD=y +CONFIG_KBD_CALL_INT15_4F=y +CONFIG_MOUSE=y +CONFIG_S3_RESUME=y +CONFIG_VGAHOOKS=y +# CONFIG_DISABLE_A20 is not set +# CONFIG_WRITABLE_UPPERMEMORY is not set +CONFIG_TCGBIOS=y + +# +# BIOS Tables +# +CONFIG_PIRTABLE=y +CONFIG_MPTABLE=y +# CONFIG_SMBIOS is not set +CONFIG_ACPI=y +CONFIG_ACPI_DSDT=y +CONFIG_FW_ROMFILE_LOAD=y + +# +# VGA ROM +# +# CONFIG_NO_VGABIOS is not set +# CONFIG_VGA_STANDARD_VGA is not set +# CONFIG_VGA_CIRRUS is not set +CONFIG_VGA_BOCHS=y +# CONFIG_VGA_GEODEGX2 is not set +# CONFIG_VGA_GEODELX is not set +# CONFIG_DISPLAY_BOCHS is not set +# CONFIG_VGA_RAMFB is not set +CONFIG_VGA_BOCHS_STDVGA=y +# CONFIG_VGA_BOCHS_VMWARE is not set +# CONFIG_VGA_BOCHS_QXL is not set +# CONFIG_VGA_BOCHS_VIRTIO is not set +CONFIG_BUILD_VGABIOS=y +CONFIG_VGA_STDVGA_PORTS=y +CONFIG_VGA_FIXUP_ASM=y +CONFIG_VGA_ALLOCATE_EXTRA_STACK=y +CONFIG_VGA_EXTRA_STACK_SIZE=512 +CONFIG_VGA_VBE=y +CONFIG_VGA_PCI=y +CONFIG_OVERRIDE_PCI_ID=y +CONFIG_VGA_VID=0x1234 +CONFIG_VGA_DID=0x1111 + +# +# Debugging +# +CONFIG_DEBUG_LEVEL=8 +# CONFIG_DEBUG_SERIAL is not set +# CONFIG_DEBUG_SERIAL_MMIO is not set +CONFIG_DEBUG_IO=y diff --git a/bios/seabios.config b/bios/seabios.config new file mode 100644 index 0000000..2be1f89 --- /dev/null +++ b/bios/seabios.config @@ -0,0 +1,114 @@ +# +# Automatically generated file; DO NOT EDIT. +# SeaBIOS Configuration +# + +# +# General Features +# +# CONFIG_COREBOOT is not set +CONFIG_QEMU=y +# CONFIG_CSM is not set +CONFIG_QEMU_HARDWARE=y +CONFIG_XEN=y +CONFIG_THREADS=y +# CONFIG_RELOCATE_INIT is not set +# CONFIG_BOOTMENU is not set +CONFIG_BOOTORDER=y +CONFIG_MULTIBOOT=y +CONFIG_ENTRY_EXTRASTACK=y +CONFIG_MALLOC_UPPERMEMORY=y +CONFIG_ROM_SIZE=0 + +# +# Hardware support +# +CONFIG_ATA=y +CONFIG_ATA_DMA=y +CONFIG_ATA_PIO32=y +CONFIG_AHCI=y +CONFIG_SDCARD=y +CONFIG_VIRTIO_BLK=y +CONFIG_VIRTIO_SCSI=y +CONFIG_PVSCSI=y +CONFIG_ESP_SCSI=y +CONFIG_LSI_SCSI=y +CONFIG_MEGASAS=y +CONFIG_MPT_SCSI=y +CONFIG_FLOPPY=y +CONFIG_FLASH_FLOPPY=y +# CONFIG_NVME is not set +CONFIG_PS2PORT=y +# CONFIG_USB is not set +CONFIG_SERIAL=y +# CONFIG_SERCON is not set +CONFIG_LPT=y +CONFIG_RTC_TIMER=y +CONFIG_HARDWARE_IRQ=y +CONFIG_USE_SMM=y +CONFIG_CALL32_SMM=y +CONFIG_MTRR_INIT=y +CONFIG_PMTIMER=y +CONFIG_TSC_TIMER=y + +# +# BIOS interfaces +# +CONFIG_DRIVES=y +CONFIG_CDROM_BOOT=y +CONFIG_CDROM_EMU=y +CONFIG_PCIBIOS=y +CONFIG_APMBIOS=y +CONFIG_PNPBIOS=y +CONFIG_OPTIONROMS=y +CONFIG_PMM=y +CONFIG_BOOT=y +CONFIG_KEYBOARD=y +CONFIG_KBD_CALL_INT15_4F=y +CONFIG_MOUSE=y +CONFIG_S3_RESUME=y +CONFIG_VGAHOOKS=y +# CONFIG_DISABLE_A20 is not set +# CONFIG_WRITABLE_UPPERMEMORY is not set +CONFIG_TCGBIOS=y + +# +# BIOS Tables +# +CONFIG_PIRTABLE=y +CONFIG_MPTABLE=y +# CONFIG_SMBIOS is not set +CONFIG_ACPI=y +CONFIG_ACPI_DSDT=y +CONFIG_FW_ROMFILE_LOAD=y + +# +# VGA ROM +# +# CONFIG_NO_VGABIOS is not set +# CONFIG_VGA_STANDARD_VGA is not set +# CONFIG_VGA_CIRRUS is not set +CONFIG_VGA_BOCHS=y +# CONFIG_VGA_GEODEGX2 is not set +# CONFIG_VGA_GEODELX is not set +# CONFIG_DISPLAY_BOCHS is not set +# CONFIG_VGA_RAMFB is not set +CONFIG_VGA_BOCHS_STDVGA=y +# CONFIG_VGA_BOCHS_VMWARE is not set +# CONFIG_VGA_BOCHS_QXL is not set +# CONFIG_VGA_BOCHS_VIRTIO is not set +CONFIG_BUILD_VGABIOS=y +CONFIG_VGA_STDVGA_PORTS=y +CONFIG_VGA_FIXUP_ASM=y +CONFIG_VGA_ALLOCATE_EXTRA_STACK=y +CONFIG_VGA_EXTRA_STACK_SIZE=512 +CONFIG_VGA_VBE=y +CONFIG_VGA_PCI=y +CONFIG_OVERRIDE_PCI_ID=y +CONFIG_VGA_VID=0x1234 +CONFIG_VGA_DID=0x1111 + +# +# Debugging +# +CONFIG_DEBUG_LEVEL=0 diff --git a/debug.html b/debug.html new file mode 100644 index 0000000..704377c --- /dev/null +++ b/debug.html @@ -0,0 +1,363 @@ + + + +Virtual x86 (debug) + + + + + +
+
+

Debugger

+ + + +
+ + + + + + +
+ + + + + + +
+ + + + + + +
+ + + + + + + +
+ + + +
+ + + + + +
+ + + + + + + +
+ + + + + + + +
+ + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +


Second hard drive disk image



Disk images are not uploaded to the server
+ MB
+
+ MB
+
+ +

+
+
+
+

+ +
+ +
+ +
+
+
+ + + +

+    
+    
+
+ + + + + + + + + + +

+ + + +
diff --git a/docs/.gitignore b/docs/.gitignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/docs/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/docs/archlinux.md b/docs/archlinux.md new file mode 100644 index 0000000..e2e62c4 --- /dev/null +++ b/docs/archlinux.md @@ -0,0 +1,490 @@ +(This document partly also applies to other Linuxes) + +Choosing an installer ISO +------------------------- + +The last ISO installer version of Archlinux that supports 32-bit is [2017.02.01](https://www.archlinux.org/releng/releases/2017.02.01/). Later versions of the archisos don't work on the v86 emulator because the installer only supports x86_64, not x86 anymore. For existing Archlinux installations, updates and patches will be done until somewhere around 2018. + +In the future the community might come up with an alternative distribution based on Archlinux to maintain support for x86. At this point in time [archlinux32](https://mirror.archlinux32.org) seems to work. + +Basic installation using QEMU +----------------------- + +Installing Archlinux like this will result in a raw disk image that can be booted by v86. + +```sh +# fetch archlinux32 installer +wget https://mirror.archlinux32.org/archisos/archlinux32-2021.12.01-i686.iso + +# Create a 10 gigabyte disk image. If you intend to pacstrap only 'base' then 1.5G should be fine also. +qemu-img create arch.img 10G + +# Follow the normal installation process (you can add accel=kvm if your system supports it to speed up the installation) +qemu-system-x86_64 -m 256 -drive file=arch.img,format=raw -cdrom archlinux32-2021.12.01-i686.iso +``` + +For keyboard support it is necessary to open /etc/mkinitcpio.conf and edit the following line: + +```sh +MODULES="atkbd i8042" +``` + +For the changes to take effect you need to regenerate the RAMdisk with `mkinitcpio -p linux` + +The resulting `arch.img` is a bootable disk image for v86. + +Scripting image creation for v86 +-------------------------------- + +Installing the ISO by hand takes a long time if you intend to recreate the image many times. There are various reasons why you might want to do this more than once. For example: because the emulator is slow you might want to compile any new software release in QEMU which is much faster and then use the resulting image in v86 instead of making the emulator compile the software. Another reason is that the build progress potentially takes long and if you want to do automated builds in parallel to find out what configurations do and don't work you can just throw more computing power at the problem in order to solve it. This example requires that you have `packer`, `qemu` and `kpartx` installed. + +### Creating a packer template + +[Packer](https://www.packer.io/docs/builders/qemu.html) is a tool that lets you boot an ISO in any of multiple emulators (so QEMU in our case) and send pre-scripted keystrokes to bootstrap and SSH server. Once the SSH connection is established a script can be started for further provisioning. + +Create a template for automating the base installation +```sh +mkdir -p packer +cat > packer/template.json << 'EOF' +{ + "provisioners": [ + { + "type": "shell", + "override": { + "qemu": { + "scripts": ["scripts/provision.sh"] + } + } + } + ], + "builders": [ + { + "accelerator": "kvm", + "type": "qemu", + "boot_command": [ + "", + "dhcpcd", + "echo root:root | chpasswd", + "systemctl start sshd" + ], + "headless": true, + "boot_wait": "10s", + "disk_size": 1500, + "disk_interface": "ide", + "iso_url": "https://mirror.archlinux32.org/archisos/archlinux32-2021.12.01-i686.iso", + "iso_checksum": "90c6f5aecb095d5578f6c9970539da7c5e9324ec", + "iso_checksum_type": "sha1", + "ssh_wait_timeout": "120s", + "ssh_pty": true, + "ssh_username": "root", + "ssh_password": "root", + "ssh_port": 22, + "format": "raw", + "vm_name": "archlinux", + "disk_detect_zeroes": "unmap", + "memory": 2048, + "vnc_bind_address": "0.0.0.0" + } + ] +} +EOF +``` + +You can tweak the options a bit to match your situation. For debugging you can set `headless` to `false`. That will show you the vnc instead of running the `boot_command` in the background. For a `base` pacstrap using a 1.5G disk should be sufficient. The `raw` disk format is important. v86 does not read qcow2 images, only raw disk images. If your system does not support kvm (the default accelerator), you can change `"accelerator": "none"` to the settings, in macos you may use `"accelerator": "hvf"`. Other accelerator options can be found [here](https://www.packer.io/docs/builders/qemu.html#accelerator). + +After gaining SSH connectivity to the VM, packer will run the `scripts/provisioning.sh` script in the guest. + +### Creating the Archlinux installation script + +Create a script for your Archlinux installation. This runs in the ISO booted Archlinux environment, so you need to partition, pacstrap and install a bootloader. +```sh +mkdir -p packer/scripts +### Write your own or copy paste the example below +vim packer/scripts/provision.sh +``` + +An example script to install Archlinux with the root mounted using the 9p network filesystem: +```sh +#!/bin/bash +echo "Creating a GPT partition on /dev/sda1" +echo -e "g\nn\n\n\n\nw" | fdisk /dev/sda + +# In case you might want to create a DOS partition instead. It doesn't really matter. +#echo "Creating a DOS partition on /dev/sda1" +#echo -e "o\nn\np\n1\n\n\nw" | fdisk /dev/sda + +echo "Formatting /dev/sda1 to ext4" +mkfs -t ext4 /dev/sda1 + +echo "Mounting new filesystem" +mount -t ext4 /dev/sda1 /mnt + +echo "Create pacman package cache dir" +mkdir -p /mnt/var/cache/pacman/pkg + +# We don't want the pacman cache to fill up the image. After reboot whatever tarballs pacman has cached are gone. +echo "Mount the package cache dir in memory so it doesn't fill up the image" +mount -t tmpfs none /mnt/var/cache/pacman/pkg + +echo "Updating archlinux-keyring" +pacman -Sy archlinux-keyring --noconfirm + +# uncomment to remove signing if unable to resolve signing errors +sed -i 's/SigLevel.*/SigLevel = Never/g' /etc/pacman.conf + +# Install the Archlinux base system, feel free to add packages you need here +echo "Performing pacstrap" +pacstrap -i /mnt base linux dhcpcd curl openssh --noconfirm + +echo "Writing fstab" +genfstab -p /mnt >> /mnt/etc/fstab + +# When the Linux boots we want it to automatically log in on tty1 as root +echo "Ensuring root autologin on tty1" +mkdir -p /mnt/etc/systemd/system/getty@tty1.service.d +cat << 'EOF' > /mnt/etc/systemd/system/getty@tty1.service.d/override.conf +[Service] +ExecStart= +ExecStart=-/usr/bin/agetty --autologin root --noclear %I $TERM +EOF + +# This is the tricky part. The current root will be mounted on /dev/sda1 but after we reboot +# it will try to mount root during boot using the 9p network filesystem. This means the emulator +# will request all files over the network using XMLHttpRequests from the server. This is great +# because then you only need to provide the client with a saved state (the memory) and the +# session will start instantly and load needed files on the fly. This is fast and it saves bandwidth. +echo "Ensuring root is remounted using 9p after reboot" +mkdir -p /mnt/etc/initcpio/hooks +cat << 'EOF' > /mnt/etc/initcpio/hooks/9p_root +run_hook() { + mount_handler="mount_9p_root" +} + +mount_9p_root() { + msg ":: mounting '$root' on real root (9p)" + # Note the host9p. We won't mount /dev/sda1 on root anymore, + # instead we mount the network filesystem and the emulator will + # retrieve the files on the fly. + if ! mount -t 9p host9p "$1"; then + echo "You are now being dropped into an emergency shell." + launch_interactive_shell + msg "Trying to continue (this will most likely fail) ..." + fi +} +EOF + +echo "Adding initcpio build hook for 9p root remount" +mkdir -p /mnt/etc/initcpio/install +cat << 'EOF' > /mnt/etc/initcpio/install/9p_root +#!/bin/bash +build() { + add_runscript +} +EOF + +# We need to load some modules into the kernel for it to play nice with the emulator +# The atkbd and i8042 modules are for keyboard input in the browser. If you do not +# want to use the network filesystem you only need these. The 9p, 9pnet and 9pnet_virtio +# modules are needed for being able to mount 9p network filesystems using the emulator. +echo "Configure mkinitcpio for 9p" +sed -i 's/MODULES=()/MODULES=(atkbd i8042 libps2 serio serio_raw psmouse virtio_pci virtio_pci_modern_dev 9p 9pnet 9pnet_virtio fscache netfs)/g' /mnt/etc/mkinitcpio.conf + +# Because we want to mount the root filesystem over the network during boot, we need to +# hook into initcpio. If you do not want to mount the root filesystem during boot but +# only want to mount a 9p filesystem later, you can leave this out. Once the system +# has been booted you should be able to mount 9p filesystems with mount -t 9p host9p /blabla +# without this hook. +sed -i 's/fsck"/fsck 9p_root"/g' /mnt/etc/mkinitcpio.conf + +# enable ssh password auth and root login +sed -i 's/#PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config +sed -i 's/#PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config + +echo "Writing the installation script" +cat << 'EOF' > /mnt/bootstrap.sh +#!/usr/bin/bash +echo "Re-generate initial ramdisk environment" +mkinitcpio -p linux + +# uncomment to remove signing if you are unable to resolve signing errors otherwise +sed -i 's/SigLevel.*/SigLevel = Never/g' /etc/pacman.conf + +pacman -S --noconfirm syslinux gptfdisk +syslinux-install_update -i -a -m + +# disabling ldconfig to speed up boot (to remove Rebuild dynamic linker cache...) +# you may want to comment this out +echo "Disabling ldconfig service" +systemctl mask ldconfig.service + +sync +EOF + +echo "Chrooting and bootstrapping the installation" +arch-chroot /mnt bash bootstrap.sh + + +cat << 'EOF' > /mnt/boot/syslinux/syslinux.cfg +# Config file for Syslinux - +# /boot/syslinux/syslinux.cfg +# +# Comboot modules: +# * menu.c32 - provides a text menu +# * vesamenu.c32 - provides a graphical menu +# * chain.c32 - chainload MBRs, partition boot sectors, Windows bootloaders +# * hdt.c32 - hardware detection tool +# * reboot.c32 - reboots the system +# +# To Use: Copy the respective files from /usr/lib/syslinux to /boot/syslinux. +# If /usr and /boot are on the same file system, symlink the files instead +# of copying them. +# +# If you do not use a menu, a 'boot:' prompt will be shown and the system +# will boot automatically after 5 seconds. +# +# Please review the wiki: https://wiki.archlinux.org/index.php/Syslinux +# The wiki provides further configuration examples + +DEFAULT arch +PROMPT 0 # Set to 1 if you always want to display the boot: prompt +TIMEOUT 100 + +# Menu Configuration +# Either menu.c32 or vesamenu32.c32 must be copied to /boot/syslinux +UI menu.c32 +#UI vesamenu.c32 + +# Refer to http://syslinux.zytor.com/wiki/index.php/Doc/menu +MENU TITLE Arch Linux +#MENU BACKGROUND splash.png +MENU COLOR border 30;44 #40ffffff #a0000000 std +MENU COLOR title 1;36;44 #9033ccff #a0000000 std +MENU COLOR sel 7;37;40 #e0ffffff #20ffffff all +MENU COLOR unsel 37;44 #50ffffff #a0000000 std +MENU COLOR help 37;40 #c0ffffff #a0000000 std +MENU COLOR timeout_msg 37;40 #80ffffff #00000000 std +MENU COLOR timeout 1;37;40 #c0ffffff #00000000 std +MENU COLOR msg07 37;40 #90ffffff #a0000000 std +MENU COLOR tabmsg 31;40 #30ffffff #00000000 std + +# boot sections follow +# +# TIP: If you want a 1024x768 framebuffer, add "vga=773" to your kernel line. +# +#-* + +LABEL arch + MENU LABEL Arch Linux 9p + LINUX ../vmlinuz-linux + APPEND root=/dev/sda1 rw quiet + INITRD ../initramfs-linux.img + +LABEL arch2 + MENU LABEL Arch Linux Disk + LINUX ../vmlinuz-linux + APPEND root=/dev/sda1 rw quiet disablehooks=9p_root + INITRD ../initramfs-linux.img + +LABEL hdt + MENU LABEL HDT (Hardware Detection Tool) + COM32 hdt.c32 + +LABEL reboot + MENU LABEL Reboot + COM32 reboot.c32 + +LABEL poweroff + MENU LABEL Poweroff + COM32 poweroff.c32 +EOF +umount -R /mnt +``` + +With the packer template and the script you have enough to create an image that can be booted by v86. But because this example script installs an Archlinux that wants to mount root over the network with 9p, we need to host that filesystem first. If you do not want to use 9p, you can just run `(cd packer && packer build -force template.json)` to build the image. + +### Creating the 9p filesystem + +Now that we have an image that contains a filesystem, we can convert that filesystem into something we can host on the webserver together with the v86 library. + +To do so, we need to mount the image once and create a json mapping of the filesystem. The following script shows how to map the filesystem in an automated fashion. + +Create a script to builds the image and then creates v86 compatible artifacts: +```sh +vim build.sh +``` + +Example script: + +```sh +#!/bin/sh + +SRC=packer +TARGET=output + +# build the boxfile from the iso +(cd $SRC && sudo PACKER_LOG=1 PACKER_LOG_PATH="./packer.log" packer build -force template.json) + +# test if there is a boxfile where we expected it +if [ ! -f $SRC/output-qemu/archlinux ]; then + echo "Looks like something went wrong building the image, maybe try again?" + exit 1 +fi; + +# clean up any previous loops and mounts +echo "Making sure mountpoint is empty" +LOOP_DEV=$(sudo losetup -f) + +sudo umount diskmount -f || /bin/true +sudo kpartx -d $LOOP_DEV || /bin/true +sudo losetup -d $LOOP_DEV || /bin/true + +# mount the generated raw image, we do that so we can create +# a json mapping of it and copy it to host on the webserver +mkdir -p diskmount +echo "Mounting the created image so we can convert it to a p9 image" +sudo losetup $LOOP_DEV $SRC/output-qemu/archlinux +sudo kpartx -a $LOOP_DEV +sudo mount /dev/mapper/$(basename $LOOP_DEV)p1 diskmount + +# make images dir +mkdir -p $TARGET +mkdir -p $TARGET/images +mkdir -p $TARGET/images/arch + +# map the filesystem to json with fs2json +sudo ./tools/fs2json.py --out $TARGET/images/fs.json diskmount +sudo ./tools/copy-to-sha256.py diskmount $TARGET/images/arch + +# copy the filesystem and chown to nonroot user +echo "Copying the filesystem to $TARGET/arch" +mkdir $TARGET/arch -p +sudo rsync -q -av diskmount/ $TARGET/arch +sudo chown -R $(whoami):$(whoami) $TARGET/arch + +# clean up mount +echo "Cleaning up mounts" +sudo umount diskmount -f +sudo kpartx -d $LOOP_DEV +sudo losetup -d $LOOP_DEV + +# Move the image to the images dir +sudo mv $SRC/output-qemu/archlinux $TARGET/images/arch.img +``` + +Given that the packer template and provision.sh is rooted at `packer` (adjust the value of `$SRC` otherwise), run the `build.sh` at root of your `v86` repo: + +``` +chmod +x build.sh +./build.sh +``` + +Generated artifacts are now available for serving from `output`. + +### Using the created artifacts in v86 + +Now that we have everything we need to host a server that serves an Archlinux environment over the network. + +Create a checkout of v86 and run `make build/libv86.js`. +We can then edit `examples/arch.html`, we have two options: + +1. Boot Arch Linux from the 9p filesystem (generated .bin artifacts at `/output/images/arch`): + + ```sh + filesystem: { + baseurl: "../output/images/arch/", + basefs: "../output/images/fs.json", + }, + + bzimage_initrd_from_filesystem: true, + + cmdline: [ + "rw", + "root=host9p rootfstype=9p rootflags=trans=virtio,cache=loose", + ].join(" "), + + acpi: false, + autostart: true, + ``` +2. Boot the archlinux from the qemu raw disk image: + + ```sh + hda: { + url: "../output/images/arch.img", + # set to true if you want to load it asynchrously during runtime (for this option we need to run a webserver that supports the Range header) + # NOTE: async: false is slow but proved to be more realiable + async: false, + + # This needs to be the size of the raw disk. + size: 1.5 * 1024 * 1024 * 1024, + # See the `disk_size` item in the packer template. + }, + + acpi: false, + autostart: true, + ``` + +Next, we need a webserver that supports the Range header. For example [this extension of the SimpleHTTPServer](https://github.com/smgoller/rangehttpserver). At your `v86` root, run: + +```sh +wget https://raw.githubusercontent.com/smgoller/rangehttpserver/master/RangeHTTPServer.py +python2 RangeHTTPServer.py +``` + +Now that the webserver is running, point your browser to `http://localhost:8000/examples/arch.html`. Wait for the Linux to boot. When the system is up, click 'Save state to file'. Your browser will download a `v86state.bin` file. Copy that file to `/your/v86/dir/images`. You can then edit `examples/arch.html` again and add a 'state' key to the `V86Starter` array. + +```sh +initial_state: { + "url": "http://localhost:8000/images/v86state.bin", +}, +``` + +If you refresh `http://localhost:8000/examples/arch.html` you will see that the state is restored instantly and all required files are loaded over the network on the fly. + +### Networking + +The emulator can emulate a network card. For more information [look at the networking documentation](https://github.com/copy/v86/blob/master/docs/networking.md). To set up networking in the VM, add the following item to the `V86Starter` array in the `examples/arch.html` file: +```sh +network_relay_url: "ws://localhost:8080/", +``` + +This will make the emulator try to connect to a [WebSockets proxy](https://github.com/benjamincburns/websockproxy). Running the proxy is very easy if you use the Docker container. + +```sh +sudo docker run --privileged -p 8080:80 --name relay bennottelling/websockproxy +``` +**NOTE:** original `benjamincburns/jor1k-relay:latest` has throttling built-in by default which will degrade the networking. `bennottelling/websockproxy` has this throttling removed via [websockproxy/issues/4#issuecomment-317255890](https://github.com/benjamincburns/websockproxy/issues/4#issuecomment-317255890). + +You can check if the relay is running correctly by going to `http://localhost:8080/` in your browser. There you should see a message that reads `Can "Upgrade" only to "Websocket".`. + +Now you should be able to get network connectivity in the virtual machine. If you are restoring from a saved state, you might need to first run: +```sh +ip link set enp0s5 down +rmmod ne2k-pci +``` + +To bring the network up, run: +```sh +modprobe ne2k-pci +dhcpcd -w4 enp0s5 +``` + +It might take a while for a carrier to become available on the interface. If the `dhcpcd` command fails shortly after booting, wait a bit and try again a bit later. If you are using the 9p network filesystem you can use the developer tools networking tab (in chrome) to get a sense of what is going on by looking at the files that are being downloaded. + +When the network is up you should be able to curl a website. To check, run `curl icanhazip.com`. There you should see the public IP of the machine running the proxy. + +You can't do inbound traffic into the VM with the websockproxy Docker container because it uses a basic NAT. To SSH into the VM running in the browser, you can create a reverse SSH tunnel to expose the SSH port of the sshd in the VM to the outside world. You may need to start `sshd` first, it may also be reasonable to change root password: + +```sh +passwd root +systemctl start sshd +``` + +then create a reverse SSH tunnel: + +```sh +# This will create a port 1122 on the example.com server +# which forwards to the SSH in the VM +ssh root@example.com -R 1122:localhost:22 +``` + +Now on the `example.com` server you should be able to SSH into your browser tab by running `ssh root@localhost -p 1122`. diff --git a/docs/filesystem.md b/docs/filesystem.md new file mode 100644 index 0000000..caf6362 --- /dev/null +++ b/docs/filesystem.md @@ -0,0 +1,27 @@ +A 9p filesystem is supported by the emulator, using a virtio transport. Using +it, files can be exchanged with the guest OS, see +[`create_file`](/src/browser/starter.js#L1179-L1199) +and +[`read_file`](/src/browser/starter.js#L1209-L1228). It can +be enabled by passing the following options to `V86Starter`: + +```javascript +filesystem: { + basefs: "../9p/fs.json", + baseurl: "../9p/base/", +} +``` + +Here, `basefs` is a json file created using +[fs2json](https://github.com/copy/fs2json). The base url is the prefix of a url +from which the files are available. For instance, if the 9p filesystem has a +file `/bin/sh`, that file must be accessible from +`http://localhost/9p/base/bin/sh`. If `basefs` and `baseurl` are omitted, an +empty 9p filesystem is created. + +The `mount_tag` of the 9p device is `host9p`. In order to mount it in the +guest, use: + +```sh +mount -t 9p host9p /mnt/9p/ +``` diff --git a/docs/linux-9p-image.md b/docs/linux-9p-image.md new file mode 100644 index 0000000..29467d2 --- /dev/null +++ b/docs/linux-9p-image.md @@ -0,0 +1,58 @@ +In order to create a Linux image that can mount the 9p file system, use add the following lines to the kernel config: + +``` +CONFIG_NET_9P=y +CONFIG_NET_9P_VIRTIO=y +CONFIG_NET_9P_DEBUG=y +CONFIG_VIRTIO=y +CONFIG_VIRTIO_PCI=y +CONFIG_9P_FS=y +CONFIG_9P_FSCACHE=y +CONFIG_9P_FS_POSIX_ACL=y +``` + +A Dockerfile for this build is here: https://github.com/ysangkok/build-v86-9p-linux + +Using initcpio +-------------- + +This allows you to remount the root file system using 9p. No changes are necessary if you only want to mount a 9p filesystem after booting. + +Add the following files: + +`/etc/initcpio/hooks/9p_root` + +```bash +#!/usr/bin/bash + +run_hook() { + mount_handler="mount_9p_root" +} + +mount_9p_root() { + msg ":: mounting '$root' on real root (9p)" + if ! mount -t 9p host9p "$1"; then + echo "You are now being dropped into an emergency shell." + launch_interactive_shell + msg "Trying to continue (this will most likely fail) ..." + fi +} +``` + +
+ +`/etc/initcpio/install/9p_root` + +```bash +#!/bin/bash +build() { + add_runscript +} +``` + +Change the following options in `/etc/mkinitcpio.conf`: + +```bash +MODULES="virtio_pci 9p 9pnet 9pnet_virtio" +HOOKS="base udev autodetect modconf block filesystems keyboard fsck 9p_root" # appended 9p_root +``` diff --git a/docs/networking.md b/docs/networking.md new file mode 100644 index 0000000..953b22e --- /dev/null +++ b/docs/networking.md @@ -0,0 +1,15 @@ +Emulating a network card is supported. It can be used by passing the +`network_relay_url` option to `V86Starter`. The url must point to a running +WebSockets Proxy. The source code for WebSockets Proxy can be found at +https://github.com/benjamincburns/websockproxy. + +The network card could also be controlled programatically, but this is +currently not exposed. + +There is no built-in support for NodeJS, but networking only depends on a +browser-compatible `WebSocket` constructor being present in the global scope. + +**NOTE:** original `benjamincburns/jor1k-relay:latest` docker image has +throttling built-in by default which will degrade the networking. +`bellenottelling/websockproxy`docker image has this throttling removed via +[websockproxy/issues/4#issuecomment-317255890](https://github.com/benjamincburns/websockproxy/issues/4#issuecomment-317255890). diff --git a/docs/sse-shifts.txt b/docs/sse-shifts.txt new file mode 100644 index 0000000..7fb5b2c --- /dev/null +++ b/docs/sse-shifts.txt @@ -0,0 +1,39 @@ + 0F F1 PSLLW mm mm/m64 mmx Shift Packed Data Left Logical +66 0F F1 PSLLW xmm xmm/m128 sse2 Shift Packed Data Left Logical + 0F F2 PSLLD mm mm/m64 mmx Shift Packed Data Left Logical +66 0F F2 PSLLD xmm xmm/m128 sse2 Shift Packed Data Left Logical + 0F F3 PSLLQ mm mm/m64 mmx Shift Packed Data Left Logical +66 0F F3 PSLLQ xmm xmm/m128 sse2 Shift Packed Data Left Logical + + 0F E1 PSRAW mm mm/m64 mmx Shift Packed Data Right Arithmetic +66 0F E1 PSRAW xmm xmm/m128 sse2 Shift Packed Data Right Arithmetic + 0F E2 PSRAD mm mm/m64 mmx Shift Packed Data Right Arithmetic +66 0F E2 PSRAD xmm xmm/m128 sse2 Shift Packed Data Right Arithmetic + + 0F D1 PSRLW mm mm/m64 mmx Shift Packed Data Right Logical +66 0F D1 PSRLW xmm xmm/m128 sse2 Shift Packed Data Right Logical + 0F D2 PSRLD mm mm/m64 mmx Shift Packed Data Right Logical +66 0F D2 PSRLD xmm xmm/m128 sse2 Shift Packed Data Right Logical + 0F D3 PSRLQ mm mm/m64 mmx Shift Packed Data Right Logical +66 0F D3 PSRLQ xmm xmm/m128 sse2 Shift Packed Data Right Logical + + 0F 71 PSRLW mm imm8 mmx Shift Packed Data Right Logical +66 0F 71 PSRLW xmm imm8 sse2 Shift Packed Data Right Logical + 0F 71 PSRAW mm imm8 mmx Shift Packed Data Right Arithmetic +66 0F 71 PSRAW xmm imm8 sse2 Shift Packed Data Right Arithmetic + 0F 71 PSLLW mm imm8 mmx Shift Packed Data Left Logical +66 0F 71 PSLLW xmm imm8 sse2 Shift Packed Data Left Logical + + 0F 72 PSRLD mm imm8 mmx Shift Double Quadword Right Logical +66 0F 72 PSRLD xmm imm8 sse2 Shift Double Quadword Right Logical + 0F 72 PSRAD mm imm8 mmx Shift Packed Data Right Arithmetic +66 0F 72 PSRAD xmm imm8 sse2 Shift Packed Data Right Arithmetic + 0F 72 PSLLD mm imm8 mmx Shift Packed Data Left Logical +66 0F 72 PSLLD xmm imm8 sse2 Shift Packed Data Left Logical + + 0F 73 PSRLQ mm imm8 mmx Shift Packed Data Right Logical +66 0F 73 PSRLQ xmm imm8 sse2 Shift Packed Data Right Logical +66 0F 73 PSRLDQ xmm imm8 sse2 Shift Double Quadword Right Logical + 0F 73 PSLLQ mm imm8 mmx Shift Packed Data Left Logical +66 0F 73 PSLLQ xmm imm8 sse2 Shift Packed Data Left Logical +66 0F 73 PSLLDQ xmm imm8 sse2 Shift Double Quadword Left Logical diff --git a/docs/windows-xp.md b/docs/windows-xp.md new file mode 100644 index 0000000..40771fa --- /dev/null +++ b/docs/windows-xp.md @@ -0,0 +1,75 @@ +*Most of this document also applies to Windows 2000.* + +You can download Windows 2000 from [WinWorld](https://winworldpc.com/download/413638c2-8d18-c39a-11c3-a4e284a2c3a5). + +Use QEMU to create `winxp.img`: + +``` +qemu-img create winxp.img 2G +qemu-system-x86_64 -m 512 -drive file=winxp.img,format=raw -cdrom en_windows_xp_professional_with_service_pack_3_x86_cd_vl_x14-73974.iso +``` + +Follow setup instructions. + +The next step fixes `Uncaught RangeError: Maximum call stack size exceeded` in Chrome during Windows 2000/XP boot in v86. + +After installation change computer type to "Standard PC" as described [here](http://web.archive.org/web/20220528021535/https://www.scm-pc-card.de/file/manual/FAQ/acpi_uninstallation_windows_xp_english.pdf): +Start > RightClick "My Computer" > Manage > +Device Manager > Computer > RightClick "ACPI Uniprocessor PC" > Update Driver... > +No, not this time > Next > Install from a list or specific location (Advanced) > Next > +Don't search. I will choose the driver to install. > Next > Standard PC > Next > Finish. +Restart the VM, follow multiple "Found New Hardware Wizard" dialogs with default options. + +Now `winxp.img` is ready for v86. You can use [the website](https://copy.sh/v86/) to run it: +Specify `winxp.img` as a hard drive and optionally set memory size to 512 MB. +Or run it in a custom html file as described below. + +Get seabios.bin and vgabios.bin from [here](https://github.com/copy/v86/tree/master/bios), +get libv86.js and v86.wasm from [releases](https://github.com/copy/v86/releases/tag/latest). +Create `winxp.htm` with this content (assuming all the files are in the same folder): + +```html + + + + + +
+
+ +
+``` + +To open this html file locally a HTTP server is needed. The standard Python server `python -m http.server` doesn't support HTTP range requests. +You can use [http-server](https://www.npmjs.com/package/http-server) or [devd](https://github.com/cortesi/devd). +Start the server (from the same folder as `winxp.htm`): +``` +npx http-server +``` +Open http://localhost:8080/winxp.htm in the browser. + +Windows XP load time (until start button becomes responsive) in Chromium on my computer: +* 3 min second time +* 4 min (first time or if cache is disabled) +* 12 min second time if Network tab in Developer Tools is open +* 17 min (first time or if cache is disabled) and Network tab in Developer Tools is open + +Sometimes Windows XP hangs after boot (before it is interactive) in v86, +displaying only desktop wallpaper without taskbar or desktop icons. diff --git a/examples/arch.html b/examples/arch.html new file mode 100644 index 0000000..fc618dd --- /dev/null +++ b/examples/arch.html @@ -0,0 +1,78 @@ + +Archlinux + + + + + +Restore from file: +
+ + +
+
+ +
diff --git a/examples/async_load.html b/examples/async_load.html new file mode 100644 index 0000000..3440fa2 --- /dev/null +++ b/examples/async_load.html @@ -0,0 +1,43 @@ + +Asynchronous loading of disk images + + + + +
+
+ +
diff --git a/examples/basic.html b/examples/basic.html new file mode 100644 index 0000000..9c3e92b --- /dev/null +++ b/examples/basic.html @@ -0,0 +1,33 @@ + +Basic Emulator + + + + + +
+
+ +
diff --git a/examples/debian.html b/examples/debian.html new file mode 100644 index 0000000..877550d --- /dev/null +++ b/examples/debian.html @@ -0,0 +1,26 @@ + +Debian + + + + + +
+
+ +
diff --git a/examples/destroy.html b/examples/destroy.html new file mode 100644 index 0000000..c9e3f51 --- /dev/null +++ b/examples/destroy.html @@ -0,0 +1,34 @@ + +Destroyable Emulator + + + + +
+
+ +
diff --git a/examples/lang.html b/examples/lang.html new file mode 100644 index 0000000..4f6da15 --- /dev/null +++ b/examples/lang.html @@ -0,0 +1,77 @@ + +Basic Emulator + + + + +
 
+ + +
+
+ +
+ +
+ +

diff --git a/examples/lua.html b/examples/lua.html
new file mode 100644
index 0000000..a08dc59
--- /dev/null
+++ b/examples/lua.html
@@ -0,0 +1,121 @@
+
+Lua interpreter
+
+
+
+
+
+
+
+
+
Wait for boot ...
+

+
+
+ +
+
+ +
diff --git a/examples/nodejs.js b/examples/nodejs.js new file mode 100755 index 0000000..2cfdfff --- /dev/null +++ b/examples/nodejs.js @@ -0,0 +1,47 @@ +#!/usr/bin/env node +"use strict"; + +var fs = require("fs"); +var V86Starter = require("../build/libv86.js").V86Starter; + +function readfile(path) +{ + return new Uint8Array(fs.readFileSync(path)).buffer; +} + +var bios = readfile(__dirname + "/../bios/seabios.bin"); +var linux = readfile(__dirname + "/../images/linux4.iso"); + +process.stdin.setRawMode(true); +process.stdin.resume(); +process.stdin.setEncoding("utf8"); + +console.log("Now booting, please stand by ..."); + +var emulator = new V86Starter({ + bios: { buffer: bios }, + cdrom: { buffer: linux }, + autostart: true, +}); + +emulator.add_listener("serial0-output-char", function(chr) +{ + if(chr <= "~") + { + process.stdout.write(chr); + } +}); + +process.stdin.on("data", function(c) +{ + if(c === "\u0003") + { + // ctrl c + emulator.stop(); + process.stdin.pause(); + } + else + { + emulator.serial0_send(c); + } +}); diff --git a/examples/nodejs_state.js b/examples/nodejs_state.js new file mode 100755 index 0000000..5dab840 --- /dev/null +++ b/examples/nodejs_state.js @@ -0,0 +1,66 @@ +#!/usr/bin/env node +"use strict"; + +var fs = require("fs"); +var V86Starter = require("../build/libv86.js").V86Starter; + +function readfile(path) +{ + return new Uint8Array(fs.readFileSync(path)).buffer; +} + +console.log("Use F2 to save the state and F3 to restore."); + +var bios = readfile(__dirname + "/../bios/seabios.bin"); +var linux = readfile(__dirname + "/../images/linux4.iso"); + +process.stdin.setRawMode(true); +process.stdin.resume(); +process.stdin.setEncoding("utf8"); + +console.log("Now booting, please stand by ..."); + +var emulator = new V86Starter({ + bios: { buffer: bios }, + cdrom: { buffer: linux }, + autostart: true, +}); + +emulator.add_listener("serial0-output-char", function(chr) +{ + if(chr <= "~") + { + process.stdout.write(chr); + } +}); + +var state; + +process.stdin.on("data", async function(c) +{ + if(c === "\u0003") + { + // ctrl c + emulator.stop(); + process.stdin.pause(); + } + else if(c === "\x1b\x4f\x51") + { + // f2 + state = await emulator.save_state(); + console.log("--- Saved ---"); + } + else if(c === "\x1b\x4f\x52") + { + // f3 + if(state) + { + console.log("--- Restored ---"); + await emulator.restore_state(state); + } + } + else + { + emulator.serial0_send(c); + } +}); diff --git a/examples/save_restore.html b/examples/save_restore.html new file mode 100644 index 0000000..bbf132f --- /dev/null +++ b/examples/save_restore.html @@ -0,0 +1,94 @@ + +Save and restore + + + + + + +Restore from file: +
+ + +
+
+ +
diff --git a/examples/serial.html b/examples/serial.html new file mode 100644 index 0000000..31ef4ad --- /dev/null +++ b/examples/serial.html @@ -0,0 +1,87 @@ + +Serial example + + + + + + + + +
+
+ +
diff --git a/examples/two_instances.html b/examples/two_instances.html new file mode 100644 index 0000000..1af82e3 --- /dev/null +++ b/examples/two_instances.html @@ -0,0 +1,88 @@ + +Two emulators + + + + +Click on a screen to control it.
+ +
+
+ +
+ +
+
+ +
diff --git a/examples/worker.html b/examples/worker.html new file mode 100644 index 0000000..665d3c7 --- /dev/null +++ b/examples/worker.html @@ -0,0 +1,34 @@ + +Worker + + + +s +
+ + diff --git a/examples/worker.js b/examples/worker.js new file mode 100644 index 0000000..5026848 --- /dev/null +++ b/examples/worker.js @@ -0,0 +1,29 @@ +importScripts("../build/libv86.js"); + +var emulator = new V86Starter({ + wasm_path: "../build/v86.wasm", + memory_size: 32 * 1024 * 1024, + vga_memory_size: 2 * 1024 * 1024, + bios: { + url: "../bios/seabios.bin", + }, + vga_bios: { + url: "../bios/vgabios.bin", + }, + cdrom: { + url: "../images/linux4.iso", + }, + autostart: true, +}); + + +emulator.add_listener("serial0-output-char", function(chr) +{ + this.postMessage(chr); +}.bind(this)); + +this.onmessage = function(e) +{ + emulator.serial0_send(e.data); +}; + diff --git a/gen/generate_analyzer.js b/gen/generate_analyzer.js new file mode 100755 index 0000000..15d8757 --- /dev/null +++ b/gen/generate_analyzer.js @@ -0,0 +1,486 @@ +#!/usr/bin/env node +"use strict"; + +const assert = require("assert").strict; +const fs = require("fs"); +const path = require("path"); +const x86_table = require("./x86_table"); +const rust_ast = require("./rust_ast"); +const { hex, mkdirpSync, get_switch_value, get_switch_exist, finalize_table_rust } = require("./util"); + +const OUT_DIR = path.join(__dirname, "..", "src/rust/gen/"); + +mkdirpSync(OUT_DIR); + +const table_arg = get_switch_value("--table"); +const gen_all = get_switch_exist("--all"); +const to_generate = { + analyzer: gen_all || table_arg === "analyzer", + analyzer0f: gen_all || table_arg === "analyzer0f", +}; + +assert( + Object.keys(to_generate).some(k => to_generate[k]), + "Pass --table [analyzer|analyzer0f] or --all to pick which tables to generate" +); + +gen_table(); + +function gen_read_imm_call(op, size_variant) +{ + let size = (op.os || op.opcode % 2 === 1) ? size_variant : 8; + + if(op.imm8 || op.imm8s || op.imm16 || op.imm1632 || op.imm32 || op.immaddr) + { + if(op.imm8) + { + return "cpu.read_imm8()"; + } + else if(op.imm8s) + { + return "cpu.read_imm8s()"; + } + else + { + if(op.immaddr) + { + // immaddr: depends on address size + return "cpu.read_moffs()"; + } + else + { + assert(op.imm1632 || op.imm16 || op.imm32); + + if(op.imm1632 && size === 16 || op.imm16) + { + return "cpu.read_imm16()"; + } + else + { + assert(op.imm1632 && size === 32 || op.imm32); + return "cpu.read_imm32()"; + } + } + } + } + else + { + return undefined; + } +} + +function gen_call(name, args) +{ + args = args || []; + return `${name}(${args.join(", ")});`; +} + +/* + * Current naming scheme: + * instr(16|32|)_(66|F2|F3)?0F?[0-9a-f]{2}(_[0-7])?(_mem|_reg|) + */ +function make_instruction_name(encoding, size) +{ + const suffix = encoding.os ? String(size) : ""; + const opcode_hex = hex(encoding.opcode & 0xFF, 2); + const first_prefix = (encoding.opcode & 0xFF00) === 0 ? "" : hex(encoding.opcode >> 8 & 0xFF, 2); + const second_prefix = (encoding.opcode & 0xFF0000) === 0 ? "" : hex(encoding.opcode >> 16 & 0xFF, 2); + const fixed_g_suffix = encoding.fixed_g === undefined ? "" : `_${encoding.fixed_g}`; + + assert(first_prefix === "" || first_prefix === "0F" || first_prefix === "F2" || first_prefix === "F3"); + assert(second_prefix === "" || second_prefix === "66" || second_prefix === "F2" || second_prefix === "F3"); + + return `instr${suffix}_${second_prefix}${first_prefix}${opcode_hex}${fixed_g_suffix}`; +} + +function gen_instruction_body(encodings, size) +{ + const encoding = encodings[0]; + + let has_66 = []; + let has_F2 = []; + let has_F3 = []; + let no_prefix = []; + + for(let e of encodings) + { + if((e.opcode >>> 16) === 0x66) has_66.push(e); + else if((e.opcode >>> 8 & 0xFF) === 0xF2 || (e.opcode >>> 16) === 0xF2) has_F2.push(e); + else if((e.opcode >>> 8 & 0xFF) === 0xF3 || (e.opcode >>> 16) === 0xF3) has_F3.push(e); + else no_prefix.push(e); + } + + if(has_F2.length || has_F3.length) + { + assert((encoding.opcode & 0xFF0000) === 0 || (encoding.opcode & 0xFF00) === 0x0F00); + } + + if(has_66.length) + { + assert((encoding.opcode & 0xFF00) === 0x0F00); + } + + const code = []; + + if(encoding.e) + { + code.push("let modrm_byte = cpu.read_imm8();"); + } + + if(has_66.length || has_F2.length || has_F3.length) + { + const if_blocks = []; + + if(has_66.length) { + const body = gen_instruction_body_after_prefix(has_66, size); + if_blocks.push({ condition: "cpu.prefixes & ::prefix::PREFIX_66 != 0", body, }); + } + if(has_F2.length) { + const body = gen_instruction_body_after_prefix(has_F2, size); + if_blocks.push({ condition: "cpu.prefixes & ::prefix::PREFIX_F2 != 0", body, }); + } + if(has_F3.length) { + const body = gen_instruction_body_after_prefix(has_F3, size); + if_blocks.push({ condition: "cpu.prefixes & ::prefix::PREFIX_F3 != 0", body, }); + } + + const else_block = { + body: gen_instruction_body_after_prefix(no_prefix, size), + }; + + return [].concat( + code, + { + type: "if-else", + if_blocks, + else_block, + } + ); + } + else { + return [].concat( + code, + gen_instruction_body_after_prefix(encodings, size) + ); + } +} + +function gen_instruction_body_after_prefix(encodings, size) +{ + const encoding = encodings[0]; + + if(encoding.fixed_g !== undefined) + { + assert(encoding.e); + + // instruction with modrm byte where the middle 3 bits encode the instruction + + // group by opcode without prefix plus middle bits of modrm byte + let cases = encodings.reduce((cases_by_opcode, case_) => { + assert(typeof case_.fixed_g === "number"); + cases_by_opcode[case_.opcode & 0xFFFF | case_.fixed_g << 16] = case_; + return cases_by_opcode; + }, Object.create(null)); + cases = Object.values(cases).sort((e1, e2) => e1.fixed_g - e2.fixed_g); + + return [ + { + type: "switch", + condition: "modrm_byte >> 3 & 7", + cases: cases.map(case_ => { + const fixed_g = case_.fixed_g; + const body = gen_instruction_body_after_fixed_g(case_, size); + + return { + conditions: [fixed_g], + body, + }; + }), + + default_case: { + body: [ + "analysis.ty = ::analysis::AnalysisType::BlockBoundary;", + "analysis.no_next_instruction = true;", + ], + } + }, + ]; + } + else { + assert(encodings.length === 1); + return gen_instruction_body_after_fixed_g(encodings[0], size); + } +} + +function gen_instruction_body_after_fixed_g(encoding, size) +{ + const imm_read = gen_read_imm_call(encoding, size); + const instruction_postfix = []; + + if(encoding.custom_sti) { + instruction_postfix.push("analysis.ty = ::analysis::AnalysisType::STI;"); + } + else if( + encoding.block_boundary && + // jump_offset_imm: Is a block boundary, but gets a different type (Jump) below + !encoding.jump_offset_imm || (!encoding.custom && encoding.e)) + { + instruction_postfix.push("analysis.ty = ::analysis::AnalysisType::BlockBoundary;"); + } + + if(encoding.no_next_instruction) + { + instruction_postfix.push("analysis.no_next_instruction = true;"); + } + if(encoding.absolute_jump) + { + instruction_postfix.push("analysis.absolute_jump = true;"); + } + + if(encoding.prefix) + { + const instruction_name = "::analysis::" + make_instruction_name(encoding, size) + "_analyze"; + const args = ["cpu", "analysis"]; + + assert(!imm_read); + + return [].concat( + gen_call(instruction_name, args), + instruction_postfix + ); + } + else if(encoding.e) + { + // instruction with modrm byte where the middle 3 bits encode a register + + const reg_postfix = []; + const mem_postfix = []; + + if(encoding.mem_ud) + { + mem_postfix.push( + "analysis.ty = ::analysis::AnalysisType::BlockBoundary;" + ); + } + + if(encoding.reg_ud) + { + reg_postfix.push( + "analysis.ty = ::analysis::AnalysisType::BlockBoundary;" + ); + } + + if(encoding.ignore_mod) + { + assert(!imm_read, "Unexpected instruction (ignore mod with immediate value)"); + + // Has modrm byte, but the 2 mod bits are ignored and both + // operands are always registers (0f20-0f24) + + return instruction_postfix; + } + else + { + return [].concat( + { + type: "if-else", + if_blocks: [{ + condition: "modrm_byte < 0xC0", + body: [].concat( + gen_call("::analysis::modrm_analyze", ["cpu", "modrm_byte"]), + mem_postfix, + ), + }], + else_block: { + body: reg_postfix, + }, + }, + imm_read ? [imm_read + ";"] : [], + instruction_postfix + ); + } + } + else + { + // instruction without modrm byte or prefix + + const body = []; + + if(imm_read) + { + if(encoding.jump_offset_imm) + { + body.push("let jump_offset = " + imm_read + ";"); + + if(encoding.conditional_jump) + { + assert( + (encoding.opcode & ~0xF) === 0x70 || + (encoding.opcode & ~0xF) === 0x0F80 || + (encoding.opcode & ~0x3) === 0xE0 + ); + const condition_index = encoding.opcode & 0xFF; + body.push(`analysis.ty = ::analysis::AnalysisType::Jump { offset: jump_offset as i32, condition: Some(0x${hex(condition_index, 2)}), is_32: cpu.osize_32() };`); + } + else + { + body.push(`analysis.ty = ::analysis::AnalysisType::Jump { offset: jump_offset as i32, condition: None, is_32: cpu.osize_32() };`); + } + } + else + { + body.push(imm_read + ";"); + } + } + + if(encoding.extra_imm16) + { + assert(imm_read); + body.push(gen_call("cpu.read_imm16")); + } + else if(encoding.extra_imm8) + { + assert(imm_read); + body.push(gen_call("cpu.read_imm8")); + } + + return [].concat( + body, + instruction_postfix + ); + } +} + +function gen_table() +{ + let by_opcode = Object.create(null); + let by_opcode0f = Object.create(null); + + for(let o of x86_table) + { + let opcode = o.opcode; + + if((opcode & 0xFF00) === 0x0F00) + { + opcode &= 0xFF; + by_opcode0f[opcode] = by_opcode0f[opcode] || []; + by_opcode0f[opcode].push(o); + } + else + { + opcode &= 0xFF; + by_opcode[opcode] = by_opcode[opcode] || []; + by_opcode[opcode].push(o); + } + } + + let cases = []; + for(let opcode = 0; opcode < 0x100; opcode++) + { + let encoding = by_opcode[opcode]; + assert(encoding && encoding.length); + + let opcode_hex = hex(opcode, 2); + let opcode_high_hex = hex(opcode | 0x100, 2); + + if(encoding[0].os) + { + cases.push({ + conditions: [`0x${opcode_hex}`], + body: gen_instruction_body(encoding, 16), + }); + cases.push({ + conditions: [`0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, 32), + }); + } + else + { + cases.push({ + conditions: [`0x${opcode_hex}`, `0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, undefined), + }); + } + } + const table = { + type: "switch", + condition: "opcode", + cases, + default_case: { + body: ["dbg_assert!(false);"] + }, + }; + + if(to_generate.analyzer) + { + const code = [ + "#[cfg_attr(rustfmt, rustfmt_skip)]", + "pub fn analyzer(opcode: u32, cpu: &mut ::cpu_context::CpuContext, analysis: &mut ::analysis::Analysis) {", + table, + "}", + ]; + + finalize_table_rust( + OUT_DIR, + "analyzer.rs", + rust_ast.print_syntax_tree([].concat(code)).join("\n") + "\n" + ); + } + + const cases0f = []; + for(let opcode = 0; opcode < 0x100; opcode++) + { + let encoding = by_opcode0f[opcode]; + + assert(encoding && encoding.length); + + let opcode_hex = hex(opcode, 2); + let opcode_high_hex = hex(opcode | 0x100, 2); + + if(encoding[0].os) + { + cases0f.push({ + conditions: [`0x${opcode_hex}`], + body: gen_instruction_body(encoding, 16), + }); + cases0f.push({ + conditions: [`0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, 32), + }); + } + else + { + let block = { + conditions: [`0x${opcode_hex}`, `0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, undefined), + }; + cases0f.push(block); + } + } + + const table0f = { + type: "switch", + condition: "opcode", + cases: cases0f, + default_case: { + body: ["dbg_assert!(false);"] + }, + }; + + if(to_generate.analyzer0f) + { + const code = [ + "#![allow(unused)]", + "#[cfg_attr(rustfmt, rustfmt_skip)]", + "pub fn analyzer(opcode: u32, cpu: &mut ::cpu_context::CpuContext, analysis: &mut ::analysis::Analysis) {", + table0f, + "}" + ]; + + finalize_table_rust( + OUT_DIR, + "analyzer0f.rs", + rust_ast.print_syntax_tree([].concat(code)).join("\n") + "\n" + ); + } +} diff --git a/gen/generate_interpreter.js b/gen/generate_interpreter.js new file mode 100755 index 0000000..1ac5338 --- /dev/null +++ b/gen/generate_interpreter.js @@ -0,0 +1,492 @@ +#!/usr/bin/env node +"use strict"; + +const assert = require("assert").strict; +const fs = require("fs"); +const path = require("path"); +const x86_table = require("./x86_table"); +const rust_ast = require("./rust_ast"); +const { hex, mkdirpSync, get_switch_value, get_switch_exist, finalize_table_rust } = require("./util"); + +const OUT_DIR = path.join(__dirname, "..", "src/rust/gen/"); + +mkdirpSync(OUT_DIR); + +const table_arg = get_switch_value("--table"); +const gen_all = get_switch_exist("--all"); +const to_generate = { + interpreter: gen_all || table_arg === "interpreter", + interpreter0f: gen_all || table_arg === "interpreter0f", +}; + +assert( + Object.keys(to_generate).some(k => to_generate[k]), + "Pass --table [interpreter|interpreter0f] or --all to pick which tables to generate" +); + +gen_table(); + +function wrap_imm_call(imm) +{ + return `match ${imm} { Ok(o) => o, Err(()) => return }`; +} + +function gen_read_imm_call(op, size_variant) +{ + let size = (op.os || op.opcode % 2 === 1) ? size_variant : 8; + + if(op.imm8 || op.imm8s || op.imm16 || op.imm1632 || op.imm32 || op.immaddr) + { + if(op.imm8) + { + return wrap_imm_call("read_imm8()"); + } + else if(op.imm8s) + { + return wrap_imm_call("read_imm8s()"); + } + else + { + if(op.immaddr) + { + // immaddr: depends on address size + return wrap_imm_call("read_moffs()"); + } + else + { + assert(op.imm1632 || op.imm16 || op.imm32); + + if(op.imm1632 && size === 16 || op.imm16) + { + return wrap_imm_call("read_imm16()"); + } + else + { + assert(op.imm1632 && size === 32 || op.imm32); + return wrap_imm_call("read_imm32s()"); + } + } + } + } + else + { + return undefined; + } +} + +function gen_call(name, args) +{ + args = args || []; + return `${name}(${args.join(", ")});`; +} + +/* + * Current naming scheme: + * instr(16|32|)_(66|F2|F3)?0F?[0-9a-f]{2}(_[0-7])?(_mem|_reg|) + */ +function make_instruction_name(encoding, size) +{ + const suffix = encoding.os ? String(size) : ""; + const opcode_hex = hex(encoding.opcode & 0xFF, 2); + const first_prefix = (encoding.opcode & 0xFF00) === 0 ? "" : hex(encoding.opcode >> 8 & 0xFF, 2); + const second_prefix = (encoding.opcode & 0xFF0000) === 0 ? "" : hex(encoding.opcode >> 16 & 0xFF, 2); + const fixed_g_suffix = encoding.fixed_g === undefined ? "" : `_${encoding.fixed_g}`; + const module = first_prefix === "0F" || second_prefix === "0F" ? "instructions_0f" : "instructions"; + + assert(first_prefix === "" || first_prefix === "0F" || first_prefix === "F2" || first_prefix === "F3"); + assert(second_prefix === "" || second_prefix === "66" || second_prefix === "F2" || second_prefix === "F3"); + + return `${module}::instr${suffix}_${second_prefix}${first_prefix}${opcode_hex}${fixed_g_suffix}`; +} + +function gen_instruction_body(encodings, size) +{ + const encoding = encodings[0]; + + let has_66 = []; + let has_F2 = []; + let has_F3 = []; + let no_prefix = []; + + for(let e of encodings) + { + if((e.opcode >>> 16) === 0x66) has_66.push(e); + else if((e.opcode >>> 8 & 0xFF) === 0xF2 || (e.opcode >>> 16) === 0xF2) has_F2.push(e); + else if((e.opcode >>> 8 & 0xFF) === 0xF3 || (e.opcode >>> 16) === 0xF3) has_F3.push(e); + else no_prefix.push(e); + } + + if(has_F2.length || has_F3.length) + { + assert((encoding.opcode & 0xFF0000) === 0 || (encoding.opcode & 0xFF00) === 0x0F00); + } + + if(has_66.length) + { + assert((encoding.opcode & 0xFF00) === 0x0F00); + } + + const code = []; + + if(encoding.e) + { + code.push(`let modrm_byte = ${wrap_imm_call("read_imm8()")};`); + } + + if(has_66.length || has_F2.length || has_F3.length) + { + const if_blocks = []; + + if(has_66.length) { + const body = gen_instruction_body_after_prefix(has_66, size); + if_blocks.push({ condition: "prefixes_ & PREFIX_66 != 0", body, }); + } + if(has_F2.length) { + const body = gen_instruction_body_after_prefix(has_F2, size); + if_blocks.push({ condition: "prefixes_ & PREFIX_F2 != 0", body, }); + } + if(has_F3.length) { + const body = gen_instruction_body_after_prefix(has_F3, size); + if_blocks.push({ condition: "prefixes_ & PREFIX_F3 != 0", body, }); + } + + const check_prefixes = encoding.sse ? "(PREFIX_66 | PREFIX_F2 | PREFIX_F3)" : "(PREFIX_F2 | PREFIX_F3)"; + + const else_block = { + body: [].concat( + "dbg_assert!((prefixes_ & " + check_prefixes + ") == 0);", + gen_instruction_body_after_prefix(no_prefix, size) + ) + }; + + return [].concat( + "let prefixes_ = *prefixes as i32;", + code, + { + type: "if-else", + if_blocks, + else_block, + } + ); + } + else { + return [].concat( + code, + gen_instruction_body_after_prefix(encodings, size) + ); + } +} + +function gen_instruction_body_after_prefix(encodings, size) +{ + const encoding = encodings[0]; + + if(encoding.fixed_g !== undefined) + { + assert(encoding.e); + + // instruction with modrm byte where the middle 3 bits encode the instruction + + // group by opcode without prefix plus middle bits of modrm byte + let cases = encodings.reduce((cases_by_opcode, case_) => { + assert(typeof case_.fixed_g === "number"); + cases_by_opcode[case_.opcode & 0xFFFF | case_.fixed_g << 16] = case_; + return cases_by_opcode; + }, Object.create(null)); + cases = Object.values(cases).sort((e1, e2) => e1.fixed_g - e2.fixed_g); + + return [ + { + type: "switch", + condition: "modrm_byte >> 3 & 7", + cases: cases.map(case_ => { + const fixed_g = case_.fixed_g; + const body = gen_instruction_body_after_fixed_g(case_, size); + + return { + conditions: [fixed_g], + body, + }; + }), + + default_case: { + body: [ + `if DEBUG { panic!("Bad instruction at {:x}", *instruction_pointer); }`, + "trigger_ud();", + ], + } + }, + ]; + } + else { + assert(encodings.length === 1); + return gen_instruction_body_after_fixed_g(encodings[0], size); + } +} + +function gen_instruction_body_after_fixed_g(encoding, size) +{ + const instruction_prefix = []; + const instruction_postfix = + (encoding.block_boundary && !encoding.no_block_boundary_in_interpreted) || + (!encoding.custom && encoding.e) ? + ["after_block_boundary();"] : []; + + if(encoding.task_switch_test || encoding.sse) + { + instruction_prefix.push( + { + type: "if-else", + if_blocks: [ + { + condition: encoding.sse ? "!task_switch_test_mmx()" : "!task_switch_test()", + body: ["return;"], + } + ], + }); + } + + const imm_read = gen_read_imm_call(encoding, size); + const instruction_name = make_instruction_name(encoding, size); + + if(encoding.e) + { + // instruction with modrm byte + + const imm_read = gen_read_imm_call(encoding, size); + + if(encoding.ignore_mod) + { + assert(!imm_read, "Unexpected instruction (ignore mod with immediate value)"); + + // Has modrm byte, but the 2 mod bits are ignored and both + // operands are always registers (0f20-0f24) + + return [].concat( + instruction_prefix, + gen_call(instruction_name, ["modrm_byte & 7", "modrm_byte >> 3 & 7"]), + instruction_postfix + ); + } + else + { + let mem_args; + + if(encoding.custom_modrm_resolve) + { + // requires special handling around modrm_resolve + mem_args = ["modrm_byte"]; + } + else + { + mem_args = ["match modrm_resolve(modrm_byte) { Ok(a) => a, Err(()) => return }"]; + } + + const reg_args = ["modrm_byte & 7"]; + + if(encoding.fixed_g === undefined) + { + mem_args.push("modrm_byte >> 3 & 7"); + reg_args.push("modrm_byte >> 3 & 7"); + } + + if(imm_read) + { + mem_args.push(imm_read); + reg_args.push(imm_read); + } + + return [].concat( + instruction_prefix, + { + type: "if-else", + if_blocks: [ + { + condition: "modrm_byte < 0xC0", + body: [].concat( + gen_call(`${instruction_name}_mem`, mem_args) + ), + } + ], + else_block: { + body: [gen_call(`${instruction_name}_reg`, reg_args)], + }, + }, + instruction_postfix + ); + } + } + else + { + const args = []; + + if(imm_read) + { + args.push(imm_read); + } + + if(encoding.extra_imm16) + { + assert(imm_read); + args.push(wrap_imm_call("read_imm16()")); + } + else if(encoding.extra_imm8) + { + assert(imm_read); + args.push(wrap_imm_call("read_imm8()")); + } + + return [].concat( + instruction_prefix, + gen_call(instruction_name, args), + instruction_postfix + ); + } +} + +function gen_table() +{ + let by_opcode = Object.create(null); + let by_opcode0f = Object.create(null); + + for(let o of x86_table) + { + let opcode = o.opcode; + + if((opcode & 0xFF00) === 0x0F00) + { + opcode &= 0xFF; + by_opcode0f[opcode] = by_opcode0f[opcode] || []; + by_opcode0f[opcode].push(o); + } + else + { + opcode &= 0xFF; + by_opcode[opcode] = by_opcode[opcode] || []; + by_opcode[opcode].push(o); + } + } + + let cases = []; + for(let opcode = 0; opcode < 0x100; opcode++) + { + let encoding = by_opcode[opcode]; + assert(encoding && encoding.length); + + let opcode_hex = hex(opcode, 2); + let opcode_high_hex = hex(opcode | 0x100, 2); + + if(encoding[0].os) + { + cases.push({ + conditions: [`0x${opcode_hex}`], + body: gen_instruction_body(encoding, 16), + }); + cases.push({ + conditions: [`0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, 32), + }); + } + else + { + cases.push({ + conditions: [`0x${opcode_hex}`, `0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, undefined), + }); + } + } + const table = { + type: "switch", + condition: "opcode", + cases, + default_case: { + body: ["assert!(false);"] + }, + }; + if(to_generate.interpreter) + { + const code = [ + "#![cfg_attr(rustfmt, rustfmt_skip)]", + + "use cpu::cpu::{after_block_boundary, modrm_resolve};", + "use cpu::cpu::{read_imm8, read_imm8s, read_imm16, read_imm32s, read_moffs};", + "use cpu::cpu::{task_switch_test, trigger_ud, DEBUG, PREFIX_F2, PREFIX_F3};", + "use cpu::instructions;", + "use cpu::global_pointers::{instruction_pointer, prefixes};", + + "pub unsafe fn run(opcode: u32) {", + table, + "}", + ]; + + finalize_table_rust( + OUT_DIR, + "interpreter.rs", + rust_ast.print_syntax_tree([].concat(code)).join("\n") + "\n" + ); + } + + const cases0f = []; + for(let opcode = 0; opcode < 0x100; opcode++) + { + let encoding = by_opcode0f[opcode]; + + assert(encoding && encoding.length); + + let opcode_hex = hex(opcode, 2); + let opcode_high_hex = hex(opcode | 0x100, 2); + + if(encoding[0].os) + { + cases0f.push({ + conditions: [`0x${opcode_hex}`], + body: gen_instruction_body(encoding, 16), + }); + cases0f.push({ + conditions: [`0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, 32), + }); + } + else + { + let block = { + conditions: [`0x${opcode_hex}`, `0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, undefined), + }; + cases0f.push(block); + } + } + + const table0f = { + type: "switch", + condition: "opcode", + cases: cases0f, + default_case: { + body: ["assert!(false);"] + }, + }; + + if(to_generate.interpreter0f) + { + const code = [ + "#![cfg_attr(rustfmt, rustfmt_skip)]", + + "use cpu::cpu::{after_block_boundary, modrm_resolve};", + "use cpu::cpu::{read_imm8, read_imm16, read_imm32s};", + "use cpu::cpu::{task_switch_test, task_switch_test_mmx, trigger_ud};", + "use cpu::cpu::{DEBUG, PREFIX_66, PREFIX_F2, PREFIX_F3};", + "use cpu::instructions_0f;", + "use cpu::global_pointers::{instruction_pointer, prefixes};", + + "pub unsafe fn run(opcode: u32) {", + table0f, + "}", + ]; + + finalize_table_rust( + OUT_DIR, + "interpreter0f.rs", + rust_ast.print_syntax_tree([].concat(code)).join("\n") + "\n" + ); + } +} diff --git a/gen/generate_jit.js b/gen/generate_jit.js new file mode 100755 index 0000000..34bf8b7 --- /dev/null +++ b/gen/generate_jit.js @@ -0,0 +1,563 @@ +#!/usr/bin/env node +"use strict"; + +const assert = require("assert").strict; +const fs = require("fs"); +const path = require("path"); +const x86_table = require("./x86_table"); +const rust_ast = require("./rust_ast"); +const { hex, mkdirpSync, get_switch_value, get_switch_exist, finalize_table_rust } = require("./util"); + +const OUT_DIR = path.join(__dirname, "..", "src/rust/gen/"); + +mkdirpSync(OUT_DIR); + +const table_arg = get_switch_value("--table"); +const gen_all = get_switch_exist("--all"); +const to_generate = { + jit: gen_all || table_arg === "jit", + jit0f: gen_all || table_arg === "jit0f", +}; + +assert( + Object.keys(to_generate).some(k => to_generate[k]), + "Pass --table [jit|jit0f] or --all to pick which tables to generate" +); + +gen_table(); + +function gen_read_imm_call(op, size_variant) +{ + let size = (op.os || op.opcode % 2 === 1) ? size_variant : 8; + + if(op.imm8 || op.imm8s || op.imm16 || op.imm1632 || op.imm32 || op.immaddr) + { + if(op.imm8) + { + return "ctx.cpu.read_imm8()"; + } + else if(op.imm8s) + { + return "ctx.cpu.read_imm8s()"; + } + else + { + if(op.immaddr) + { + // immaddr: depends on address size + return "ctx.cpu.read_moffs()"; + } + else + { + assert(op.imm1632 || op.imm16 || op.imm32); + + if(op.imm1632 && size === 16 || op.imm16) + { + return "ctx.cpu.read_imm16()"; + } + else + { + assert(op.imm1632 && size === 32 || op.imm32); + return "ctx.cpu.read_imm32()"; + } + } + } + } + else + { + return undefined; + } +} + +function gen_call(name, args) +{ + args = args || []; + return `${name}(${args.join(", ")});`; +} + +/* + * Current naming scheme: + * instr(16|32|)_(66|F2|F3)?0F?[0-9a-f]{2}(_[0-7])?(_mem|_reg|) + */ +function make_instruction_name(encoding, size) +{ + const suffix = encoding.os ? String(size) : ""; + const opcode_hex = hex(encoding.opcode & 0xFF, 2); + const first_prefix = (encoding.opcode & 0xFF00) === 0 ? "" : hex(encoding.opcode >> 8 & 0xFF, 2); + const second_prefix = (encoding.opcode & 0xFF0000) === 0 ? "" : hex(encoding.opcode >> 16 & 0xFF, 2); + const fixed_g_suffix = encoding.fixed_g === undefined ? "" : `_${encoding.fixed_g}`; + + assert(first_prefix === "" || first_prefix === "0F" || first_prefix === "F2" || first_prefix === "F3"); + assert(second_prefix === "" || second_prefix === "66" || second_prefix === "F2" || second_prefix === "F3"); + + return `instr${suffix}_${second_prefix}${first_prefix}${opcode_hex}${fixed_g_suffix}`; +} + +function gen_instruction_body(encodings, size) +{ + const encoding = encodings[0]; + + let has_66 = []; + let has_F2 = []; + let has_F3 = []; + let no_prefix = []; + + for(let e of encodings) + { + if((e.opcode >>> 16) === 0x66) has_66.push(e); + else if((e.opcode >>> 8 & 0xFF) === 0xF2 || (e.opcode >>> 16) === 0xF2) has_F2.push(e); + else if((e.opcode >>> 8 & 0xFF) === 0xF3 || (e.opcode >>> 16) === 0xF3) has_F3.push(e); + else no_prefix.push(e); + } + + if(has_F2.length || has_F3.length) + { + assert((encoding.opcode & 0xFF0000) === 0 || (encoding.opcode & 0xFF00) === 0x0F00); + } + + if(has_66.length) + { + assert((encoding.opcode & 0xFF00) === 0x0F00); + } + + const code = []; + + if(encoding.e) + { + code.push("let modrm_byte = ctx.cpu.read_imm8();"); + } + + if(has_66.length || has_F2.length || has_F3.length) + { + const if_blocks = []; + + if(has_66.length) { + const body = gen_instruction_body_after_prefix(has_66, size); + if_blocks.push({ condition: "ctx.cpu.prefixes & ::prefix::PREFIX_66 != 0", body, }); + } + if(has_F2.length) { + const body = gen_instruction_body_after_prefix(has_F2, size); + if_blocks.push({ condition: "ctx.cpu.prefixes & ::prefix::PREFIX_F2 != 0", body, }); + } + if(has_F3.length) { + const body = gen_instruction_body_after_prefix(has_F3, size); + if_blocks.push({ condition: "ctx.cpu.prefixes & ::prefix::PREFIX_F3 != 0", body, }); + } + + const else_block = { + body: gen_instruction_body_after_prefix(no_prefix, size), + }; + + return [].concat( + code, + { + type: "if-else", + if_blocks, + else_block, + } + ); + } + else { + return [].concat( + code, + gen_instruction_body_after_prefix(encodings, size) + ); + } +} + +function gen_instruction_body_after_prefix(encodings, size) +{ + const encoding = encodings[0]; + + if(encoding.fixed_g !== undefined) + { + assert(encoding.e); + + // instruction with modrm byte where the middle 3 bits encode the instruction + + // group by opcode without prefix plus middle bits of modrm byte + let cases = encodings.reduce((cases_by_opcode, case_) => { + assert(typeof case_.fixed_g === "number"); + cases_by_opcode[case_.opcode & 0xFFFF | case_.fixed_g << 16] = case_; + return cases_by_opcode; + }, Object.create(null)); + cases = Object.values(cases).sort((e1, e2) => e1.fixed_g - e2.fixed_g); + + return [ + { + type: "switch", + condition: "modrm_byte >> 3 & 7", + cases: cases.map(case_ => { + const fixed_g = case_.fixed_g; + const body = gen_instruction_body_after_fixed_g(case_, size); + + return { + conditions: [fixed_g], + body, + }; + }), + + default_case: { + body: [].concat( + gen_call(`::codegen::gen_trigger_ud`, ["ctx"]), + "*instr_flags |= ::jit::JIT_INSTR_BLOCK_BOUNDARY_FLAG;" + ), + } + }, + ]; + } + else { + assert(encodings.length === 1); + return gen_instruction_body_after_fixed_g(encodings[0], size); + } +} + +function gen_instruction_body_after_fixed_g(encoding, size) +{ + const instruction_postfix = []; + + if(encoding.block_boundary || (!encoding.custom && encoding.e)) + { + instruction_postfix.push("*instr_flags |= ::jit::JIT_INSTR_BLOCK_BOUNDARY_FLAG;"); + } + + const instruction_prefix = []; + + if(encoding.task_switch_test || encoding.sse) + { + instruction_prefix.push( + gen_call(encoding.sse ? "::codegen::gen_task_switch_test_mmx" : "::codegen::gen_task_switch_test", ["ctx"]) + ); + } + + const imm_read = gen_read_imm_call(encoding, size); + const imm_read_bindings = []; + if(imm_read) + { + imm_read_bindings.push(`let imm = ${imm_read} as u32;`); + } + + const instruction_name = make_instruction_name(encoding, size); + + if(!encoding.prefix) + { + if(encoding.custom) + { + } + else + { + instruction_prefix.push( + gen_call("::codegen::gen_move_registers_from_locals_to_memory", ["ctx"]) + ); + instruction_postfix.push( + gen_call("::codegen::gen_move_registers_from_memory_to_locals", ["ctx"]) + ); + } + } + + if(encoding.e) + { + const reg_postfix = []; + const mem_postfix = []; + + if(encoding.mem_ud) + { + mem_postfix.push( + "*instr_flags |= ::jit::JIT_INSTR_BLOCK_BOUNDARY_FLAG;" + ); + } + + if(encoding.reg_ud) + { + reg_postfix.push( + "*instr_flags |= ::jit::JIT_INSTR_BLOCK_BOUNDARY_FLAG;" + ); + } + + if(encoding.ignore_mod) + { + assert(!imm_read, "Unexpected instruction (ignore mod with immediate value)"); + + // Has modrm byte, but the 2 mod bits are ignored and both + // operands are always registers (0f20-0f24) + const args = ["ctx.builder", `"${instruction_name}"`, "(modrm_byte & 7) as u32", "(modrm_byte >> 3 & 7) as u32"]; + + return [].concat( + instruction_prefix, + gen_call(`::codegen::gen_fn${args.length - 2}_const`, args), + reg_postfix, + instruction_postfix + ); + } + else if(encoding.custom) + { + const mem_args = ["ctx", "addr"]; + const reg_args = ["ctx", "(modrm_byte & 7) as u32"]; + + if(encoding.fixed_g === undefined) + { + mem_args.push("(modrm_byte >> 3 & 7) as u32"); + reg_args.push("(modrm_byte >> 3 & 7) as u32"); + } + + if(imm_read) + { + mem_args.push("imm"); + reg_args.push("imm"); + } + + return [].concat( + instruction_prefix, + { + type: "if-else", + if_blocks: [{ + condition: "modrm_byte < 0xC0", + body: [].concat( + "let addr = ::modrm::decode(ctx.cpu, modrm_byte);", + imm_read_bindings, + gen_call(`::jit_instructions::${instruction_name}_mem_jit`, mem_args), + mem_postfix + ), + }], + else_block: { + body: [].concat( + imm_read_bindings, + gen_call(`::jit_instructions::${instruction_name}_reg_jit`, reg_args), + reg_postfix + ), + }, + }, + instruction_postfix + ); + } + else + { + const mem_args = ["ctx.builder", `"${instruction_name}_mem"`]; + const reg_args = ["ctx.builder", `"${instruction_name}_reg"`, "(modrm_byte & 7) as u32"]; + + if(encoding.fixed_g === undefined) + { + mem_args.push("(modrm_byte >> 3 & 7) as u32"); + reg_args.push("(modrm_byte >> 3 & 7) as u32"); + } + + if(imm_read) + { + mem_args.push("imm"); + reg_args.push("imm"); + } + + return [].concat( + instruction_prefix, + { + type: "if-else", + if_blocks: [{ + condition: "modrm_byte < 0xC0", + body: [].concat( + "let addr = ::modrm::decode(ctx.cpu, modrm_byte);", + gen_call(`::codegen::gen_modrm_resolve`, ["ctx", "addr"]), + imm_read_bindings, + gen_call(`::codegen::gen_modrm_fn${mem_args.length - 2}`, mem_args), + mem_postfix + ), + }], + else_block: { + body: [].concat( + imm_read_bindings, + gen_call(`::codegen::gen_fn${reg_args.length - 2}_const`, reg_args), + reg_postfix + ), + }, + }, + instruction_postfix + ); + } + } + else if(encoding.prefix || encoding.custom) + { + // custom, but not modrm + + const args = ["ctx"]; + + if(imm_read) + { + args.push("imm"); + } + + if(encoding.prefix) + { + args.push("instr_flags"); + } + + return [].concat( + instruction_prefix, + imm_read_bindings, + gen_call(`::jit_instructions::${instruction_name}_jit`, args), + instruction_postfix + ); + } + else + { + // instruction without modrm byte or prefix + + const args = ["ctx.builder", `"${instruction_name}"`]; + + if(imm_read) + { + args.push("imm"); + } + + if(encoding.extra_imm16) + { + assert(imm_read); + imm_read_bindings.push(`let imm2 = ctx.cpu.read_imm16() as u32;`); + args.push("imm2"); + } + else if(encoding.extra_imm8) + { + assert(imm_read); + imm_read_bindings.push(`let imm2 = ctx.cpu.read_imm8() as u32;`); + args.push("imm2"); + } + + return [].concat( + instruction_prefix, + imm_read_bindings, + gen_call(`::codegen::gen_fn${args.length - 2}_const`, args), + instruction_postfix + ); + } +} + +function gen_table() +{ + let by_opcode = Object.create(null); + let by_opcode0f = Object.create(null); + + for(let o of x86_table) + { + let opcode = o.opcode; + + if((opcode & 0xFF00) === 0x0F00) + { + opcode &= 0xFF; + by_opcode0f[opcode] = by_opcode0f[opcode] || []; + by_opcode0f[opcode].push(o); + } + else + { + opcode &= 0xFF; + by_opcode[opcode] = by_opcode[opcode] || []; + by_opcode[opcode].push(o); + } + } + + let cases = []; + for(let opcode = 0; opcode < 0x100; opcode++) + { + let encoding = by_opcode[opcode]; + assert(encoding && encoding.length); + + let opcode_hex = hex(opcode, 2); + let opcode_high_hex = hex(opcode | 0x100, 2); + + if(encoding[0].os) + { + cases.push({ + conditions: [`0x${opcode_hex}`], + body: gen_instruction_body(encoding, 16), + }); + cases.push({ + conditions: [`0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, 32), + }); + } + else + { + cases.push({ + conditions: [`0x${opcode_hex}`, `0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, undefined), + }); + } + } + const table = { + type: "switch", + condition: "opcode", + cases, + default_case: { + body: ["assert!(false);"] + }, + }; + + if(to_generate.jit) + { + const code = [ + "#[cfg_attr(rustfmt, rustfmt_skip)]", + "pub fn jit(opcode: u32, ctx: &mut ::jit::JitContext, instr_flags: &mut u32) {", + table, + "}", + ]; + + finalize_table_rust( + OUT_DIR, + "jit.rs", + rust_ast.print_syntax_tree([].concat(code)).join("\n") + "\n" + ); + } + + const cases0f = []; + for(let opcode = 0; opcode < 0x100; opcode++) + { + let encoding = by_opcode0f[opcode]; + + assert(encoding && encoding.length); + + let opcode_hex = hex(opcode, 2); + let opcode_high_hex = hex(opcode | 0x100, 2); + + if(encoding[0].os) + { + cases0f.push({ + conditions: [`0x${opcode_hex}`], + body: gen_instruction_body(encoding, 16), + }); + cases0f.push({ + conditions: [`0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, 32), + }); + } + else + { + let block = { + conditions: [`0x${opcode_hex}`, `0x${opcode_high_hex}`], + body: gen_instruction_body(encoding, undefined), + }; + cases0f.push(block); + } + } + + const table0f = { + type: "switch", + condition: "opcode", + cases: cases0f, + default_case: { + body: ["assert!(false);"] + }, + }; + + if(to_generate.jit0f) + { + const code = [ + "#[cfg_attr(rustfmt, rustfmt_skip)]", + "pub fn jit(opcode: u32, ctx: &mut ::jit::JitContext, instr_flags: &mut u32) {", + table0f, + "}", + ]; + + finalize_table_rust( + OUT_DIR, + "jit0f.rs", + rust_ast.print_syntax_tree([].concat(code)).join("\n") + "\n" + ); + } +} diff --git a/gen/rust_ast.js b/gen/rust_ast.js new file mode 100644 index 0000000..fb4f2e9 --- /dev/null +++ b/gen/rust_ast.js @@ -0,0 +1,83 @@ +"use strict"; + +const assert = require("assert").strict; + +function indent(lines, how_much) +{ + return lines.map(line => " ".repeat(how_much) + line); +} + +function print_syntax_tree(statements) +{ + let code = []; + + for(let statement of statements) + { + if(typeof statement === "string") + { + code.push(statement); + } + else if(statement.type === "switch") + { + assert(statement.condition); + + const cases = []; + + for(let case_ of statement.cases) + { + assert(case_.conditions.length >= 1); + + cases.push(case_.conditions.join(" | ") + " => {"); + cases.push.apply(cases, indent(print_syntax_tree(case_.body), 4)); + cases.push(`},`); + } + + if(statement.default_case) + { + cases.push(`_ => {`); + cases.push.apply(cases, indent(print_syntax_tree(statement.default_case.body), 4)); + cases.push(`}`); + } + + code.push(`match ${statement.condition} {`); + code.push.apply(code, indent(cases, 4)); + code.push(`}`); + } + else if(statement.type === "if-else") + { + assert(statement.if_blocks.length >= 1); + + let first_if_block = statement.if_blocks[0]; + + code.push(`if ${first_if_block.condition} {`); + code.push.apply(code, indent(print_syntax_tree(first_if_block.body), 4)); + code.push(`}`); + + for(let i = 1; i < statement.if_blocks.length; i++) + { + let if_block = statement.if_blocks[i]; + + code.push(`else if ${if_block.condition} {`); + code.push.apply(code, indent(print_syntax_tree(if_block.body), 4)); + code.push(`}`); + } + + if(statement.else_block) + { + code.push(`else {`); + code.push.apply(code, indent(print_syntax_tree(statement.else_block.body), 4)); + code.push(`}`); + } + } + else + { + assert(false, "Unexpected type: " + statement.type, "In:", statement); + } + } + + return code; +} + +module.exports = { + print_syntax_tree, +}; diff --git a/gen/util.js b/gen/util.js new file mode 100644 index 0000000..9325428 --- /dev/null +++ b/gen/util.js @@ -0,0 +1,54 @@ +"use strict"; + +const assert = require("assert"); +const fs = require("fs"); +const path = require("path"); +const process = require("process"); +const child_process = require("child_process"); + +const CYAN_FMT = "\x1b[36m%s\x1b[0m"; + +function hex(n, pad) +{ + pad = pad || 0; + let s = n.toString(16).toUpperCase(); + while(s.length < pad) s = "0" + s; + return s; +} + +function mkdirpSync(dir) +{ + fs.mkdirSync(dir, { recursive: true }); +} + +function get_switch_value(arg_switch) +{ + const argv = process.argv; + const switch_i = argv.indexOf(arg_switch); + const val_i = switch_i + 1; + if(switch_i > -1 && val_i < argv.length) + { + return argv[switch_i + 1]; + } + return null; +} + +function get_switch_exist(arg_switch) +{ + return process.argv.includes(arg_switch); +} + +function finalize_table_rust(out_dir, name, contents) +{ + const file_path = path.join(out_dir, name); + fs.writeFileSync(file_path, contents); + console.log(CYAN_FMT, `[+] Wrote table ${name}.`); +} + +module.exports = { + hex, + mkdirpSync, + get_switch_value, + get_switch_exist, + finalize_table_rust, +}; diff --git a/gen/x86_table.js b/gen/x86_table.js new file mode 100644 index 0000000..dc0645f --- /dev/null +++ b/gen/x86_table.js @@ -0,0 +1,976 @@ +"use strict"; + +const { hex } = require("./util"); + +// http://ref.x86asm.net/coder32.html + +const zf = 1 << 6; +const of = 1 << 11; +const cf = 1 << 0; +const af = 1 << 4; +const pf = 1 << 2; +const sf = 1 << 7; + +// === Types of instructions +// +// create entry | check for compiled code | instruction +// -------------+-------------------------+----------------------------------------------------------- +// 1 | optional | pop ds (may change cpu state) +// | | trigger_ud, div (exception that doesn't generate conditional return from BB) +// | | port io, popf, sti (may call interrupt or continue at next instruction) +// | | hlt +// -------------+-------------------------+----------------------------------------------------------- +// 1 | 1 | call [eax], jmp [eax], int, iret, ret, jmpf, callf, sysenter, sysexit +// | | Special case: normal instruction with fallthough to next page +// | | Special case: after execution of compiled code +// | | -> may create redundant entry points depending on last instruction? +// -------------+-------------------------+----------------------------------------------------------- +// 1 | 0 | rep movs, rep lods, rep stos, rep cmps, rep scas +// | | -> Executed as follows: +// | | - Upto including the first call in compiled mode +// | | - Back to main loop and repeated in interpreted mode (as entry point is after instruction, not on) +// | | - When finished entry pointer *after* instruction is hit and execution continues in compiled mode +// -------------+-------------------------+----------------------------------------------------------- +// 0 | optional | jmp foo, jnz foo +// | | (foo is in the same page as the instruction) +// -------------+-------------------------+----------------------------------------------------------- +// 1 | 1 | call foo +// | | (foo is in the same page as the instruction) +// | | -> The entry point is not created for jumps within +// | | this page, but speculatively for calls from +// | | other pages to the function in this page +// -------------+-------------------------+----------------------------------------------------------- +// 1 | 1 | call foo, jmp foo, jnz foo +// | | (foo is in a different page than the instruction) + + +// e: a modrm byte follows the operand +// os: the instruction behaves differently depending on the operand size +// fixed_g: the reg field of the modrm byte selects an instruction +// skip: skip automatically generated tests (nasmtests) +// mask_flags: flags bits to mask in generated tests +// prefix: is a prefix instruction +// imm8, imm8s, imm16, imm1632, immaddr, extra_imm8, extra_imm16: one or two immediate bytes follows the instruction +// custom: will callback jit to generate custom code +// block_boundary: may change eip in a way not handled by the jit +// no_next_instruction: jit will stop analysing after instruction (e.g., unconditional jump, ret) +const encodings = [ + { opcode: 0x00, custom: 1, e: 1, }, + { opcode: 0x01, custom: 1, os: 1, e: 1, }, + { opcode: 0x02, custom: 1, e: 1, }, + { opcode: 0x03, custom: 1, os: 1, e: 1, }, + + { opcode: 0x08, custom: 1, e: 1, }, + { opcode: 0x09, custom: 1, os: 1, e: 1, }, + { opcode: 0x0A, custom: 1, e: 1, }, + { opcode: 0x0B, custom: 1, os: 1, e: 1, }, + + { opcode: 0x10, custom: 1, e: 1, }, + { opcode: 0x11, custom: 1, os: 1, e: 1, }, + { opcode: 0x12, custom: 1, e: 1, }, + { opcode: 0x13, custom: 1, os: 1, e: 1, }, + + { opcode: 0x18, custom: 1, e: 1, }, + { opcode: 0x19, custom: 1, os: 1, e: 1, }, + { opcode: 0x1A, custom: 1, e: 1, }, + { opcode: 0x1B, custom: 1, os: 1, e: 1, }, + + { opcode: 0x20, custom: 1, e: 1, }, + { opcode: 0x21, custom: 1, os: 1, e: 1, }, + { opcode: 0x22, custom: 1, e: 1, }, + { opcode: 0x23, custom: 1, os: 1, e: 1, }, + + { opcode: 0x28, custom: 1, e: 1, }, + { opcode: 0x29, custom: 1, os: 1, e: 1, }, + { opcode: 0x2A, custom: 1, e: 1, }, + { opcode: 0x2B, custom: 1, os: 1, e: 1, }, + + { opcode: 0x30, custom: 1, e: 1, }, + { opcode: 0x31, custom: 1, os: 1, e: 1, }, + { opcode: 0x32, custom: 1, e: 1, }, + { opcode: 0x33, custom: 1, os: 1, e: 1, }, + + { opcode: 0x38, custom: 1, e: 1, }, + { opcode: 0x39, custom: 1, os: 1, e: 1, }, + { opcode: 0x3A, custom: 1, e: 1, }, + { opcode: 0x3B, custom: 1, os: 1, e: 1, }, + + { opcode: 0x06, os: 1, custom: 1 }, + { opcode: 0x07, os: 1, skip: 1, block_boundary: 1, }, // pop es: block_boundary since it uses non-raising cpu exceptions + { opcode: 0x0E, os: 1, custom: 1 }, + { opcode: 0x0F, os: 1, prefix: 1, }, + { opcode: 0x16, os: 1, custom: 1 }, + { opcode: 0x17, block_boundary: 1, os: 1, skip: 1, }, // pop ss + { opcode: 0x1E, os: 1, custom: 1 }, + { opcode: 0x1F, block_boundary: 1, os: 1, skip: 1, }, // pop ds + { opcode: 0x26, prefix: 1, }, + { opcode: 0x27, mask_flags: of, }, + { opcode: 0x2E, prefix: 1, }, + { opcode: 0x2F, mask_flags: of, }, + { opcode: 0x36, prefix: 1, }, + { opcode: 0x37, mask_flags: of | sf | pf | zf, }, + { opcode: 0x3E, prefix: 1, }, + { opcode: 0x3F, mask_flags: of | sf | pf | zf, }, + + { opcode: 0x40, os: 1, custom: 1 }, + { opcode: 0x41, os: 1, custom: 1 }, + { opcode: 0x42, os: 1, custom: 1 }, + { opcode: 0x43, os: 1, custom: 1 }, + { opcode: 0x44, os: 1, custom: 1 }, + { opcode: 0x45, os: 1, custom: 1 }, + { opcode: 0x46, os: 1, custom: 1 }, + { opcode: 0x47, os: 1, custom: 1 }, + + { opcode: 0x48, os: 1, custom: 1 }, + { opcode: 0x49, os: 1, custom: 1 }, + { opcode: 0x4A, os: 1, custom: 1 }, + { opcode: 0x4B, os: 1, custom: 1 }, + { opcode: 0x4C, os: 1, custom: 1 }, + { opcode: 0x4D, os: 1, custom: 1 }, + { opcode: 0x4E, os: 1, custom: 1 }, + { opcode: 0x4F, os: 1, custom: 1 }, + + { opcode: 0x50, custom: 1, os: 1 }, + { opcode: 0x51, custom: 1, os: 1 }, + { opcode: 0x52, custom: 1, os: 1 }, + { opcode: 0x53, custom: 1, os: 1 }, + { opcode: 0x54, custom: 1, os: 1 }, + { opcode: 0x55, custom: 1, os: 1 }, + { opcode: 0x56, custom: 1, os: 1 }, + { opcode: 0x57, custom: 1, os: 1 }, + + { opcode: 0x58, custom: 1, os: 1, }, + { opcode: 0x59, custom: 1, os: 1, }, + { opcode: 0x5A, custom: 1, os: 1, }, + { opcode: 0x5B, custom: 1, os: 1, }, + { opcode: 0x5C, custom: 1, os: 1, }, + { opcode: 0x5D, custom: 1, os: 1, }, + { opcode: 0x5E, custom: 1, os: 1, }, + { opcode: 0x5F, custom: 1, os: 1, }, + + { opcode: 0x60, os: 1, block_boundary: 1 }, // pusha + { opcode: 0x61, os: 1, block_boundary: 1 }, // popa + { opcode: 0x62, e: 1, skip: 1, }, + { opcode: 0x63, e: 1, block_boundary: 1, }, // arpl + { opcode: 0x64, prefix: 1, }, + { opcode: 0x65, prefix: 1, }, + { opcode: 0x66, prefix: 1, }, + { opcode: 0x67, prefix: 1, }, + + { opcode: 0x68, custom: 1, os: 1, imm1632: 1 }, + { opcode: 0x69, os: 1, e: 1, custom: 1, imm1632: 1, mask_flags: af, }, // zf? + { opcode: 0x6A, custom: 1, os: 1, imm8s: 1 }, + { opcode: 0x6B, os: 1, e: 1, custom: 1, imm8s: 1, mask_flags: af, }, // zf? + + { opcode: 0x6C, block_boundary: 1, custom: 1, is_string: 1, skip: 1, }, // ins + { opcode: 0xF26C, block_boundary: 1, custom: 1, is_string: 1, skip: 1, }, + { opcode: 0xF36C, block_boundary: 1, custom: 1, is_string: 1, skip: 1, }, + { opcode: 0x6D, block_boundary: 1, custom: 1, is_string: 1, os: 1, skip: 1, }, + { opcode: 0xF26D, block_boundary: 1, custom: 1, is_string: 1, os: 1, skip: 1, }, + { opcode: 0xF36D, block_boundary: 1, custom: 1, is_string: 1, os: 1, skip: 1, }, + + { opcode: 0x6E, block_boundary: 1, custom: 1, is_string: 1, skip: 1, }, // outs + { opcode: 0xF26E, block_boundary: 1, custom: 1, is_string: 1, skip: 1, }, + { opcode: 0xF36E, block_boundary: 1, custom: 1, is_string: 1, skip: 1, }, + { opcode: 0x6F, block_boundary: 1, custom: 1, is_string: 1, os: 1, skip: 1, }, + { opcode: 0xF26F, block_boundary: 1, custom: 1, is_string: 1, os: 1, skip: 1, }, + { opcode: 0xF36F, block_boundary: 1, custom: 1, is_string: 1, os: 1, skip: 1, }, + + { opcode: 0x84, custom: 1, e: 1, }, + { opcode: 0x85, custom: 1, e: 1, os: 1, }, + { opcode: 0x86, custom: 1, e: 1, }, + { opcode: 0x87, custom: 1, os: 1, e: 1, }, + { opcode: 0x88, custom: 1, e: 1, }, + { opcode: 0x89, custom: 1, os: 1, e: 1, }, + { opcode: 0x8A, custom: 1, e: 1, }, + { opcode: 0x8B, custom: 1, os: 1, e: 1, }, + + { opcode: 0x8C, os: 1, e: 1, custom: 1, skip: 1 }, // mov reg, sreg + { opcode: 0x8D, reg_ud: 1, os: 1, e: 1, custom_modrm_resolve: 1, custom: 1, }, // lea + { opcode: 0x8E, block_boundary: 1, e: 1, skip: 1, }, // mov sreg + { opcode: 0x8F, os: 1, e: 1, fixed_g: 0, custom_modrm_resolve: 1, custom: 1, block_boundary: 1, }, // pop r/m + + { opcode: 0x90, custom: 1, }, + { opcode: 0x91, custom: 1, os: 1, }, + { opcode: 0x92, custom: 1, os: 1, }, + { opcode: 0x93, custom: 1, os: 1, }, + { opcode: 0x94, custom: 1, os: 1, }, + { opcode: 0x95, custom: 1, os: 1, }, + { opcode: 0x96, custom: 1, os: 1, }, + { opcode: 0x97, custom: 1, os: 1, }, + + { opcode: 0x98, os: 1, custom: 1 }, + { opcode: 0x99, os: 1, custom: 1 }, + { opcode: 0x9A, os: 1, imm1632: 1, extra_imm16: 1, skip: 1, block_boundary: 1, }, // callf + { opcode: 0x9B, block_boundary: 1, skip: 1, }, // fwait: block_boundary since it uses non-raising cpu exceptions + { opcode: 0x9C, os: 1, custom: 1, skip: 1 }, // pushf + { opcode: 0x9D, os: 1, custom: 1, skip: 1 }, // popf + { opcode: 0x9E, custom: 1 }, + { opcode: 0x9F, custom: 1 }, + + { opcode: 0xA0, custom: 1, immaddr: 1 }, + { opcode: 0xA1, custom: 1, os: 1, immaddr: 1 }, + { opcode: 0xA2, custom: 1, immaddr: 1 }, + { opcode: 0xA3, custom: 1, os: 1, immaddr: 1 }, + + // string instructions aren't jumps, but they modify eip due to how they're implemented + { opcode: 0xA4, block_boundary: 0, custom: 1, is_string: 1, }, + { opcode: 0xF2A4, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xF3A4, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xA5, block_boundary: 0, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF2A5, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF3A5, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + + { opcode: 0xA6, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xF2A6, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xF3A6, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xA7, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF2A7, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF3A7, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + + { opcode: 0xA8, custom: 1, imm8: 1, }, + { opcode: 0xA9, custom: 1, os: 1, imm1632: 1, }, + + { opcode: 0xAA, block_boundary: 0, custom: 1, is_string: 1, }, + { opcode: 0xF2AA, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xF3AA, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xAB, block_boundary: 0, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF2AB, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF3AB, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + + { opcode: 0xAC, block_boundary: 0, custom: 1, is_string: 1, }, + { opcode: 0xF2AC, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xF3AC, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xAD, block_boundary: 0, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF2AD, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF3AD, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + + { opcode: 0xAE, block_boundary: 0, custom: 1, is_string: 1, }, + { opcode: 0xF2AE, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xF3AE, block_boundary: 1, custom: 1, is_string: 1, }, + { opcode: 0xAF, block_boundary: 0, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF2AF, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + { opcode: 0xF3AF, block_boundary: 1, custom: 1, is_string: 1, os: 1, }, + + { opcode: 0xC2, custom: 1, block_boundary: 1, no_next_instruction: 1, os: 1, absolute_jump: 1, imm16: 1, skip: 1, }, // ret + { opcode: 0xC3, custom: 1, block_boundary: 1, no_next_instruction: 1, os: 1, absolute_jump: 1, skip: 1, }, + + { opcode: 0xC4, block_boundary: 1, os: 1, e: 1, skip: 1, }, // les + { opcode: 0xC5, block_boundary: 1, os: 1, e: 1, skip: 1, }, // lds + + { opcode: 0xC6, custom: 1, e: 1, fixed_g: 0, imm8: 1 }, + { opcode: 0xC7, custom: 1, os: 1, e: 1, fixed_g: 0, imm1632: 1 }, + + // XXX: Temporary block boundary + { opcode: 0xC8, os: 1, imm16: 1, extra_imm8: 1, block_boundary: 1, }, // enter + { opcode: 0xC9, custom: 1, os: 1, skip: 1 }, // leave + + { opcode: 0xCA, block_boundary: 1, no_next_instruction: 1, os: 1, imm16: 1, skip: 1, }, // retf + { opcode: 0xCB, block_boundary: 1, no_next_instruction: 1, os: 1, skip: 1, }, + { opcode: 0xCC, block_boundary: 1, skip: 1, }, // int + { opcode: 0xCD, block_boundary: 1, skip: 1, imm8: 1, }, + { opcode: 0xCE, block_boundary: 1, skip: 1, }, + { opcode: 0xCF, block_boundary: 1, no_next_instruction: 1, os: 1, skip: 1, }, // iret + + { opcode: 0xD4, imm8: 1, block_boundary: 1, }, // aam, may trigger #de + { opcode: 0xD5, imm8: 1, mask_flags: of | cf | af, }, + { opcode: 0xD6, }, + + { opcode: 0xD7, skip: 1, custom: 1, }, + + { opcode: 0xD8, e: 1, fixed_g: 0, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xD8, e: 1, fixed_g: 1, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xD8, e: 1, fixed_g: 2, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xD8, e: 1, fixed_g: 3, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xD8, e: 1, fixed_g: 4, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xD8, e: 1, fixed_g: 5, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xD8, e: 1, fixed_g: 6, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xD8, e: 1, fixed_g: 7, custom: 1, is_fpu: 1, task_switch_test: 1, }, + + { opcode: 0xD9, e: 1, fixed_g: 0, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, }, + { opcode: 0xD9, e: 1, fixed_g: 1, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, }, + { opcode: 0xD9, e: 1, fixed_g: 2, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, }, + { opcode: 0xD9, e: 1, fixed_g: 3, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, }, + { opcode: 0xD9, e: 1, fixed_g: 4, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, skip_mem: 1, }, // fldenv (mem) + { opcode: 0xD9, e: 1, fixed_g: 5, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, }, + { opcode: 0xD9, e: 1, fixed_g: 6, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, skip: 1, }, // fstenv (mem), fprem (reg) + { opcode: 0xD9, e: 1, fixed_g: 7, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, skip_reg: 1, }, // fprem, fyl2xp1 (precision issues) + + { opcode: 0xDA, e: 1, fixed_g: 0, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDA, e: 1, fixed_g: 1, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDA, e: 1, fixed_g: 2, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDA, e: 1, fixed_g: 3, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDA, e: 1, fixed_g: 4, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDA, e: 1, fixed_g: 5, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDA, e: 1, fixed_g: 6, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDA, e: 1, fixed_g: 7, custom: 1, is_fpu: 1, task_switch_test: 1, }, + + { opcode: 0xDB, e: 1, fixed_g: 0, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDB, e: 1, fixed_g: 1, custom: 0, is_fpu: 1, task_switch_test: 1, skip_mem: 1, }, // unimplemented: fisttp (sse3) + { opcode: 0xDB, e: 1, fixed_g: 2, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDB, e: 1, fixed_g: 3, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDB, e: 1, fixed_g: 4, custom: 0, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDB, e: 1, fixed_g: 5, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDB, e: 1, fixed_g: 6, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDB, e: 1, fixed_g: 7, custom: 0, is_fpu: 1, task_switch_test: 1, }, + + { opcode: 0xDC, e: 1, fixed_g: 0, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDC, e: 1, fixed_g: 1, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDC, e: 1, fixed_g: 2, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDC, e: 1, fixed_g: 3, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDC, e: 1, fixed_g: 4, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDC, e: 1, fixed_g: 5, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDC, e: 1, fixed_g: 6, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDC, e: 1, fixed_g: 7, custom: 1, is_fpu: 1, task_switch_test: 1, }, + + { opcode: 0xDD, e: 1, fixed_g: 0, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, }, + { opcode: 0xDD, e: 1, fixed_g: 1, custom: 0, is_fpu: 1, task_switch_test: 1, os: 1, skip_mem: 1, }, // unimplemented: fisttp (sse3) + { opcode: 0xDD, e: 1, fixed_g: 2, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, }, + { opcode: 0xDD, e: 1, fixed_g: 3, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, }, + { opcode: 0xDD, e: 1, fixed_g: 4, custom: 0, is_fpu: 1, task_switch_test: 1, os: 1, skip_mem: 1 }, // frstor + { opcode: 0xDD, e: 1, fixed_g: 5, custom: 1, is_fpu: 1, task_switch_test: 1, os: 1, }, + { opcode: 0xDD, e: 1, fixed_g: 6, custom: 0, is_fpu: 1, task_switch_test: 1, os: 1, skip_mem: 1 }, // fsave + { opcode: 0xDD, e: 1, fixed_g: 7, custom: 0, is_fpu: 1, task_switch_test: 1, os: 1, }, + + { opcode: 0xDE, e: 1, fixed_g: 0, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDE, e: 1, fixed_g: 1, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDE, e: 1, fixed_g: 2, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDE, e: 1, fixed_g: 3, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDE, e: 1, fixed_g: 4, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDE, e: 1, fixed_g: 5, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDE, e: 1, fixed_g: 6, custom: 1, is_fpu: 1, task_switch_test: 1, }, + { opcode: 0xDE, e: 1, fixed_g: 7, custom: 1, is_fpu: 1, task_switch_test: 1, }, + + { opcode: 0xDF, e: 1, fixed_g: 0, custom: 0, is_fpu: 1, task_switch_test: 1 }, + { opcode: 0xDF, e: 1, fixed_g: 1, custom: 0, is_fpu: 1, task_switch_test: 1, skip_mem: 1 }, // unimplemented: fisttp (sse3) + { opcode: 0xDF, e: 1, fixed_g: 2, custom: 1, is_fpu: 1, task_switch_test: 1 }, + { opcode: 0xDF, e: 1, fixed_g: 3, custom: 1, is_fpu: 1, task_switch_test: 1 }, + { opcode: 0xDF, e: 1, fixed_g: 4, custom: 1, is_fpu: 1, task_switch_test: 1, skip_mem: 1 }, // unimplemented: Binary Coded Decimals + { opcode: 0xDF, e: 1, fixed_g: 5, custom: 1, is_fpu: 1, task_switch_test: 1 }, + { opcode: 0xDF, e: 1, fixed_g: 6, custom: 1, is_fpu: 1, task_switch_test: 1 }, + { opcode: 0xDF, e: 1, fixed_g: 7, custom: 1, is_fpu: 1, task_switch_test: 1 }, + + // loop, jcxz, etc. + { opcode: 0xE0, os: 1, imm8s: 1, no_block_boundary_in_interpreted: 1, skip: 1, block_boundary: 1, jump_offset_imm: 1, custom: 1, conditional_jump: 1, }, + { opcode: 0xE1, os: 1, imm8s: 1, no_block_boundary_in_interpreted: 1, skip: 1, block_boundary: 1, jump_offset_imm: 1, custom: 1, conditional_jump: 1, }, + { opcode: 0xE2, os: 1, imm8s: 1, no_block_boundary_in_interpreted: 1, skip: 1, block_boundary: 1, jump_offset_imm: 1, custom: 1, conditional_jump: 1, }, + { opcode: 0xE3, os: 1, imm8s: 1, no_block_boundary_in_interpreted: 1, skip: 1, block_boundary: 1, jump_offset_imm: 1, custom: 1, conditional_jump: 1, }, + + // port functions aren't jumps, but they may modify eip due to how they are implemented + { opcode: 0xE4, block_boundary: 1, imm8: 1, skip: 1, }, // in + { opcode: 0xE5, block_boundary: 1, os: 1, imm8: 1, skip: 1, }, + { opcode: 0xE6, block_boundary: 1, imm8: 1, skip: 1, }, // out + { opcode: 0xE7, block_boundary: 1, os: 1, imm8: 1, skip: 1, }, + + { opcode: 0xE8, block_boundary: 1, jump_offset_imm: 1, os: 1, imm1632: 1, custom: 1, skip: 1, }, // call + { opcode: 0xE9, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, no_next_instruction: 1, os: 1, imm1632: 1, custom: 1, skip: 1, }, + { opcode: 0xEA, block_boundary: 1, no_next_instruction: 1, os: 1, imm1632: 1, extra_imm16: 1, skip: 1, }, // jmpf + { opcode: 0xEB, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, no_next_instruction: 1, os: 1, imm8s: 1, custom: 1, skip: 1, }, + + { opcode: 0xEC, block_boundary: 1, skip: 1, }, // in + { opcode: 0xED, block_boundary: 1, os: 1, skip: 1, }, + { opcode: 0xEE, block_boundary: 1, skip: 1, }, // out + { opcode: 0xEF, block_boundary: 1, os: 1, skip: 1, }, + + { opcode: 0xF0, prefix: 1, }, + { opcode: 0xF1, skip: 1, }, + { opcode: 0xF2, prefix: 1, }, + { opcode: 0xF3, prefix: 1, }, + { opcode: 0xF4, block_boundary: 1, no_next_instruction: 1, skip: 1, }, // hlt + { opcode: 0xF5, }, + + { opcode: 0xF6, e: 1, fixed_g: 0, imm8: 1, custom: 1 }, + { opcode: 0xF6, e: 1, fixed_g: 1, imm8: 1, custom: 1 }, + { opcode: 0xF6, e: 1, fixed_g: 2, custom: 1 }, + { opcode: 0xF6, e: 1, fixed_g: 3, custom: 1 }, + { opcode: 0xF6, e: 1, fixed_g: 4, mask_flags: af | zf, }, + { opcode: 0xF6, e: 1, fixed_g: 5, mask_flags: af | zf, }, + { opcode: 0xF6, e: 1, fixed_g: 6, block_boundary: 1, }, // div/idiv: Not a block boundary, but doesn't use control flow exceptions + { opcode: 0xF6, e: 1, fixed_g: 7, block_boundary: 1, }, + + { opcode: 0xF7, os: 1, e: 1, fixed_g: 0, imm1632: 1, custom: 1 }, + { opcode: 0xF7, os: 1, e: 1, fixed_g: 1, imm1632: 1, custom: 1 }, + { opcode: 0xF7, os: 1, e: 1, fixed_g: 2, custom: 1 }, + { opcode: 0xF7, os: 1, e: 1, fixed_g: 3, custom: 1 }, + { opcode: 0xF7, os: 1, e: 1, fixed_g: 4, mask_flags: zf | af, custom: 1 }, + { opcode: 0xF7, os: 1, e: 1, fixed_g: 5, mask_flags: zf | af, custom: 1 }, + { opcode: 0xF7, os: 1, e: 1, fixed_g: 6, custom: 1 }, + { opcode: 0xF7, os: 1, e: 1, fixed_g: 7, custom: 1 }, + + { opcode: 0xF8, custom: 1 }, + { opcode: 0xF9, custom: 1 }, + { opcode: 0xFA, custom: 1, skip: 1 }, + // STI: Note: Has special handling in jit in order to call handle_irqs safely + { opcode: 0xFB, custom: 1, custom_sti: 1, skip: 1, }, + { opcode: 0xFC, custom: 1, }, + { opcode: 0xFD, custom: 1, }, + + { opcode: 0xFE, e: 1, fixed_g: 0, custom: 1 }, + { opcode: 0xFE, e: 1, fixed_g: 1, custom: 1 }, + { opcode: 0xFF, os: 1, e: 1, fixed_g: 0, custom: 1, }, + { opcode: 0xFF, os: 1, e: 1, fixed_g: 1, custom: 1, }, + { opcode: 0xFF, os: 1, e: 1, fixed_g: 2, custom: 1, block_boundary: 1, absolute_jump: 1, skip: 1, }, + { opcode: 0xFF, os: 1, e: 1, fixed_g: 3, block_boundary: 1, skip: 1, }, + { opcode: 0xFF, os: 1, e: 1, fixed_g: 4, custom: 1, block_boundary: 1, absolute_jump: 1, no_next_instruction: 1, skip: 1, }, + { opcode: 0xFF, os: 1, e: 1, fixed_g: 5, block_boundary: 1, no_next_instruction: 1, skip: 1, }, + { opcode: 0xFF, custom: 1, os: 1, e: 1, fixed_g: 6, }, + + { opcode: 0x0F00, fixed_g: 0, e: 1, skip: 1, block_boundary: 1, os: 1, }, // sldt, ... + { opcode: 0x0F00, fixed_g: 1, e: 1, skip: 1, block_boundary: 1, os: 1, }, + { opcode: 0x0F00, fixed_g: 2, e: 1, skip: 1, block_boundary: 1, os: 1, }, + { opcode: 0x0F00, fixed_g: 3, e: 1, skip: 1, block_boundary: 1, os: 1, }, + { opcode: 0x0F00, fixed_g: 4, e: 1, skip: 1, block_boundary: 1, os: 1, }, + { opcode: 0x0F00, fixed_g: 5, e: 1, skip: 1, block_boundary: 1, os: 1, }, + + { opcode: 0x0F01, fixed_g: 0, e: 1, skip: 1, block_boundary: 1, os: 1, }, // sgdt, ... + { opcode: 0x0F01, fixed_g: 1, e: 1, skip: 1, block_boundary: 1, os: 1, }, + { opcode: 0x0F01, fixed_g: 2, e: 1, skip: 1, block_boundary: 1, os: 1, }, + { opcode: 0x0F01, fixed_g: 3, e: 1, skip: 1, block_boundary: 1, os: 1, }, + { opcode: 0x0F01, fixed_g: 4, e: 1, skip: 1, block_boundary: 1, os: 1, }, + { opcode: 0x0F01, fixed_g: 6, e: 1, skip: 1, block_boundary: 1, os: 1, }, + { opcode: 0x0F01, fixed_g: 7, e: 1, skip: 1, block_boundary: 1, os: 1, }, + + { opcode: 0x0F02, os: 1, e: 1, skip: 1, block_boundary: 1, }, // lar + { opcode: 0x0F03, os: 1, e: 1, skip: 1, block_boundary: 1, }, // lsl + { opcode: 0x0F04, skip: 1, block_boundary: 1, }, + { opcode: 0x0F05, skip: 1, block_boundary: 1, }, + { opcode: 0x0F06, skip: 1, block_boundary: 1, }, // clts + { opcode: 0x0F07, skip: 1, block_boundary: 1, }, + { opcode: 0x0F08, skip: 1, block_boundary: 1, }, + { opcode: 0x0F09, skip: 1, block_boundary: 1, }, // wbinvd + { opcode: 0x0F0A, skip: 1, block_boundary: 1, }, + // ud2 + // Technically has a next instruction, but Linux uses this for assertions + // and embeds the assertion message after this instruction, which is likely + // the most common use case of ud2 + { opcode: 0x0F0B, skip: 1, block_boundary: 1, custom: 1, no_next_instruction: 1, }, + { opcode: 0x0F0C, skip: 1, block_boundary: 1, }, + { opcode: 0x0F0D, skip: 1, block_boundary: 1, }, + { opcode: 0x0F0E, skip: 1, block_boundary: 1, }, + { opcode: 0x0F0F, skip: 1, block_boundary: 1, }, + + { opcode: 0x0F18, e: 1, custom: 1 }, + { opcode: 0x0F19, custom: 1, e: 1, }, + { opcode: 0x0F1A, skip: 1, block_boundary: 1, }, + { opcode: 0x0F1B, skip: 1, block_boundary: 1, }, + { opcode: 0x0F1C, custom: 1, e: 1, }, + { opcode: 0x0F1D, custom: 1, e: 1, }, + { opcode: 0x0F1E, custom: 1, e: 1, }, + { opcode: 0x0F1F, custom: 1, e: 1, }, + + { opcode: 0x0F20, ignore_mod: 1, e: 1, skip: 1, block_boundary: 1, }, // mov reg, creg + { opcode: 0x0F21, ignore_mod: 1, e: 1, skip: 1, block_boundary: 1, }, // mov reg, dreg + { opcode: 0x0F22, ignore_mod: 1, e: 1, skip: 1, block_boundary: 1, }, // mov creg, reg + { opcode: 0x0F23, ignore_mod: 1, e: 1, skip: 1, block_boundary: 1, }, // mov dreg, reg + { opcode: 0x0F24, skip: 1, block_boundary: 1, }, + { opcode: 0x0F25, skip: 1, block_boundary: 1, }, + { opcode: 0x0F26, skip: 1, block_boundary: 1, }, + { opcode: 0x0F27, skip: 1, block_boundary: 1, }, + + { opcode: 0x0F30, skip: 1, block_boundary: 1, }, // wrmsr + { opcode: 0x0F31, skip: 1, custom: 1, }, // rdtsc + { opcode: 0x0F32, skip: 1, block_boundary: 1, }, // rdmsr + { opcode: 0x0F33, skip: 1, block_boundary: 1, }, // rdpmc + { opcode: 0x0F34, skip: 1, block_boundary: 1, no_next_instruction: 1, }, // sysenter + { opcode: 0x0F35, skip: 1, block_boundary: 1, no_next_instruction: 1, }, // sysexit + + { opcode: 0x0F36, skip: 1, block_boundary: 1, }, // ud + { opcode: 0x0F37, skip: 1, block_boundary: 1, }, // getsec + + // sse3+ + { opcode: 0x0F38, skip: 1, block_boundary: 1, }, + { opcode: 0x0F39, skip: 1, block_boundary: 1, }, + { opcode: 0x0F3A, skip: 1, block_boundary: 1, }, + { opcode: 0x0F3B, skip: 1, block_boundary: 1, }, + { opcode: 0x0F3C, skip: 1, block_boundary: 1, }, + { opcode: 0x0F3D, skip: 1, block_boundary: 1, }, + { opcode: 0x0F3E, skip: 1, block_boundary: 1, }, + { opcode: 0x0F3F, skip: 1, block_boundary: 1, }, + + { opcode: 0x0F40, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F41, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F42, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F43, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F44, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F45, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F46, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F47, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F48, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F49, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F4A, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F4B, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F4C, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F4D, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F4E, e: 1, os: 1, custom: 1, }, + { opcode: 0x0F4F, e: 1, os: 1, custom: 1, }, + + { opcode: 0x0F80, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F81, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F82, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F83, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F84, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F85, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F86, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F87, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F88, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F89, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F8A, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F8B, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F8C, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F8D, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F8E, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + { opcode: 0x0F8F, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, imm1632: 1, os: 1, custom: 1, skip: 1, }, + + { opcode: 0x0F90, e: 1, custom: 1, }, + { opcode: 0x0F91, e: 1, custom: 1, }, + { opcode: 0x0F92, e: 1, custom: 1, }, + { opcode: 0x0F93, e: 1, custom: 1, }, + { opcode: 0x0F94, e: 1, custom: 1, }, + { opcode: 0x0F95, e: 1, custom: 1, }, + { opcode: 0x0F96, e: 1, custom: 1, }, + { opcode: 0x0F97, e: 1, custom: 1, }, + { opcode: 0x0F98, e: 1, custom: 1, }, + { opcode: 0x0F99, e: 1, custom: 1, }, + { opcode: 0x0F9A, e: 1, custom: 1, }, + { opcode: 0x0F9B, e: 1, custom: 1, }, + { opcode: 0x0F9C, e: 1, custom: 1, }, + { opcode: 0x0F9D, e: 1, custom: 1, }, + { opcode: 0x0F9E, e: 1, custom: 1, }, + { opcode: 0x0F9F, e: 1, custom: 1, }, + + { opcode: 0x0FA0, os: 1, custom: 1, }, + { opcode: 0x0FA1, os: 1, block_boundary: 1, skip: 1, }, // pop fs: block_boundary since it uses non-raising cpu exceptions + + { opcode: 0x0FA2, skip: 1, }, + + { opcode: 0x0FA8, os: 1, custom: 1, }, + { opcode: 0x0FA9, os: 1, block_boundary: 1, skip: 1, }, // pop gs + + { opcode: 0x0FA3, os: 1, e: 1, custom: 1, skip_mem: 1 }, // bt (can also index memory, but not supported by test right now) + { opcode: 0x0FAB, os: 1, e: 1, custom: 1, skip_mem: 1 }, + { opcode: 0x0FB3, os: 1, e: 1, custom: 1, skip_mem: 1 }, + { opcode: 0x0FBB, os: 1, e: 1, custom: 1, skip_mem: 1 }, + + { opcode: 0x0FBA, os: 1, e: 1, fixed_g: 4, imm8: 1, custom: 1 }, // bt + { opcode: 0x0FBA, os: 1, e: 1, fixed_g: 5, imm8: 1, custom: 1 }, + { opcode: 0x0FBA, os: 1, e: 1, fixed_g: 6, imm8: 1, custom: 1 }, + { opcode: 0x0FBA, os: 1, e: 1, fixed_g: 7, imm8: 1, custom: 1 }, + + { opcode: 0x0FBC, os: 1, e: 1, mask_flags: af, custom: 1 }, // bsf + { opcode: 0x0FBD, os: 1, e: 1, mask_flags: af, custom: 1 }, + + // note: overflow flag only undefined if shift is > 1 + { opcode: 0x0FA4, os: 1, e: 1, custom: 1, imm8: 1, mask_flags: af | of, }, // shld + { opcode: 0x0FA5, os: 1, e: 1, custom: 1, mask_flags: af | of, }, + { opcode: 0x0FAC, os: 1, e: 1, custom: 1, imm8: 1, mask_flags: af | of, }, + { opcode: 0x0FAD, os: 1, e: 1, custom: 1, mask_flags: af | of, }, + + { opcode: 0x0FA6, skip: 1, block_boundary: 1, }, // ud + { opcode: 0x0FA7, skip: 1, block_boundary: 1, }, // ud + + { opcode: 0x0FAA, skip: 1 }, + + { opcode: 0x0FAE, e: 1, fixed_g: 0, reg_ud: 1, task_switch_test: 1, skip: 1, block_boundary: 1, }, // fxsave + { opcode: 0x0FAE, e: 1, fixed_g: 1, reg_ud: 1, task_switch_test: 1, skip: 1, block_boundary: 1, }, // fxrstor + { opcode: 0x0FAE, e: 1, fixed_g: 2, reg_ud: 1, sse: 1, skip: 1, block_boundary: 1, }, // ldmxcsr + { opcode: 0x0FAE, e: 1, fixed_g: 3, reg_ud: 1, sse: 1, skip: 1, block_boundary: 1, }, // stmxcsr + + { opcode: 0x0FAE, e: 1, fixed_g: 4, reg_ud: 1, skip: 1, block_boundary: 1, }, // xsave (mem, not implemented) + { opcode: 0x0FAE, e: 1, fixed_g: 5, skip: 1, custom: 1 }, // lfence (reg, only 0), xrstor (mem, not implemented) + { opcode: 0x0FAE, e: 1, fixed_g: 6, skip: 1, block_boundary: 1, }, // mfence (reg, only 0), xsaveopt (mem, not implemented) + { opcode: 0x0FAE, e: 1, fixed_g: 7, skip: 1, block_boundary: 1, }, // sfence (reg, only 0), clflush (mem) + + { opcode: 0x0FAF, os: 1, e: 1, mask_flags: af | zf, custom: 1, }, // imul + + { opcode: 0x0FB0, e: 1 }, // cmxchg + { opcode: 0x0FB1, os: 1, e: 1, custom: 1 }, + { opcode: 0x0FC7, e: 1, fixed_g: 1, os: 1, reg_ud: 1, custom: 1 }, // cmpxchg8b (memory) + { opcode: 0x0FC7, e: 1, fixed_g: 6, os: 1, mem_ud: 1, skip: 1, }, // rdrand + + { opcode: 0x0FB2, block_boundary: 1, os: 1, e: 1, skip: 1, }, // lss + { opcode: 0x0FB4, block_boundary: 1, os: 1, e: 1, skip: 1, }, // lfs + { opcode: 0x0FB5, block_boundary: 1, os: 1, e: 1, skip: 1, }, // lgs + + { opcode: 0x0FB6, os: 1, e: 1, custom: 1 }, // movzx + { opcode: 0x0FB7, os: 1, e: 1, custom: 1 }, + + { opcode: 0xF30FB8, os: 1, e: 1, custom: 1 }, // popcnt + { opcode: 0x0FB8, os: 1, e: 1, block_boundary: 1, }, // ud + + { opcode: 0x0FB9, block_boundary: 1, }, // ud2 + + { opcode: 0x0FBE, os: 1, e: 1, custom: 1 }, // movsx + { opcode: 0x0FBF, os: 1, e: 1, custom: 1 }, + + { opcode: 0x0FC0, e: 1, }, // xadd + { opcode: 0x0FC1, os: 1, e: 1, custom: 1 }, + + { opcode: 0x0FC8, custom: 1 }, // bswap + { opcode: 0x0FC9, custom: 1 }, + { opcode: 0x0FCA, custom: 1 }, + { opcode: 0x0FCB, custom: 1 }, + { opcode: 0x0FCC, custom: 1 }, + { opcode: 0x0FCD, custom: 1 }, + { opcode: 0x0FCE, custom: 1 }, + { opcode: 0x0FCF, custom: 1 }, + + + // mmx, sse + // - skipped or missing are sse3+ + + { sse: 1, opcode: 0x0F10, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F10, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F10, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F10, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F11, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F11, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F11, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F11, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F12, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F12, reg_ud: 1, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F12, e: 1, skip: 1, block_boundary: 1, }, // sse3 + { sse: 1, opcode: 0xF30F12, e: 1, skip: 1, block_boundary: 1, }, // sse3 + { sse: 1, opcode: 0x0F13, reg_ud: 1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F13, reg_ud: 1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F14, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F14, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F15, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F15, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F16, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F16, reg_ud: 1, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F16, skip: 1, e: 1, block_boundary: 1, }, // sse3 + { sse: 1, opcode: 0x0F17, reg_ud: 1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F17, reg_ud: 1, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F28, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F28, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F29, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F29, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F2A, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F2A, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F2A, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F2A, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F2B, reg_ud: 1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F2B, reg_ud: 1, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F2C, e: 1, }, + { sse: 1, opcode: 0x660F2C, e: 1, }, + { sse: 1, opcode: 0xF20F2C, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F2C, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F2D, e: 1, }, + { sse: 1, opcode: 0x660F2D, e: 1, }, + { sse: 1, opcode: 0xF20F2D, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F2D, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F2E, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F2E, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F2F, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F2F, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F50, mem_ud: 1, e: 1 }, + { sse: 1, opcode: 0x660F50, mem_ud: 1, e: 1 }, + { sse: 1, opcode: 0x0F51, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F51, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F51, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F51, e: 1, custom: 1 }, + + // approximation of 1/sqrt(x). Skipped because our approximation doesn't match intel's + { sse: 1, opcode: 0x0F52, e: 1, skip: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F52, e: 1, skip: 1, custom: 1 }, + + // reciprocal: approximation of 1/x. Skipped because our approximation doesn't match intel's + { sse: 1, opcode: 0x0F53, e: 1, skip: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F53, e: 1, skip: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F54, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F54, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F55, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F55, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F56, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F56, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F57, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F57, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F58, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F58, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F58, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F58, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F59, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F59, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F59, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F59, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F5A, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F5A, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F5A, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F5A, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F5B, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F5B, e: 1, custom: 1 }, + // no F2 variant + { sse: 1, opcode: 0xF30F5B, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F5C, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F5C, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F5C, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F5C, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F5D, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F5D, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F5D, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F5D, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F5E, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F5E, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F5E, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F5E, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F5F, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F5F, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F5F, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F5F, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x660F60, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F60, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F61, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F61, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F62, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F62, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F63, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F63, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F64, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F64, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F65, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F65, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F66, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F66, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F67, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F67, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x660F68, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F68, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F69, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F69, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F6A, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F6A, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F6B, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F6B, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F6C, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F6C, e: 1, block_boundary: 1, }, // ud + { sse: 1, opcode: 0x660F6D, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F6D, e: 1, block_boundary: 1, }, // ud + { sse: 1, opcode: 0x660F6E, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F6E, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F6F, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F6F, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F6F, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F70, e: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0x660F70, e: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0xF20F70, e: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F70, e: 1, imm8: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F71, e: 1, fixed_g: 2, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F71, e: 1, fixed_g: 2, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x0F71, e: 1, fixed_g: 4, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F71, e: 1, fixed_g: 4, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x0F71, e: 1, fixed_g: 6, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F71, e: 1, fixed_g: 6, imm8: 1, mem_ud: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F72, e: 1, fixed_g: 2, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F72, e: 1, fixed_g: 2, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x0F72, e: 1, fixed_g: 4, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F72, e: 1, fixed_g: 4, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x0F72, e: 1, fixed_g: 6, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F72, e: 1, fixed_g: 6, imm8: 1, mem_ud: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F73, e: 1, fixed_g: 2, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F73, e: 1, fixed_g: 2, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F73, e: 1, fixed_g: 3, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x0F73, e: 1, fixed_g: 6, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F73, e: 1, fixed_g: 6, imm8: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660F73, e: 1, fixed_g: 7, imm8: 1, mem_ud: 1, custom: 1 }, + + { sse: 1, opcode: 0x0F74, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F74, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F75, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F75, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F76, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F76, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F77, skip: 1 }, // emms (skip as it breaks gdb printing of float registers) + + // vmx instructions + { opcode: 0x0F78, skip: 1, block_boundary: 1, }, + { opcode: 0x0F79, skip: 1, block_boundary: 1, }, + + { opcode: 0x0F7A, skip: 1, block_boundary: 1, }, // ud + { opcode: 0x0F7B, skip: 1, block_boundary: 1, }, // ud + { sse: 1, opcode: 0x0F7C, skip: 1, block_boundary: 1, }, // sse3 + { sse: 1, opcode: 0x0F7D, skip: 1, block_boundary: 1, }, // sse3 + + { sse: 1, opcode: 0x0F7E, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F7E, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F7E, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0F7F, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660F7F, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30F7F, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0FC2, e: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0x660FC2, e: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0xF20FC2, e: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0xF30FC2, e: 1, imm8: 1, custom: 1 }, + + { opcode: 0x0FC3, e: 1, custom: 1, reg_ud: 1, }, // movnti: Uses normal registers, hence not marked as sse + + { sse: 1, opcode: 0x0FC4, e: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0x660FC4, e: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0x0FC5, e: 1, mem_ud: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0x660FC5, e: 1, mem_ud: 1, imm8: 1, custom: 1 }, + + { sse: 1, opcode: 0x0FC6, e: 1, imm8: 1, custom: 1 }, + { sse: 1, opcode: 0x660FC6, e: 1, imm8: 1, custom: 1 }, + + { sse: 1, opcode: 0x0FD0, skip: 1, block_boundary: 1, }, // sse3 + + { sse: 1, opcode: 0x0FD1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FD1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FD2, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FD2, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FD3, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FD3, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FD4, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FD4, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FD5, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FD5, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x660FD6, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20FD6, mem_ud: 1, e: 1 }, + { sse: 1, opcode: 0xF30FD6, mem_ud: 1, e: 1 }, + { sse: 1, opcode: 0x0FD6, e: 1, block_boundary: 1, }, // ud + + { sse: 1, opcode: 0x0FD7, e: 1, mem_ud: 1, custom: 1 }, + { sse: 1, opcode: 0x660FD7, e: 1, mem_ud: 1, custom: 1 }, + + { sse: 1, opcode: 0x0FD8, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FD8, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FD9, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FD9, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FDA, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FDA, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FDB, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FDB, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FDC, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FDC, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FDD, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FDD, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FDE, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FDE, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FDF, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FDF, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0FE0, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FE0, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FE1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FE1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FE2, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FE2, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FE3, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FE3, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FE4, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FE4, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FE5, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FE5, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x660FE6, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF20FE6, e: 1, custom: 1 }, + { sse: 1, opcode: 0xF30FE6, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FE6, e: 1, block_boundary: 1, }, // ud + { sse: 1, opcode: 0x0FE7, e: 1, reg_ud: 1 }, + { sse: 1, opcode: 0x660FE7, e: 1, reg_ud: 1, custom: 1 }, + + { sse: 1, opcode: 0x0FE8, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FE8, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FE9, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FE9, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FEA, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FEA, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FEB, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FEB, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FEC, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FEC, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FED, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FED, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FEE, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FEE, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FEF, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FEF, e: 1, custom: 1 }, + + { sse: 1, opcode: 0x0FF0, skip: 1, block_boundary: 1, }, // sse3 + + { sse: 1, opcode: 0x0FF1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FF1, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FF2, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FF2, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FF3, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FF3, e: 1, custom: 1, }, + { sse: 1, opcode: 0x0FF4, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FF4, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FF5, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FF5, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FF6, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FF6, e: 1, custom: 1 }, + // maskmovq (0FF7), maskmovdqu (660FF7) tested manually + // Generated tests don't setup EDI as required (yet) + { sse: 1, opcode: 0x0FF7, mem_ud: 1, e: 1, custom: 1, skip: 1, }, + { sse: 1, opcode: 0x660FF7, mem_ud: 1, e: 1, custom: 1, skip: 1, }, + + { sse: 1, opcode: 0x0FF8, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FF8, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FF9, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FF9, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FFA, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FFA, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FFB, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FFB, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FFC, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FFC, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FFD, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FFD, e: 1, custom: 1 }, + { sse: 1, opcode: 0x0FFE, e: 1, custom: 1 }, + { sse: 1, opcode: 0x660FFE, e: 1, custom: 1 }, + + { opcode: 0x0FFF, block_boundary: 1, }, // ud +]; + +for(let i = 0; i < 8; i++) +{ + encodings.push.apply(encodings, [ + { opcode: 0x04 | i << 3, custom: 1, imm8: 1, }, + { opcode: 0x05 | i << 3, custom: 1, os: 1, imm1632: 1, }, + + { opcode: 0x70 | i, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, os: 1, imm8s: 1, custom: 1, skip: 1, }, + { opcode: 0x78 | i, block_boundary: 1, no_block_boundary_in_interpreted: 1, jump_offset_imm: 1, conditional_jump: 1, os: 1, imm8s: 1, custom: 1, skip: 1, }, + + { opcode: 0x80, e: 1, fixed_g: i, imm8: 1, custom: 1, }, + { opcode: 0x81, os: 1, e: 1, fixed_g: i, imm1632: 1, custom: 1, }, + { opcode: 0x82, e: 1, fixed_g: i, imm8: 1, custom: 1, }, + { opcode: 0x83, os: 1, e: 1, fixed_g: i, imm8s: 1, custom: 1, }, + + { opcode: 0xB0 | i, custom: 1, imm8: 1, }, + { opcode: 0xB8 | i, custom: 1, os: 1, imm1632: 1, }, + + // note: overflow flag only undefined if shift is > 1 + // note: the adjust flag is undefined for shifts > 0 and unaffected by rotates + { opcode: 0xC0, e: 1, fixed_g: i, imm8: 1, mask_flags: of | af, custom: 1, }, + { opcode: 0xC1, os: 1, e: 1, fixed_g: i, imm8: 1, mask_flags: of | af, custom: 1, }, + { opcode: 0xD0, e: 1, fixed_g: i, mask_flags: af, custom: 1 }, + { opcode: 0xD1, os: 1, e: 1, fixed_g: i, mask_flags: af, custom: 1, }, + { opcode: 0xD2, e: 1, fixed_g: i, mask_flags: of | af, custom: 1 }, + { opcode: 0xD3, os: 1, e: 1, fixed_g: i, mask_flags: of | af, custom: 1, }, + ]); +} + +encodings.sort((e1, e2) => { + let o1 = (e1.opcode & 0xFF00) === 0x0F00 ? e1.opcode & 0xFFFF : e1.opcode & 0xFF; + let o2 = (e2.opcode & 0xFF00) === 0x0F00 ? e2.opcode & 0xFFFF : e2.opcode & 0xFF; + return o1 - o2 || e1.fixed_g - e2.fixed_g; +}); + +module.exports = Object.freeze(encodings.map(entry => Object.freeze(entry))); diff --git a/index.html b/index.html new file mode 100644 index 0000000..5d78c03 --- /dev/null +++ b/index.html @@ -0,0 +1,290 @@ + + + +Virtual x86 + + + + + + +
+
+

Select profile

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Arch Linux 12 MB + A complete Arch Linux restored from a snapshot, additional files are loaded as needed
Damn Small Linux 50 MB + Graphical Linux with 2.4 kernel, Firefox 2.0 and more. Takes 1 minute to boot.
Buildroot Linux 5.0 MB + Minimal Linux with busybox, Lua, tests, internet access, ping, telnet and curl. Exchange files through /mnt/.
ReactOS 18 MB + Windows-compatible OS. Restored from snapshot
Windows 2000 22 MB + Including Pinball and Internet Explorer with internet access. Additional sectors are loaded as needed.
Windows 98 9.7 MB + Including Minesweeper and Internet Explorer with internet access. Additional sectors are loaded as needed.
Windows 95 4.6 MB + Restored from snapshot
Windows 3.1 15 MB + Takes 15 seconds to boot
Windows 1.01 0.6 MB + Takes 1 second to boot
MS-DOS 6.22 4.4 MB + With Enhanced Tools, QBasic, vim, games and demos.
FreeDOS 0.5 MB + With nasm, vim, debug.com, Rogue, some games and demos.
FreeBSD 17 MB + FreeBSD 12.0 base install. Restored from snapshot.
OpenBSD 12 MB + OpenBSD 6.6 base install. Restored from snapshot.
9front 4.4 MB + A Plan 9 fork.
Haiku 46 MB + An open-source operating system inspired by BeOS. Restored from snapshot. Includes network support.
SerenityOS 11 MB + A graphical Unix-like operating system. Restored from snapshot.
HelenOS 7.9 MB + A graphical operating system based on a multiserver microkernel design
Android-x86 42 MB + An x86 port of the Android Open Source Project, version 1.6. Quite slow. Takes about 10 minutes to boot.
Oberon 1.2 MB + Native Oberon 2.3.6
KolibriOS 1.4 MB + Fast graphical OS written in Assembly
QNX 1.3 MB + QNX 4.05 Demo disk (no networking)
Snowdrop 0.3 MB + A homebrew operating system from scratch, written in assembly language
Solar OS 0.3 MB + Simple graphical OS
Bootchess 512 B + A tiny chess program written in the boot sector
SectorLISP 512 B + A LISP interpreter that fits into the boot sector
+ +
+

Setup

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +




Disk images are not uploaded to the server
+ MB
+
+ MB
+
+ +

+
+
+
+

+ +
+ +
+ +
+ + + +
+ + + + + + + + +

+ +
+ +
+Version: 98e7110c2 (Feb 16, 2021 12:02) + +
+Enable debug +— +Readme +— +Project on Github +— +Compatibility diff --git a/lib/9p.js b/lib/9p.js new file mode 100644 index 0000000..645632c --- /dev/null +++ b/lib/9p.js @@ -0,0 +1,856 @@ +// ------------------------------------------------- +// --------------------- 9P ------------------------ +// ------------------------------------------------- +// Implementation of the 9p filesystem device following the +// 9P2000.L protocol ( https://code.google.com/p/diod/wiki/protocol ) + +"use strict"; + +// Feature bit (bit position) for mount tag. +const VIRTIO_9P_F_MOUNT_TAG = 0; +// Assumed max tag length in bytes. +const VIRTIO_9P_MAX_TAGLEN = 254; + +// TODO +// flush + +var EPERM = 1; /* Operation not permitted */ +var ENOENT = 2; /* No such file or directory */ +var EEXIST = 17; /* File exists */ +var EINVAL = 22; /* Invalid argument */ +var EOPNOTSUPP = 95; /* Operation is not supported */ +var ENOTEMPTY = 39; /* Directory not empty */ +var EPROTO = 71; /* Protocol error */ + +var P9_SETATTR_MODE = 0x00000001; +var P9_SETATTR_UID = 0x00000002; +var P9_SETATTR_GID = 0x00000004; +var P9_SETATTR_SIZE = 0x00000008; +var P9_SETATTR_ATIME = 0x00000010; +var P9_SETATTR_MTIME = 0x00000020; +var P9_SETATTR_CTIME = 0x00000040; +var P9_SETATTR_ATIME_SET = 0x00000080; +var P9_SETATTR_MTIME_SET = 0x00000100; + +var P9_STAT_MODE_DIR = 0x80000000; +var P9_STAT_MODE_APPEND = 0x40000000; +var P9_STAT_MODE_EXCL = 0x20000000; +var P9_STAT_MODE_MOUNT = 0x10000000; +var P9_STAT_MODE_AUTH = 0x08000000; +var P9_STAT_MODE_TMP = 0x04000000; +var P9_STAT_MODE_SYMLINK = 0x02000000; +var P9_STAT_MODE_LINK = 0x01000000; +var P9_STAT_MODE_DEVICE = 0x00800000; +var P9_STAT_MODE_NAMED_PIPE = 0x00200000; +var P9_STAT_MODE_SOCKET = 0x00100000; +var P9_STAT_MODE_SETUID = 0x00080000; +var P9_STAT_MODE_SETGID = 0x00040000; +var P9_STAT_MODE_SETVTX = 0x00010000; + +const P9_LOCK_TYPE_RDLCK = 0; +const P9_LOCK_TYPE_WRLCK = 1; +const P9_LOCK_TYPE_UNLCK = 2; +const P9_LOCK_TYPES = Object.freeze(["shared", "exclusive", "unlock"]); + +const P9_LOCK_FLAGS_BLOCK = 1; +const P9_LOCK_FLAGS_RECLAIM = 2; + +const P9_LOCK_SUCCESS = 0; +const P9_LOCK_BLOCKED = 1; +const P9_LOCK_ERROR = 2; +const P9_LOCK_GRACE = 3; + +var FID_NONE = -1; +var FID_INODE = 1; +var FID_XATTR = 2; + +/** + * @constructor + * + * @param {FS} filesystem + * @param {CPU} cpu + */ +function Virtio9p(filesystem, cpu, bus) { + /** @type {FS} */ + this.fs = filesystem; + + /** @const @type {BusConnector} */ + this.bus = bus; + + //this.configspace = [0x0, 0x4, 0x68, 0x6F, 0x73, 0x74]; // length of string and "host" string + //this.configspace = [0x0, 0x9, 0x2F, 0x64, 0x65, 0x76, 0x2F, 0x72, 0x6F, 0x6F, 0x74 ]; // length of string and "/dev/root" string + this.configspace_tagname = [0x68, 0x6F, 0x73, 0x74, 0x39, 0x70]; // "host9p" string + this.configspace_taglen = this.configspace_tagname.length; // num bytes + this.VERSION = "9P2000.L"; + this.BLOCKSIZE = 8192; // Let's define one page. + this.msize = 8192; // maximum message size + this.replybuffer = new Uint8Array(this.msize*2); // Twice the msize to stay on the safe site + this.replybuffersize = 0; + + this.fids = []; + + /** @type {VirtIO} */ + this.virtio = new VirtIO(cpu, + { + name: "virtio-9p", + pci_id: 0x06 << 3, + device_id: 0x1049, + subsystem_device_id: 9, + common: + { + initial_port: 0xA800, + queues: + [ + { + size_supported: 32, + notify_offset: 0, + }, + ], + features: + [ + VIRTIO_9P_F_MOUNT_TAG, + VIRTIO_F_VERSION_1, + VIRTIO_F_RING_EVENT_IDX, + VIRTIO_F_RING_INDIRECT_DESC, + ], + on_driver_ok: () => {}, + }, + notification: + { + initial_port: 0xA900, + single_handler: false, + handlers: + [ + (queue_id) => + { + if(queue_id !== 0) + { + dbg_assert(false, "Virtio9P Notified for non-existent queue: " + queue_id + + " (expected queue_id of 0)"); + return; + } + while(this.virtqueue.has_request()) + { + const bufchain = this.virtqueue.pop_request(); + this.ReceiveRequest(bufchain); + } + this.virtqueue.notify_me_after(0); + // Don't flush replies here: async replies are not completed yet. + }, + ], + }, + isr_status: + { + initial_port: 0xA700, + }, + device_specific: + { + initial_port: 0xA600, + struct: + [ + { + bytes: 2, + name: "mount tag length", + read: () => this.configspace_taglen, + write: data => { /* read only */ }, + }, + ].concat(v86util.range(VIRTIO_9P_MAX_TAGLEN).map(index => + ({ + bytes: 1, + name: "mount tag name " + index, + // Note: configspace_tagname may have changed after set_state + read: () => this.configspace_tagname[index] || 0, + write: data => { /* read only */ }, + }) + )), + }, + }); + this.virtqueue = this.virtio.queues[0]; +} + +Virtio9p.prototype.get_state = function() +{ + var state = []; + + state[0] = this.configspace_tagname; + state[1] = this.configspace_taglen; + state[2] = this.virtio; + state[3] = this.VERSION; + state[4] = this.BLOCKSIZE; + state[5] = this.msize; + state[6] = this.replybuffer; + state[7] = this.replybuffersize; + state[8] = this.fids.map(function(f) { return [f.inodeid, f.type, f.uid, f.dbg_name]; }); + state[9] = this.fs; + + return state; +}; + +Virtio9p.prototype.set_state = function(state) +{ + this.configspace_tagname = state[0]; + this.configspace_taglen = state[1]; + this.virtio.set_state(state[2]); + this.virtqueue = this.virtio.queues[0]; + this.VERSION = state[3]; + this.BLOCKSIZE = state[4]; + this.msize = state[5]; + this.replybuffer = state[6]; + this.replybuffersize = state[7]; + this.fids = state[8].map(function(f) + { + return { inodeid: f[0], type: f[1], uid: f[2], dbg_name: f[3] }; + }); + this.fs.set_state(state[9]); +}; + +// Note: dbg_name is only used for debugging messages and may not be the same as the filename, +// since it is not synchronised with renames done outside of 9p. Hard-links, linking and unlinking +// operations also mean that having a single filename no longer makes sense. +// Set TRACK_FILENAMES = true (in config.js) to sync dbg_name during 9p renames. +Virtio9p.prototype.Createfid = function(inodeid, type, uid, dbg_name) { + return {inodeid, type, uid, dbg_name}; +}; + +Virtio9p.prototype.update_dbg_name = function(idx, newname) +{ + for(const fid of this.fids) + { + if(fid.inodeid === idx) fid.dbg_name = newname; + } +}; + +Virtio9p.prototype.Reset = function() { + this.fids = []; +}; + + +Virtio9p.prototype.BuildReply = function(id, tag, payloadsize) { + dbg_assert(payloadsize >= 0, "9P: Negative payload size"); + marshall.Marshall(["w", "b", "h"], [payloadsize+7, id+1, tag], this.replybuffer, 0); + if ((payloadsize+7) >= this.replybuffer.length) { + message.Debug("Error in 9p: payloadsize exceeds maximum length"); + } + //for(var i=0; i= 0, "9P: Negative replybuffersize"); + bufchain.set_next_blob(this.replybuffer.subarray(0, this.replybuffersize)); + this.virtqueue.push_reply(bufchain); + this.virtqueue.flush_replies(); +}; + +Virtio9p.prototype.ReceiveRequest = async function (bufchain) { + // TODO: split into header + data blobs to avoid unnecessary copying. + const buffer = new Uint8Array(bufchain.length_readable); + bufchain.get_next_blob(buffer); + + const state = { offset : 0 }; + var header = marshall.Unmarshall(["w", "b", "h"], buffer, state); + var size = header[0]; + var id = header[1]; + var tag = header[2]; + //message.Debug("size:" + size + " id:" + id + " tag:" + tag); + + switch(id) + { + case 8: // statfs + size = this.fs.GetTotalSize(); // size used by all files + var space = this.fs.GetSpace(); + var req = []; + req[0] = 0x01021997; + req[1] = this.BLOCKSIZE; // optimal transfer block size + req[2] = Math.floor(space/req[1]); // free blocks + req[3] = req[2] - Math.floor(size/req[1]); // free blocks in fs + req[4] = req[2] - Math.floor(size/req[1]); // free blocks avail to non-superuser + req[5] = this.fs.CountUsedInodes(); // total number of inodes + req[6] = this.fs.CountFreeInodes(); + req[7] = 0; // file system id? + req[8] = 256; // maximum length of filenames + + size = marshall.Marshall(["w", "w", "d", "d", "d", "d", "d", "d", "w"], req, this.replybuffer, 7); + this.BuildReply(id, tag, size); + this.SendReply(bufchain); + break; + + case 112: // topen + case 12: // tlopen + var req = marshall.Unmarshall(["w", "w"], buffer, state); + var fid = req[0]; + var mode = req[1]; + message.Debug("[open] fid=" + fid + ", mode=" + mode); + var idx = this.fids[fid].inodeid; + var inode = this.fs.GetInode(idx); + message.Debug("file open " + this.fids[fid].dbg_name); + //if (inode.status == STATUS_LOADING) return; + var ret = this.fs.OpenInode(idx, mode); + + this.fs.AddEvent(this.fids[fid].inodeid, + function() { + message.Debug("file opened " + this.fids[fid].dbg_name + " tag:"+tag); + var req = []; + req[0] = inode.qid; + req[1] = this.msize - 24; + marshall.Marshall(["Q", "w"], req, this.replybuffer, 7); + this.BuildReply(id, tag, 13+4); + this.SendReply(bufchain); + }.bind(this) + ); + break; + + case 70: // link + var req = marshall.Unmarshall(["w", "w", "s"], buffer, state); + var dfid = req[0]; + var fid = req[1]; + var name = req[2]; + message.Debug("[link] dfid=" + dfid + ", name=" + name); + + var ret = this.fs.Link(this.fids[dfid].inodeid, this.fids[fid].inodeid, name); + + if(ret < 0) + { + let error_message = ""; + if(ret === -EPERM) error_message = "Operation not permitted"; + else + { + error_message = "Unknown error: " + (-ret); + dbg_assert(false, "[link]: Unexpected error code: " + (-ret)); + } + this.SendError(tag, error_message, -ret); + this.SendReply(bufchain); + break; + } + + this.BuildReply(id, tag, 0); + this.SendReply(bufchain); + break; + + case 16: // symlink + var req = marshall.Unmarshall(["w", "s", "s", "w"], buffer, state); + var fid = req[0]; + var name = req[1]; + var symgt = req[2]; + var gid = req[3]; + message.Debug("[symlink] fid=" + fid + ", name=" + name + ", symgt=" + symgt + ", gid=" + gid); + var idx = this.fs.CreateSymlink(name, this.fids[fid].inodeid, symgt); + var inode = this.fs.GetInode(idx); + inode.uid = this.fids[fid].uid; + inode.gid = gid; + marshall.Marshall(["Q"], [inode.qid], this.replybuffer, 7); + this.BuildReply(id, tag, 13); + this.SendReply(bufchain); + break; + + case 18: // mknod + var req = marshall.Unmarshall(["w", "s", "w", "w", "w", "w"], buffer, state); + var fid = req[0]; + var name = req[1]; + var mode = req[2]; + var major = req[3]; + var minor = req[4]; + var gid = req[5]; + message.Debug("[mknod] fid=" + fid + ", name=" + name + ", major=" + major + ", minor=" + minor+ ""); + var idx = this.fs.CreateNode(name, this.fids[fid].inodeid, major, minor); + var inode = this.fs.GetInode(idx); + inode.mode = mode; + inode.uid = this.fids[fid].uid; + inode.gid = gid; + marshall.Marshall(["Q"], [inode.qid], this.replybuffer, 7); + this.BuildReply(id, tag, 13); + this.SendReply(bufchain); + break; + + + case 22: // TREADLINK + var req = marshall.Unmarshall(["w"], buffer, state); + var fid = req[0]; + var inode = this.fs.GetInode(this.fids[fid].inodeid); + message.Debug("[readlink] fid=" + fid + " name=" + this.fids[fid].dbg_name + " target=" + inode.symlink); + size = marshall.Marshall(["s"], [inode.symlink], this.replybuffer, 7); + this.BuildReply(id, tag, size); + this.SendReply(bufchain); + break; + + + case 72: // tmkdir + var req = marshall.Unmarshall(["w", "s", "w", "w"], buffer, state); + var fid = req[0]; + var name = req[1]; + var mode = req[2]; + var gid = req[3]; + message.Debug("[mkdir] fid=" + fid + ", name=" + name + ", mode=" + mode + ", gid=" + gid); + var idx = this.fs.CreateDirectory(name, this.fids[fid].inodeid); + var inode = this.fs.GetInode(idx); + inode.mode = mode | S_IFDIR; + inode.uid = this.fids[fid].uid; + inode.gid = gid; + marshall.Marshall(["Q"], [inode.qid], this.replybuffer, 7); + this.BuildReply(id, tag, 13); + this.SendReply(bufchain); + break; + + case 14: // tlcreate + var req = marshall.Unmarshall(["w", "s", "w", "w", "w"], buffer, state); + var fid = req[0]; + var name = req[1]; + var flags = req[2]; + var mode = req[3]; + var gid = req[4]; + this.bus.send("9p-create", [name, this.fids[fid].inodeid]); + message.Debug("[create] fid=" + fid + ", name=" + name + ", flags=" + flags + ", mode=" + mode + ", gid=" + gid); + var idx = this.fs.CreateFile(name, this.fids[fid].inodeid); + this.fids[fid].inodeid = idx; + this.fids[fid].type = FID_INODE; + this.fids[fid].dbg_name = name; + var inode = this.fs.GetInode(idx); + inode.uid = this.fids[fid].uid; + inode.gid = gid; + inode.mode = mode; + marshall.Marshall(["Q", "w"], [inode.qid, this.msize - 24], this.replybuffer, 7); + this.BuildReply(id, tag, 13+4); + this.SendReply(bufchain); + break; + + case 52: // lock + var req = marshall.Unmarshall(["w", "b", "w", "d", "d", "w", "s"], buffer, state); + var fid = req[0]; + var flags = req[2]; + var lock_length = req[4] === 0 ? Infinity : req[4]; + var lock_request = this.fs.DescribeLock(req[1], req[3], lock_length, req[5], req[6]); + message.Debug("[lock] fid=" + fid + + ", type=" + P9_LOCK_TYPES[lock_request.type] + ", start=" + lock_request.start + + ", length=" + lock_request.length + ", proc_id=" + lock_request.proc_id); + + var ret = this.fs.Lock(this.fids[fid].inodeid, lock_request, flags); + + marshall.Marshall(["b"], [ret], this.replybuffer, 7); + this.BuildReply(id, tag, 1); + this.SendReply(bufchain); + break; + + case 54: // getlock + var req = marshall.Unmarshall(["w", "b", "d", "d", "w", "s"], buffer, state); + var fid = req[0]; + var lock_length = req[3] === 0 ? Infinity : req[3]; + var lock_request = this.fs.DescribeLock(req[1], req[2], lock_length, req[4], req[5]); + message.Debug("[getlock] fid=" + fid + + ", type=" + P9_LOCK_TYPES[lock_request.type] + ", start=" + lock_request.start + + ", length=" + lock_request.length + ", proc_id=" + lock_request.proc_id); + + var ret = this.fs.GetLock(this.fids[fid].inodeid, lock_request); + + if(!ret) + { + ret = lock_request; + ret.type = P9_LOCK_TYPE_UNLCK; + } + + var ret_length = ret.length === Infinity ? 0 : ret.length; + + size = marshall.Marshall(["b", "d", "d", "w", "s"], + [ret.type, ret.start, ret_length, ret.proc_id, ret.client_id], + this.replybuffer, 7); + + this.BuildReply(id, tag, size); + this.SendReply(bufchain); + break; + + case 24: // getattr + var req = marshall.Unmarshall(["w", "d"], buffer, state); + var fid = req[0]; + var inode = this.fs.GetInode(this.fids[fid].inodeid); + message.Debug("[getattr]: fid=" + fid + " name=" + this.fids[fid].dbg_name + " request mask=" + req[1]); + if(!inode || inode.status === STATUS_UNLINKED) + { + message.Debug("getattr: unlinked"); + this.SendError(tag, "No such file or directory", ENOENT); + this.SendReply(bufchain); + break; + } + req[0] |= 0x1000; // P9_STATS_GEN + + req[0] = req[1]; // request mask + req[1] = inode.qid; + + req[2] = inode.mode; + req[3] = inode.uid; // user id + req[4] = inode.gid; // group id + + req[5] = inode.nlinks; // number of hard links + req[6] = (inode.major<<8) | (inode.minor); // device id low + req[7] = inode.size; // size low + req[8] = this.BLOCKSIZE; + req[9] = Math.floor(inode.size/512+1); // blk size low + req[10] = inode.atime; // atime + req[11] = 0x0; + req[12] = inode.mtime; // mtime + req[13] = 0x0; + req[14] = inode.ctime; // ctime + req[15] = 0x0; + req[16] = 0x0; // btime + req[17] = 0x0; + req[18] = 0x0; // st_gen + req[19] = 0x0; // data_version + marshall.Marshall([ + "d", "Q", + "w", + "w", "w", + "d", "d", + "d", "d", "d", + "d", "d", // atime + "d", "d", // mtime + "d", "d", // ctime + "d", "d", // btime + "d", "d", + ], req, this.replybuffer, 7); + this.BuildReply(id, tag, 8 + 13 + 4 + 4+ 4 + 8*15); + this.SendReply(bufchain); + break; + + case 26: // setattr + var req = marshall.Unmarshall(["w", "w", + "w", // mode + "w", "w", // uid, gid + "d", // size + "d", "d", // atime + "d", "d", // mtime + ], buffer, state); + var fid = req[0]; + var inode = this.fs.GetInode(this.fids[fid].inodeid); + message.Debug("[setattr]: fid=" + fid + " request mask=" + req[1] + " name=" + this.fids[fid].dbg_name); + if (req[1] & P9_SETATTR_MODE) { + inode.mode = req[2]; + } + if (req[1] & P9_SETATTR_UID) { + inode.uid = req[3]; + } + if (req[1] & P9_SETATTR_GID) { + inode.gid = req[4]; + } + if (req[1] & P9_SETATTR_ATIME) { + inode.atime = Math.floor((new Date()).getTime()/1000); + } + if (req[1] & P9_SETATTR_MTIME) { + inode.mtime = Math.floor((new Date()).getTime()/1000); + } + if (req[1] & P9_SETATTR_CTIME) { + inode.ctime = Math.floor((new Date()).getTime()/1000); + } + if (req[1] & P9_SETATTR_ATIME_SET) { + inode.atime = req[6]; + } + if (req[1] & P9_SETATTR_MTIME_SET) { + inode.mtime = req[8]; + } + if (req[1] & P9_SETATTR_SIZE) { + await this.fs.ChangeSize(this.fids[fid].inodeid, req[5]); + } + this.BuildReply(id, tag, 0); + this.SendReply(bufchain); + break; + + case 50: // fsync + var req = marshall.Unmarshall(["w", "d"], buffer, state); + var fid = req[0]; + this.BuildReply(id, tag, 0); + this.SendReply(bufchain); + break; + + case 40: // TREADDIR + case 116: // read + var req = marshall.Unmarshall(["w", "d", "w"], buffer, state); + var fid = req[0]; + var offset = req[1]; + var count = req[2]; + var inode = this.fs.GetInode(this.fids[fid].inodeid); + if (id == 40) message.Debug("[treaddir]: fid=" + fid + " offset=" + offset + " count=" + count); + if (id == 116) message.Debug("[read]: fid=" + fid + " (" + this.fids[fid].dbg_name + ") offset=" + offset + " count=" + count + " fidtype=" + this.fids[fid].type); + if(!inode || inode.status === STATUS_UNLINKED) + { + message.Debug("read/treaddir: unlinked"); + this.SendError(tag, "No such file or directory", ENOENT); + this.SendReply(bufchain); + break; + } + if (this.fids[fid].type == FID_XATTR) { + if (inode.caps.length < offset+count) count = inode.caps.length - offset; + for(var i=0; i inode.size) + { + // offset can be greater than available - should return count of zero. + // See http://ericvh.github.io/9p-rfc/rfc9p2000.html#anchor30 + count = 0; + } + + this.bus.send("9p-read-start", [this.fids[fid].dbg_name]); + + const data = await this.fs.Read(inodeid, offset, count); + + this.bus.send("9p-read-end", [this.fids[fid].dbg_name, count]); + + if(data) { + this.replybuffer.set(data, 7 + 4); + } + marshall.Marshall(["w"], [count], this.replybuffer, 7); + this.BuildReply(id, tag, 4 + count); + this.SendReply(bufchain); + } + break; + + case 118: // write + var req = marshall.Unmarshall(["w", "d", "w"], buffer, state); + var fid = req[0]; + var offset = req[1]; + var count = req[2]; + + const filename = this.fids[fid].dbg_name; + + message.Debug("[write]: fid=" + fid + " (" + filename + ") offset=" + offset + " count=" + count + " fidtype=" + this.fids[fid].type); + if(this.fids[fid].type === FID_XATTR) + { + // XXX: xattr not supported yet. Ignore write. + this.SendError(tag, "Setxattr not supported", EOPNOTSUPP); + this.SendReply(bufchain); + break; + } + else + { + // XXX: Size of the subarray is unchecked + await this.fs.Write(this.fids[fid].inodeid, offset, count, buffer.subarray(state.offset)); + } + + this.bus.send("9p-write-end", [filename, count]); + + marshall.Marshall(["w"], [count], this.replybuffer, 7); + this.BuildReply(id, tag, 4); + this.SendReply(bufchain); + break; + + case 74: // RENAMEAT + var req = marshall.Unmarshall(["w", "s", "w", "s"], buffer, state); + var olddirfid = req[0]; + var oldname = req[1]; + var newdirfid = req[2]; + var newname = req[3]; + message.Debug("[renameat]: oldname=" + oldname + " newname=" + newname); + var ret = await this.fs.Rename(this.fids[olddirfid].inodeid, oldname, this.fids[newdirfid].inodeid, newname); + if (ret < 0) { + let error_message = ""; + if(ret === -ENOENT) error_message = "No such file or directory"; + else if(ret === -EPERM) error_message = "Operation not permitted"; + else if(ret === -ENOTEMPTY) error_message = "Directory not empty"; + else + { + error_message = "Unknown error: " + (-ret); + dbg_assert(false, "[renameat]: Unexpected error code: " + (-ret)); + } + this.SendError(tag, error_message, -ret); + this.SendReply(bufchain); + break; + } + if(TRACK_FILENAMES) + { + const newidx = this.fs.Search(this.fids[newdirfid].inodeid, newname); + this.update_dbg_name(newidx, newname); + } + this.BuildReply(id, tag, 0); + this.SendReply(bufchain); + break; + + case 76: // TUNLINKAT + var req = marshall.Unmarshall(["w", "s", "w"], buffer, state); + var dirfd = req[0]; + var name = req[1]; + var flags = req[2]; + message.Debug("[unlink]: dirfd=" + dirfd + " name=" + name + " flags=" + flags); + var fid = this.fs.Search(this.fids[dirfd].inodeid, name); + if (fid == -1) { + this.SendError(tag, "No such file or directory", ENOENT); + this.SendReply(bufchain); + break; + } + var ret = this.fs.Unlink(this.fids[dirfd].inodeid, name); + if (ret < 0) { + let error_message = ""; + if(ret === -ENOTEMPTY) error_message = "Directory not empty"; + else if(ret === -EPERM) error_message = "Operation not permitted"; + else + { + error_message = "Unknown error: " + (-ret); + dbg_assert(false, "[unlink]: Unexpected error code: " + (-ret)); + } + this.SendError(tag, error_message, -ret); + this.SendReply(bufchain); + break; + } + this.BuildReply(id, tag, 0); + this.SendReply(bufchain); + break; + + case 100: // version + var version = marshall.Unmarshall(["w", "s"], buffer, state); + message.Debug("[version]: msize=" + version[0] + " version=" + version[1]); + this.msize = version[0]; + size = marshall.Marshall(["w", "s"], [this.msize, this.VERSION], this.replybuffer, 7); + this.BuildReply(id, tag, size); + this.SendReply(bufchain); + break; + + case 104: // attach + // return root directorie's QID + var req = marshall.Unmarshall(["w", "w", "s", "s", "w"], buffer, state); + var fid = req[0]; + var uid = req[4]; + message.Debug("[attach]: fid=" + fid + " afid=" + hex8(req[1]) + " uname=" + req[2] + " aname=" + req[3]); + this.fids[fid] = this.Createfid(0, FID_INODE, uid, ""); + var inode = this.fs.GetInode(this.fids[fid].inodeid); + marshall.Marshall(["Q"], [inode.qid], this.replybuffer, 7); + this.BuildReply(id, tag, 13); + this.SendReply(bufchain); + this.bus.send("9p-attach"); + break; + + case 108: // tflush + var req = marshall.Unmarshall(["h"], buffer, state); + var oldtag = req[0]; + message.Debug("[flush] " + tag); + //marshall.Marshall(["Q"], [inode.qid], this.replybuffer, 7); + this.BuildReply(id, tag, 0); + this.SendReply(bufchain); + break; + + + case 110: // walk + var req = marshall.Unmarshall(["w", "w", "h"], buffer, state); + var fid = req[0]; + var nwfid = req[1]; + var nwname = req[2]; + message.Debug("[walk]: fid=" + req[0] + " nwfid=" + req[1] + " nwname=" + nwname); + if (nwname == 0) { + this.fids[nwfid] = this.Createfid(this.fids[fid].inodeid, FID_INODE, this.fids[fid].uid, this.fids[fid].dbg_name); + //this.fids[nwfid].inodeid = this.fids[fid].inodeid; + marshall.Marshall(["h"], [0], this.replybuffer, 7); + this.BuildReply(id, tag, 2); + this.SendReply(bufchain); + break; + } + var wnames = []; + for(var i=0; i} */ + this.inodes = []; + this.events = []; + + this.storage = storage; + + this.qidcounter = qidcounter || { last_qidnumber: 0 }; + + //this.tar = new TAR(this); + + this.inodedata = {}; + + this.total_size = 256 * 1024 * 1024 * 1024; + this.used_size = 0; + + /** @type {!Array} */ + this.mounts = []; + + //RegisterMessage("LoadFilesystem", this.LoadFilesystem.bind(this) ); + //RegisterMessage("MergeFile", this.MergeFile.bind(this) ); + //RegisterMessage("tar", + // function(data) { + // SendToMaster("tar", this.tar.Pack(data)); + // }.bind(this) + //); + //RegisterMessage("sync", + // function(data) { + // SendToMaster("sync", this.tar.Pack(data)); + // }.bind(this) + //); + + // root entry + this.CreateDirectory("", -1); +} + +FS.prototype.get_state = function() +{ + let state = []; + + state[0] = this.inodes; + state[1] = this.qidcounter.last_qidnumber; + state[2] = []; + for(const [id, data] of Object.entries(this.inodedata)) + { + if((this.inodes[id].mode & S_IFDIR) === 0) + { + state[2].push([id, data]); + } + } + state[3] = this.total_size; + state[4] = this.used_size; + state = state.concat(this.mounts); + + return state; +}; + +FS.prototype.set_state = function(state) +{ + this.inodes = state[0].map(state => { const inode = new Inode(0); inode.set_state(state); return inode; }); + this.qidcounter.last_qidnumber = state[1]; + this.inodedata = {}; + for(let [key, value] of state[2]) + { + if(value.buffer.byteLength !== value.byteLength) + { + // make a copy if we didn't get one + value = value.slice(); + } + + this.inodedata[key] = value; + } + this.total_size = state[3]; + this.used_size = state[4]; + this.mounts = state.slice(5); +}; + + +// ----------------------------------------------------- + +FS.prototype.AddEvent = function(id, OnEvent) { + var inode = this.inodes[id]; + if (inode.status == STATUS_OK || inode.status == STATUS_ON_STORAGE) { + OnEvent(); + } + else if(this.is_forwarder(inode)) + { + this.follow_fs(inode).AddEvent(inode.foreign_id, OnEvent); + } + else + { + this.events.push({id: id, OnEvent: OnEvent}); + } +}; + +FS.prototype.HandleEvent = function(id) { + const inode = this.inodes[id]; + if(this.is_forwarder(inode)) + { + this.follow_fs(inode).HandleEvent(inode.foreign_id); + } + //message.Debug("number of events: " + this.events.length); + var newevents = []; + for(var i=0; i= 0, + "Filesystem: Found negative nlinks value of " + inode.nlinks); + dbg_assert(!parent_inode.direntries.has(name), + "Filesystem: Name '" + name + "' is already taken"); + + parent_inode.direntries.set(name, idx); + inode.nlinks++; + + if(this.IsDirectory(idx)) + { + dbg_assert(!inode.direntries.has(".."), + "Filesystem: Cannot link a directory twice"); + + if(!inode.direntries.has(".")) inode.nlinks++; + inode.direntries.set(".", idx); + + inode.direntries.set("..", parentid); + parent_inode.nlinks++; + } +}; + +/** + * @private + * @param {number} parentid + * @param {string} name + */ +FS.prototype.unlink_from_dir = function(parentid, name) +{ + const idx = this.Search(parentid, name); + const inode = this.inodes[idx]; + const parent_inode = this.inodes[parentid]; + + dbg_assert(!this.is_forwarder(parent_inode), "Filesystem: Can't unlink from forwarders"); + dbg_assert(this.IsDirectory(parentid), "Filesystem: Can't unlink from non-directories"); + + const exists = parent_inode.direntries.delete(name); + if(!exists) + { + dbg_assert(false, "Filesystem: Can't unlink non-existent file: " + name); + return; + } + + inode.nlinks--; + + if(this.IsDirectory(idx)) + { + dbg_assert(inode.direntries.get("..") === parentid, + "Filesystem: Found directory with bad parent id"); + + inode.direntries.delete(".."); + parent_inode.nlinks--; + } + + dbg_assert(inode.nlinks >= 0, + "Filesystem: Found negative nlinks value of " + inode.nlinks); +}; + +FS.prototype.PushInode = function(inode, parentid, name) { + if (parentid != -1) { + this.inodes.push(inode); + inode.fid = this.inodes.length - 1; + this.link_under_dir(parentid, inode.fid, name); + return; + } else { + if (this.inodes.length == 0) { // if root directory + this.inodes.push(inode); + inode.direntries.set(".", 0); + inode.direntries.set("..", 0); + inode.nlinks = 2; + return; + } + } + + message.Debug("Error in Filesystem: Pushed inode with name = "+ name + " has no parent"); + message.Abort(); + +}; + +/** @constructor */ +function Inode(qidnumber) +{ + this.direntries = new Map(); // maps filename to inode id + this.status = 0; + this.size = 0x0; + this.uid = 0x0; + this.gid = 0x0; + this.fid = 0; + this.ctime = 0; + this.atime = 0; + this.mtime = 0; + this.major = 0x0; + this.minor = 0x0; + this.symlink = ""; + this.mode = 0x01ED; + this.qid = { + type: 0, + version: 0, + path: qidnumber, + }; + this.caps = undefined; + this.nlinks = 0; + this.sha256sum = ""; + + /** @type{!Array} */ + this.locks = []; // lock regions applied to the file, sorted by starting offset. + + // For forwarders: + this.mount_id = -1; // which fs in this.mounts does this inode forward to? + this.foreign_id = -1; // which foreign inode id does it represent? + + //this.qid_type = 0; + //this.qid_version = 0; + //this.qid_path = qidnumber; +} + +Inode.prototype.get_state = function() +{ + const state = []; + state[0] = this.mode; + + if((this.mode & S_IFMT) === S_IFDIR) + { + state[1] = [...this.direntries]; + } + else if((this.mode & S_IFMT) === S_IFREG) + { + state[1] = this.sha256sum; + } + else if((this.mode & S_IFMT) === S_IFLNK) + { + state[1] = this.symlink; + } + else if((this.mode & S_IFMT) === S_IFSOCK) + { + state[1] = [this.minor, this.major]; + } + else + { + state[1] = null; + } + + state[2] = this.locks; + state[3] = this.status; + state[4] = this.size; + state[5] = this.uid; + state[6] = this.gid; + state[7] = this.fid; + state[8] = this.ctime; + state[9] = this.atime; + state[10] = this.mtime; + state[11] = this.qid.version; + state[12] = this.qid.path; + state[13] = this.nlinks; + + //state[23] = this.mount_id; + //state[24] = this.foreign_id; + //state[25] = this.caps; // currently not writable + return state; +}; + +Inode.prototype.set_state = function(state) +{ + this.mode = state[0]; + + if((this.mode & S_IFMT) === S_IFDIR) + { + this.direntries = new Map(); + for(const [name, entry] of state[1]) + { + this.direntries.set(name, entry); + } + } + else if((this.mode & S_IFMT) === S_IFREG) + { + this.sha256sum = state[1]; + } + else if((this.mode & S_IFMT) === S_IFLNK) + { + this.symlink = state[1]; + } + else if((this.mode & S_IFMT) === S_IFSOCK) + { + [this.minor, this.major] = state[1]; + } + else + { + // Nothing + } + + this.locks = []; + for(const lock_state of state[2]) + { + const lock = new FSLockRegion(); + lock.set_state(lock_state); + this.locks.push(lock); + } + this.status = state[3]; + this.size = state[4]; + this.uid = state[5]; + this.gid = state[6]; + this.fid = state[7]; + this.ctime = state[8]; + this.atime = state[9]; + this.mtime = state[10]; + this.qid.type = (this.mode & S_IFMT) >> 8; + this.qid.version = state[11]; + this.qid.path = state[12]; + this.nlinks = state[13]; + + //this.mount_id = state[23]; + //this.foreign_id = state[24]; + //this.caps = state[20]; +}; + +/** + * Clones given inode to new idx, effectively diverting the inode to new idx value. + * Hence, original idx value is now free to use without losing the original information. + * @private + * @param {number} parentid Parent of target to divert. + * @param {string} filename Name of target to divert. + * @return {number} New idx of diversion. + */ +FS.prototype.divert = function(parentid, filename) +{ + const old_idx = this.Search(parentid, filename); + const old_inode = this.inodes[old_idx]; + const new_inode = new Inode(-1); + + dbg_assert(old_inode, "Filesystem divert: name (" + filename + ") not found"); + dbg_assert(this.IsDirectory(old_idx) || old_inode.nlinks <= 1, + "Filesystem: can't divert hardlinked file '" + filename + "' with nlinks=" + + old_inode.nlinks); + + // Shallow copy is alright. + Object.assign(new_inode, old_inode); + + const idx = this.inodes.length; + this.inodes.push(new_inode); + new_inode.fid = idx; + + // Relink references + if(this.is_forwarder(old_inode)) + { + this.mounts[old_inode.mount_id].backtrack.set(old_inode.foreign_id, idx); + } + if(this.should_be_linked(old_inode)) + { + this.unlink_from_dir(parentid, filename); + this.link_under_dir(parentid, idx, filename); + } + + // Update children + if(this.IsDirectory(old_idx) && !this.is_forwarder(old_inode)) + { + for(const [name, child_id] of new_inode.direntries) + { + if(name === "." || name === "..") continue; + if(this.IsDirectory(child_id)) + { + this.inodes[child_id].direntries.set("..", idx); + } + } + } + + // Relocate local data if any. + this.inodedata[idx] = this.inodedata[old_idx]; + delete this.inodedata[old_idx]; + + // Retire old reference information. + old_inode.direntries = new Map(); + old_inode.nlinks = 0; + + return idx; +}; + +/** + * Copy all non-redundant info. + * References left untouched: local idx value and links + * @private + * @param {!Inode} src_inode + * @param {!Inode} dest_inode + */ +FS.prototype.copy_inode = function(src_inode, dest_inode) +{ + Object.assign(dest_inode, src_inode, { + fid: dest_inode.fid, + direntries: dest_inode.direntries, + nlinks: dest_inode.nlinks, + }); +}; + +FS.prototype.CreateInode = function() { + //console.log("CreateInode", Error().stack); + const now = Math.round(Date.now() / 1000); + const inode = new Inode(++this.qidcounter.last_qidnumber); + inode.atime = inode.ctime = inode.mtime = now; + return inode; +}; + + +// Note: parentid = -1 for initial root directory. +FS.prototype.CreateDirectory = function(name, parentid) { + const parent_inode = this.inodes[parentid]; + if(parentid >= 0 && this.is_forwarder(parent_inode)) + { + const foreign_parentid = parent_inode.foreign_id; + const foreign_id = this.follow_fs(parent_inode).CreateDirectory(name, foreign_parentid); + return this.create_forwarder(parent_inode.mount_id, foreign_id); + } + var x = this.CreateInode(); + x.mode = 0x01FF | S_IFDIR; + if (parentid >= 0) { + x.uid = this.inodes[parentid].uid; + x.gid = this.inodes[parentid].gid; + x.mode = (this.inodes[parentid].mode & 0x1FF) | S_IFDIR; + } + x.qid.type = S_IFDIR >> 8; + this.PushInode(x, parentid, name); + this.NotifyListeners(this.inodes.length-1, 'newdir'); + return this.inodes.length-1; +}; + +FS.prototype.CreateFile = function(filename, parentid) { + const parent_inode = this.inodes[parentid]; + if(this.is_forwarder(parent_inode)) + { + const foreign_parentid = parent_inode.foreign_id; + const foreign_id = this.follow_fs(parent_inode).CreateFile(filename, foreign_parentid); + return this.create_forwarder(parent_inode.mount_id, foreign_id); + } + var x = this.CreateInode(); + x.uid = this.inodes[parentid].uid; + x.gid = this.inodes[parentid].gid; + x.qid.type = S_IFREG >> 8; + x.mode = (this.inodes[parentid].mode & 0x1B6) | S_IFREG; + this.PushInode(x, parentid, filename); + this.NotifyListeners(this.inodes.length-1, 'newfile'); + return this.inodes.length-1; +}; + + +FS.prototype.CreateNode = function(filename, parentid, major, minor) { + const parent_inode = this.inodes[parentid]; + if(this.is_forwarder(parent_inode)) + { + const foreign_parentid = parent_inode.foreign_id; + const foreign_id = + this.follow_fs(parent_inode).CreateNode(filename, foreign_parentid, major, minor); + return this.create_forwarder(parent_inode.mount_id, foreign_id); + } + var x = this.CreateInode(); + x.major = major; + x.minor = minor; + x.uid = this.inodes[parentid].uid; + x.gid = this.inodes[parentid].gid; + x.qid.type = S_IFSOCK >> 8; + x.mode = (this.inodes[parentid].mode & 0x1B6); + this.PushInode(x, parentid, filename); + return this.inodes.length-1; +}; + +FS.prototype.CreateSymlink = function(filename, parentid, symlink) { + const parent_inode = this.inodes[parentid]; + if(this.is_forwarder(parent_inode)) + { + const foreign_parentid = parent_inode.foreign_id; + const foreign_id = + this.follow_fs(parent_inode).CreateSymlink(filename, foreign_parentid, symlink); + return this.create_forwarder(parent_inode.mount_id, foreign_id); + } + var x = this.CreateInode(); + x.uid = this.inodes[parentid].uid; + x.gid = this.inodes[parentid].gid; + x.qid.type = S_IFLNK >> 8; + x.symlink = symlink; + x.mode = S_IFLNK; + this.PushInode(x, parentid, filename); + return this.inodes.length-1; +}; + +FS.prototype.CreateTextFile = async function(filename, parentid, str) { + const parent_inode = this.inodes[parentid]; + if(this.is_forwarder(parent_inode)) + { + const foreign_parentid = parent_inode.foreign_id; + const foreign_id = await + this.follow_fs(parent_inode).CreateTextFile(filename, foreign_parentid, str); + return this.create_forwarder(parent_inode.mount_id, foreign_id); + } + var id = this.CreateFile(filename, parentid); + var x = this.inodes[id]; + var data = new Uint8Array(str.length); + x.size = str.length; + for (var j = 0; j < str.length; j++) { + data[j] = str.charCodeAt(j); + } + await this.set_data(id, data); + return id; +}; + +/** + * @param {Uint8Array} buffer + */ +FS.prototype.CreateBinaryFile = async function(filename, parentid, buffer) { + const parent_inode = this.inodes[parentid]; + if(this.is_forwarder(parent_inode)) + { + const foreign_parentid = parent_inode.foreign_id; + const foreign_id = await + this.follow_fs(parent_inode).CreateBinaryFile(filename, foreign_parentid, buffer); + return this.create_forwarder(parent_inode.mount_id, foreign_id); + } + var id = this.CreateFile(filename, parentid); + var x = this.inodes[id]; + var data = new Uint8Array(buffer.length); + data.set(buffer); + await this.set_data(id, data); + x.size = buffer.length; + return id; +}; + + +FS.prototype.OpenInode = function(id, mode) { + var inode = this.inodes[id]; + if(this.is_forwarder(inode)) + { + return this.follow_fs(inode).OpenInode(inode.foreign_id, mode); + } + if ((inode.mode&S_IFMT) == S_IFDIR) { + this.FillDirectory(id); + } + /* + var type = ""; + switch(inode.mode&S_IFMT) { + case S_IFREG: type = "File"; break; + case S_IFBLK: type = "Block Device"; break; + case S_IFDIR: type = "Directory"; break; + case S_IFCHR: type = "Character Device"; break; + } + */ + //message.Debug("open:" + this.GetFullPath(id) + " type: " + inode.mode + " status:" + inode.status); + return true; +}; + +FS.prototype.CloseInode = async function(id) { + //message.Debug("close: " + this.GetFullPath(id)); + var inode = this.inodes[id]; + if(this.is_forwarder(inode)) + { + return await this.follow_fs(inode).CloseInode(inode.foreign_id); + } + if(inode.status === STATUS_ON_STORAGE) + { + this.storage.uncache(inode.sha256sum); + } + if (inode.status == STATUS_UNLINKED) { + //message.Debug("Filesystem: Delete unlinked file"); + inode.status = STATUS_INVALID; + await this.DeleteData(id); + } +}; + +/** + * @return {!Promise} 0 if success, or -errno if failured. + */ +FS.prototype.Rename = async function(olddirid, oldname, newdirid, newname) { + // message.Debug("Rename " + oldname + " to " + newname); + if ((olddirid == newdirid) && (oldname == newname)) { + return 0; + } + var oldid = this.Search(olddirid, oldname); + if(oldid === -1) + { + return -ENOENT; + } + + // For event notification near end of method. + var oldpath = this.GetFullPath(olddirid) + "/" + oldname; + + var newid = this.Search(newdirid, newname); + if (newid != -1) { + const ret = this.Unlink(newdirid, newname); + if(ret < 0) return ret; + } + + var idx = oldid; // idx contains the id which we want to rename + var inode = this.inodes[idx]; + const olddir = this.inodes[olddirid]; + const newdir = this.inodes[newdirid]; + + if(!this.is_forwarder(olddir) && !this.is_forwarder(newdir)) + { + // Move inode within current filesystem. + + this.unlink_from_dir(olddirid, oldname); + this.link_under_dir(newdirid, idx, newname); + + inode.qid.version++; + } + else if(this.is_forwarder(olddir) && olddir.mount_id === newdir.mount_id) + { + // Move inode within the same child filesystem. + + const ret = await + this.follow_fs(olddir).Rename(olddir.foreign_id, oldname, newdir.foreign_id, newname); + + if(ret < 0) return ret; + } + else if(this.is_a_root(idx)) + { + // The actual inode is a root of some descendant filesystem. + // Moving mountpoint across fs not supported - needs to update all corresponding forwarders. + dbg_log("XXX: Attempted to move mountpoint (" + oldname + ") - skipped", LOG_9P); + return -EPERM; + } + else if(!this.IsDirectory(idx) && this.GetInode(idx).nlinks > 1) + { + // Move hardlinked inode vertically in mount tree. + dbg_log("XXX: Attempted to move hardlinked file (" + oldname + ") " + + "across filesystems - skipped", LOG_9P); + return -EPERM; + } + else + { + // Jump between filesystems. + + // Can't work with both old and new inode information without first diverting the old + // information into a new idx value. + const diverted_old_idx = this.divert(olddirid, oldname); + const old_real_inode = this.GetInode(idx); + + const data = await this.Read(diverted_old_idx, 0, old_real_inode.size); + + if(this.is_forwarder(newdir)) + { + // Create new inode. + const foreign_fs = this.follow_fs(newdir); + const foreign_id = this.IsDirectory(diverted_old_idx) ? + foreign_fs.CreateDirectory(newname, newdir.foreign_id) : + foreign_fs.CreateFile(newname, newdir.foreign_id); + + const new_real_inode = foreign_fs.GetInode(foreign_id); + this.copy_inode(old_real_inode, new_real_inode); + + // Point to this new location. + this.set_forwarder(idx, newdir.mount_id, foreign_id); + } + else + { + // Replace current forwarder with real inode. + this.delete_forwarder(inode); + this.copy_inode(old_real_inode, inode); + + // Link into new location in this filesystem. + this.link_under_dir(newdirid, idx, newname); + } + + // Rewrite data to newly created destination. + await this.ChangeSize(idx, old_real_inode.size); + if(data && data.length) + { + await this.Write(idx, 0, data.length, data); + } + + // Move children to newly created destination. + if(this.IsDirectory(idx)) + { + for(const child_filename of this.GetChildren(diverted_old_idx)) + { + const ret = await this.Rename(diverted_old_idx, child_filename, idx, child_filename); + if(ret < 0) return ret; + } + } + + // Perform destructive changes only after migration succeeded. + await this.DeleteData(diverted_old_idx); + const ret = this.Unlink(olddirid, oldname); + if(ret < 0) return ret; + } + + this.NotifyListeners(idx, "rename", {oldpath: oldpath}); + + return 0; +}; + +FS.prototype.Write = async function(id, offset, count, buffer) { + this.NotifyListeners(id, 'write'); + var inode = this.inodes[id]; + + if(this.is_forwarder(inode)) + { + const foreign_id = inode.foreign_id; + await this.follow_fs(inode).Write(foreign_id, offset, count, buffer); + return; + } + + var data = await this.get_buffer(id); + + if (!data || data.length < (offset+count)) { + await this.ChangeSize(id, Math.floor(((offset+count)*3)/2)); + inode.size = offset + count; + data = await this.get_buffer(id); + } else + if (inode.size < (offset+count)) { + inode.size = offset + count; + } + if(buffer) + { + data.set(buffer.subarray(0, count), offset); + } + await this.set_data(id, data); +}; + +FS.prototype.Read = async function(inodeid, offset, count) +{ + const inode = this.inodes[inodeid]; + if(this.is_forwarder(inode)) + { + const foreign_id = inode.foreign_id; + return await this.follow_fs(inode).Read(foreign_id, offset, count); + } + + return await this.get_data(inodeid, offset, count); +}; + +FS.prototype.Search = function(parentid, name) { + const parent_inode = this.inodes[parentid]; + + if(this.is_forwarder(parent_inode)) + { + const foreign_parentid = parent_inode.foreign_id; + const foreign_id = this.follow_fs(parent_inode).Search(foreign_parentid, name); + if(foreign_id === -1) return -1; + return this.get_forwarder(parent_inode.mount_id, foreign_id); + } + + const childid = parent_inode.direntries.get(name); + return childid === undefined ? -1 : childid; +}; + +FS.prototype.CountUsedInodes = function() +{ + let count = this.inodes.length; + for(const { fs, backtrack } of this.mounts) + { + count += fs.CountUsedInodes(); + + // Forwarder inodes don't count. + count -= backtrack.size; + } + return count; +}; + +FS.prototype.CountFreeInodes = function() +{ + let count = 1024 * 1024; + for(const { fs } of this.mounts) + { + count += fs.CountFreeInodes(); + } + return count; +}; + +FS.prototype.GetTotalSize = function() { + let size = this.used_size; + for(const { fs } of this.mounts) + { + size += fs.GetTotalSize(); + } + return size; + //var size = 0; + //for(var i=0; i} The buffer that contains the file contents, which may be larger + * than the data itself. To ensure that any modifications done to this buffer is reflected + * to the file, call set_data with the modified buffer. + */ +FS.prototype.get_buffer = async function(idx) +{ + const inode = this.inodes[idx]; + dbg_assert(inode, `Filesystem get_buffer: idx ${idx} does not point to an inode`); + + if(this.inodedata[idx]) + { + return this.inodedata[idx]; + } + else if(inode.status === STATUS_ON_STORAGE) + { + dbg_assert(inode.sha256sum, "Filesystem get_data: found inode on server without sha256sum"); + return await this.storage.read(inode.sha256sum, 0, inode.size); + } + else + { + return null; + } +}; + +/** + * @private + * @param {number} idx + * @param {number} offset + * @param {number} count + * @return {!Promise} + */ +FS.prototype.get_data = async function(idx, offset, count) +{ + const inode = this.inodes[idx]; + dbg_assert(inode, `Filesystem get_data: idx ${idx} does not point to an inode`); + + if(this.inodedata[idx]) + { + return this.inodedata[idx].subarray(offset, offset + count); + } + else if(inode.status === STATUS_ON_STORAGE) + { + dbg_assert(inode.sha256sum, "Filesystem get_data: found inode on server without sha256sum"); + return await this.storage.read(inode.sha256sum, offset, count); + } + else + { + return null; + } +}; + +/** + * @private + * @param {number} idx + * @param {Uint8Array} buffer + */ +FS.prototype.set_data = async function(idx, buffer) +{ + // Current scheme: Save all modified buffers into local inodedata. + this.inodedata[idx] = buffer; + if(this.inodes[idx].status === STATUS_ON_STORAGE) + { + this.inodes[idx].status = STATUS_OK; + this.storage.uncache(this.inodes[idx].sha256sum); + } +}; + +/** + * @param {number} idx + * @return {!Inode} + */ +FS.prototype.GetInode = function(idx) +{ + dbg_assert(!isNaN(idx), "Filesystem GetInode: NaN idx"); + dbg_assert(idx >= 0 && idx < this.inodes.length, "Filesystem GetInode: out of range idx:" + idx); + + const inode = this.inodes[idx]; + if(this.is_forwarder(inode)) + { + return this.follow_fs(inode).GetInode(inode.foreign_id); + } + + return inode; +}; + +FS.prototype.ChangeSize = async function(idx, newsize) +{ + var inode = this.GetInode(idx); + var temp = await this.get_data(idx, 0, inode.size); + //message.Debug("change size to: " + newsize); + if (newsize == inode.size) return; + var data = new Uint8Array(newsize); + inode.size = newsize; + if(temp) + { + var size = Math.min(temp.length, inode.size); + data.set(temp.subarray(0, size), 0); + } + await this.set_data(idx, data); +}; + +FS.prototype.SearchPath = function(path) { + //path = path.replace(/\/\//g, "/"); + path = path.replace("//", "/"); + var walk = path.split("/"); + if (walk.length > 0 && walk[walk.length - 1].length === 0) walk.pop(); + if (walk.length > 0 && walk[0].length === 0) walk.shift(); + const n = walk.length; + + var parentid = -1; + var id = 0; + let forward_path = null; + for(var i=0; i} list + */ +FS.prototype.GetRecursiveList = function(dirid, list) { + if(this.is_forwarder(this.inodes[dirid])) + { + const foreign_fs = this.follow_fs(this.inodes[dirid]); + const foreign_dirid = this.inodes[dirid].foreign_id; + const mount_id = this.inodes[dirid].mount_id; + + const foreign_start = list.length; + foreign_fs.GetRecursiveList(foreign_dirid, list); + for(let i = foreign_start; i < list.length; i++) + { + list[i].parentid = this.get_forwarder(mount_id, list[i].parentid); + } + return; + } + for(const [name, id] of this.inodes[dirid].direntries) + { + if(name !== "." && name !== "..") + { + list.push({ parentid: dirid, name }); + if(this.IsDirectory(id)) + { + this.GetRecursiveList(id, list); + } + } + } +}; + +FS.prototype.RecursiveDelete = function(path) { + var toDelete = []; + var ids = this.SearchPath(path); + if(ids.id === -1) return; + + this.GetRecursiveList(ids.id, toDelete); + + for(var i=toDelete.length-1; i>=0; i--) + { + const ret = this.Unlink(toDelete[i].parentid, toDelete[i].name); + dbg_assert(ret === 0, "Filesystem RecursiveDelete failed at parent=" + toDelete[i].parentid + + ", name='" + toDelete[i].name + "' with error code: " + (-ret)); + } +}; + +FS.prototype.DeleteNode = function(path) { + var ids = this.SearchPath(path); + if (ids.id == -1) return; + + if ((this.inodes[ids.id].mode&S_IFMT) == S_IFREG){ + const ret = this.Unlink(ids.parentid, ids.name); + dbg_assert(ret === 0, "Filesystem DeleteNode failed with error code: " + (-ret)); + return; + } + if ((this.inodes[ids.id].mode&S_IFMT) == S_IFDIR){ + this.RecursiveDelete(path); + const ret = this.Unlink(ids.parentid, ids.name); + dbg_assert(ret === 0, "Filesystem DeleteNode failed with error code: " + (-ret)); + return; + } +}; + +/** @param {*=} info */ +FS.prototype.NotifyListeners = function(id, action, info) { + //if(info==undefined) + // info = {}; + + //var path = this.GetFullPath(id); + //if (this.watchFiles[path] == true && action=='write') { + // message.Send("WatchFileEvent", path); + //} + //for (var directory of this.watchDirectories) { + // if (this.watchDirectories.hasOwnProperty(directory)) { + // var indexOf = path.indexOf(directory) + // if(indexOf == 0 || indexOf == 1) + // message.Send("WatchDirectoryEvent", {path: path, event: action, info: info}); + // } + //} +}; + + +FS.prototype.Check = function() { + for(var i=1; i> 12, + name], + data, offset); + } +}; + +FS.prototype.RoundToDirentry = function(dirid, offset_target) +{ + const data = this.inodedata[dirid]; + dbg_assert(data, `FS directory data for dirid=${dirid} should be generated`); + dbg_assert(data.length, "FS directory should have at least an entry"); + + if(offset_target >= data.length) + { + return data.length; + } + + let offset = 0; + while(true) + { + const next_offset = marshall.Unmarshall(["Q", "d"], data, { offset })[1]; + if(next_offset > offset_target) break; + offset = next_offset; + } + + return offset; +}; + +/** + * @param {number} idx + * @return {boolean} + */ +FS.prototype.IsDirectory = function(idx) +{ + const inode = this.inodes[idx]; + if(this.is_forwarder(inode)) + { + return this.follow_fs(inode).IsDirectory(inode.foreign_id); + } + return (inode.mode & S_IFMT) === S_IFDIR; +}; + +/** + * @param {number} idx + * @return {boolean} + */ +FS.prototype.IsEmpty = function(idx) +{ + const inode = this.inodes[idx]; + if(this.is_forwarder(inode)) + { + return this.follow_fs(inode).IsDirectory(inode.foreign_id); + } + for(const name of inode.direntries.keys()) + { + if(name !== "." && name !== "..") return false; + } + return true; +}; + +/** + * @param {number} idx + * @return {!Array} List of children names + */ +FS.prototype.GetChildren = function(idx) +{ + dbg_assert(this.IsDirectory(idx), "Filesystem: cannot get children of non-directory inode"); + const inode = this.inodes[idx]; + if(this.is_forwarder(inode)) + { + return this.follow_fs(inode).GetChildren(inode.foreign_id); + } + const children = []; + for(const name of inode.direntries.keys()) + { + if(name !== "." && name !== "..") + { + children.push(name); + } + } + return children; +}; + +/** + * @param {number} idx + * @return {number} Local idx of parent + */ +FS.prototype.GetParent = function(idx) +{ + dbg_assert(this.IsDirectory(idx), "Filesystem: cannot get parent of non-directory inode"); + + const inode = this.inodes[idx]; + + if(this.should_be_linked(inode)) + { + return inode.direntries.get(".."); + } + else + { + const foreign_dirid = this.follow_fs(inode).GetParent(inode.foreign_id); + dbg_assert(foreign_dirid !== -1, "Filesystem: should not have invalid parent ids"); + return this.get_forwarder(inode.mount_id, foreign_dirid); + } +}; + + +// ----------------------------------------------------- + +// only support for security.capabilities +// should return a "struct vfs_cap_data" defined in +// linux/capability for format +// check also: +// sys/capability.h +// http://lxr.free-electrons.com/source/security/commoncap.c#L376 +// http://man7.org/linux/man-pages/man7/capabilities.7.html +// http://man7.org/linux/man-pages/man8/getcap.8.html +// http://man7.org/linux/man-pages/man3/libcap.3.html +FS.prototype.PrepareCAPs = function(id) { + var inode = this.GetInode(id); + if (inode.caps) return inode.caps.length; + inode.caps = new Uint8Array(20); + // format is little endian + // note: getxattr returns -EINVAL if using revision 1 format. + // note: getxattr presents revision 3 as revision 2 when revision 3 is not needed. + // magic_etc (revision=0x02: 20 bytes) + inode.caps[0] = 0x00; + inode.caps[1] = 0x00; + inode.caps[2] = 0x00; + inode.caps[3] = 0x02; + + // lower + // permitted (first 32 capabilities) + inode.caps[4] = 0xFF; + inode.caps[5] = 0xFF; + inode.caps[6] = 0xFF; + inode.caps[7] = 0xFF; + // inheritable (first 32 capabilities) + inode.caps[8] = 0xFF; + inode.caps[9] = 0xFF; + inode.caps[10] = 0xFF; + inode.caps[11] = 0xFF; + + // higher + // permitted (last 6 capabilities) + inode.caps[12] = 0x3F; + inode.caps[13] = 0x00; + inode.caps[14] = 0x00; + inode.caps[15] = 0x00; + // inheritable (last 6 capabilities) + inode.caps[16] = 0x3F; + inode.caps[17] = 0x00; + inode.caps[18] = 0x00; + inode.caps[19] = 0x00; + + return inode.caps.length; +}; + +// ----------------------------------------------------- + +/** + * @constructor + * @param {FS} filesystem + */ +function FSMountInfo(filesystem) +{ + /** @type {FS}*/ + this.fs = filesystem; + + /** + * Maps foreign inode id back to local inode id. + * @type {!Map} + */ + this.backtrack = new Map(); +} + +FSMountInfo.prototype.get_state = function() +{ + const state = []; + + state[0] = this.fs; + state[1] = [...this.backtrack]; + + return state; +}; + +FSMountInfo.prototype.set_state = function(state) +{ + this.fs = state[0]; + this.backtrack = new Map(state[1]); +}; + +/** + * @private + * @param {number} idx Local idx of inode. + * @param {number} mount_id Mount number of the destination fs. + * @param {number} foreign_id Foreign idx of destination inode. + */ +FS.prototype.set_forwarder = function(idx, mount_id, foreign_id) +{ + const inode = this.inodes[idx]; + + dbg_assert(inode.nlinks === 0, + "Filesystem: attempted to convert an inode into forwarder before unlinking the inode"); + + if(this.is_forwarder(inode)) + { + this.mounts[inode.mount_id].backtrack.delete(inode.foreign_id); + } + + inode.status = STATUS_FORWARDING; + inode.mount_id = mount_id; + inode.foreign_id = foreign_id; + + this.mounts[mount_id].backtrack.set(foreign_id, idx); +}; + +/** + * @private + * @param {number} mount_id Mount number of the destination fs. + * @param {number} foreign_id Foreign idx of destination inode. + * @return {number} Local idx of newly created forwarder. + */ +FS.prototype.create_forwarder = function(mount_id, foreign_id) +{ + const inode = this.CreateInode(); + + const idx = this.inodes.length; + this.inodes.push(inode); + inode.fid = idx; + + this.set_forwarder(idx, mount_id, foreign_id); + return idx; +}; + +/** + * @private + * @param {Inode} inode + * @return {boolean} + */ +FS.prototype.is_forwarder = function(inode) +{ + return inode.status === STATUS_FORWARDING; +}; + +/** + * Whether the inode it points to is a root of some filesystem. + * @private + * @param {number} idx + * @return {boolean} + */ +FS.prototype.is_a_root = function(idx) +{ + return this.GetInode(idx).fid === 0; +}; + +/** + * Ensures forwarder exists, and returns such forwarder, for the described foreign inode. + * @private + * @param {number} mount_id + * @param {number} foreign_id + * @return {number} Local idx of a forwarder to described inode. + */ +FS.prototype.get_forwarder = function(mount_id, foreign_id) +{ + const mount = this.mounts[mount_id]; + + dbg_assert(foreign_id >= 0, "Filesystem get_forwarder: invalid foreign_id: " + foreign_id); + dbg_assert(mount, "Filesystem get_forwarder: invalid mount number: " + mount_id); + + const result = mount.backtrack.get(foreign_id); + + if(result === undefined) + { + // Create if not already exists. + return this.create_forwarder(mount_id, foreign_id); + } + + return result; +}; + +/** + * @private + * @param {Inode} inode + */ +FS.prototype.delete_forwarder = function(inode) +{ + dbg_assert(this.is_forwarder(inode), "Filesystem delete_forwarder: expected forwarder"); + + inode.status = STATUS_INVALID; + this.mounts[inode.mount_id].backtrack.delete(inode.foreign_id); +}; + +/** + * @private + * @param {Inode} inode + * @return {FS} + */ +FS.prototype.follow_fs = function(inode) +{ + const mount = this.mounts[inode.mount_id]; + + dbg_assert(this.is_forwarder(inode), + "Filesystem follow_fs: inode should be a forwarding inode"); + dbg_assert(mount, "Filesystem follow_fs: inode should point to valid mounted FS"); + + return mount.fs; +}; + +/** + * Mount another filesystem to given path. + * @param {string} path + * @param {FS} fs + * @return {number} inode id of mount point if successful, or -errno if mounting failed. + */ +FS.prototype.Mount = function(path, fs) +{ + dbg_assert(fs.qidcounter === this.qidcounter, + "Cannot mount filesystem whose qid numbers aren't synchronised with current filesystem."); + + const path_infos = this.SearchPath(path); + + if(path_infos.parentid === -1) + { + dbg_log("Mount failed: parent for path not found: " + path, LOG_9P); + return -ENOENT; + } + if(path_infos.id !== -1) + { + dbg_log("Mount failed: file already exists at path: " + path, LOG_9P); + return -EEXIST; + } + if(path_infos.forward_path) + { + const parent = this.inodes[path_infos.parentid]; + const ret = this.follow_fs(parent).Mount(path_infos.forward_path, fs); + if(ret < 0) return ret; + return this.get_forwarder(parent.mount_id, ret); + } + + const mount_id = this.mounts.length; + this.mounts.push(new FSMountInfo(fs)); + + const idx = this.create_forwarder(mount_id, 0); + this.link_under_dir(path_infos.parentid, idx, path_infos.name); + + return idx; +}; + +/** + * @constructor + */ +function FSLockRegion() +{ + this.type = P9_LOCK_TYPE_UNLCK; + this.start = 0; + this.length = Infinity; + this.proc_id = -1; + this.client_id = ""; +} + +FSLockRegion.prototype.get_state = function() +{ + const state = []; + + state[0] = this.type; + state[1] = this.start; + // Infinity is not JSON.stringify-able + state[2] = this.length === Infinity ? 0 : this.length; + state[3] = this.proc_id; + state[4] = this.client_id; + + return state; +}; + +FSLockRegion.prototype.set_state = function(state) +{ + this.type = state[0]; + this.start = state[1]; + this.length = state[2] === 0 ? Infinity : state[2]; + this.proc_id = state[3]; + this.client_id = state[4]; +}; + +/** + * @return {FSLockRegion} + */ +FSLockRegion.prototype.clone = function() +{ + const new_region = new FSLockRegion(); + new_region.set_state(this.get_state()); + return new_region; +}; + +/** + * @param {FSLockRegion} region + * @return {boolean} + */ +FSLockRegion.prototype.conflicts_with = function(region) +{ + if(this.proc_id === region.proc_id && this.client_id === region.client_id) return false; + if(this.type === P9_LOCK_TYPE_UNLCK || region.type === P9_LOCK_TYPE_UNLCK) return false; + if(this.type !== P9_LOCK_TYPE_WRLCK && region.type !== P9_LOCK_TYPE_WRLCK) return false; + if(this.start + this.length <= region.start) return false; + if(region.start + region.length <= this.start) return false; + return true; +}; + +/** + * @param {FSLockRegion} region + * @return {boolean} + */ +FSLockRegion.prototype.is_alike = function(region) +{ + return region.proc_id === this.proc_id && + region.client_id === this.client_id && + region.type === this.type; +}; + +/** + * @param {FSLockRegion} region + * @return {boolean} + */ +FSLockRegion.prototype.may_merge_after = function(region) +{ + return this.is_alike(region) && region.start + region.length === this.start; +}; + +/** + * @param {number} type + * @param {number} start + * @param {number} length + * @param {number} proc_id + * @param {string} client_id + * @return {!FSLockRegion} + */ +FS.prototype.DescribeLock = function(type, start, length, proc_id, client_id) +{ + dbg_assert(type === P9_LOCK_TYPE_RDLCK || + type === P9_LOCK_TYPE_WRLCK || + type === P9_LOCK_TYPE_UNLCK, + "Filesystem: Invalid lock type: " + type); + dbg_assert(start >= 0, "Filesystem: Invalid negative lock starting offset: " + start); + dbg_assert(length > 0, "Filesystem: Invalid non-positive lock length: " + length); + + const lock = new FSLockRegion(); + lock.type = type; + lock.start = start; + lock.length = length; + lock.proc_id = proc_id; + lock.client_id = client_id; + + return lock; +}; + +/** + * @param {number} id + * @param {FSLockRegion} request + * @return {FSLockRegion} The first conflicting lock found, or null if requested lock is possible. + */ +FS.prototype.GetLock = function(id, request) +{ + const inode = this.inodes[id]; + + if(this.is_forwarder(inode)) + { + const foreign_id = inode.foreign_id; + return this.follow_fs(inode).GetLock(foreign_id, request); + } + + for(const region of inode.locks) + { + if(request.conflicts_with(region)) + { + return region.clone(); + } + } + return null; +}; + +/** + * @param {number} id + * @param {FSLockRegion} request + * @param {number} flags + * @return {number} One of P9_LOCK_SUCCESS / P9_LOCK_BLOCKED / P9_LOCK_ERROR / P9_LOCK_GRACE. + */ +FS.prototype.Lock = function(id, request, flags) +{ + const inode = this.inodes[id]; + + if(this.is_forwarder(inode)) + { + const foreign_id = inode.foreign_id; + return this.follow_fs(inode).Lock(foreign_id, request, flags); + } + + request = request.clone(); + + // (1) Check whether lock is possible before any modification. + if(request.type !== P9_LOCK_TYPE_UNLCK && this.GetLock(id, request)) + { + return P9_LOCK_BLOCKED; + } + + // (2) Subtract requested region from locks of the same owner. + for(let i = 0; i < inode.locks.length; i++) + { + const region = inode.locks[i]; + + dbg_assert(region.length > 0, + "Filesystem: Found non-positive lock region length: " + region.length); + dbg_assert(region.type === P9_LOCK_TYPE_RDLCK || region.type === P9_LOCK_TYPE_WRLCK, + "Filesystem: Found invalid lock type: " + region.type); + dbg_assert(!inode.locks[i-1] || inode.locks[i-1].start <= region.start, + "Filesystem: Locks should be sorted by starting offset"); + + // Skip to requested region. + if(region.start + region.length <= request.start) continue; + + // Check whether we've skipped past the requested region. + if(request.start + request.length <= region.start) break; + + // Skip over locks of different owners. + if(region.proc_id !== request.proc_id || region.client_id !== request.client_id) + { + dbg_assert(!region.conflicts_with(request), + "Filesytem: Found conflicting lock region, despite already checked for conflicts"); + continue; + } + + // Pretend region would be split into parts 1 and 2. + const start1 = region.start; + const start2 = request.start + request.length; + const length1 = request.start - start1; + const length2 = region.start + region.length - start2; + + if(length1 > 0 && length2 > 0 && region.type === request.type) + { + // Requested region is already locked with the required type. + // Return early - no need to modify anything. + return P9_LOCK_SUCCESS; + } + + if(length1 > 0) + { + // Shrink from right / first half of the split. + region.length = length1; + } + + if(length1 <= 0 && length2 > 0) + { + // Shrink from left. + region.start = start2; + region.length = length2; + } + else if(length2 > 0) + { + // Add second half of the split. + + // Fast-forward to correct location. + while(i < inode.locks.length && inode.locks[i].start < start2) i++; + + inode.locks.splice(i, 0, + this.DescribeLock(region.type, start2, length2, region.proc_id, region.client_id)); + } + else if(length1 <= 0) + { + // Requested region completely covers this region. Delete. + inode.locks.splice(i, 1); + i--; + } + } + + // (3) Insert requested lock region as a whole. + // No point in adding the requested lock region as fragmented bits in the above loop + // and having to merge them all back into one. + if(request.type !== P9_LOCK_TYPE_UNLCK) + { + let new_region = request; + let has_merged = false; + let i = 0; + + // Fast-forward to requested position, and try merging with previous region. + for(; i < inode.locks.length; i++) + { + if(new_region.may_merge_after(inode.locks[i])) + { + inode.locks[i].length += request.length; + new_region = inode.locks[i]; + has_merged = true; + } + if(request.start <= inode.locks[i].start) break; + } + + if(!has_merged) + { + inode.locks.splice(i, 0, new_region); + i++; + } + + // Try merging with the subsequent alike region. + for(; i < inode.locks.length; i++) + { + if(!inode.locks[i].is_alike(new_region)) continue; + + if(inode.locks[i].may_merge_after(new_region)) + { + new_region.length += inode.locks[i].length; + inode.locks.splice(i, 1); + } + + // No more mergable regions after this. + break; + } + } + + return P9_LOCK_SUCCESS; +}; + +FS.prototype.read_dir = function(path) +{ + const p = this.SearchPath(path); + + if(p.id === -1) + { + return undefined; + } + + const dir = this.GetInode(p.id); + + return Array.from(dir.direntries.keys()).filter(path => path !== "." && path !== ".."); +}; + +FS.prototype.read_file = function(file) +{ + const p = this.SearchPath(file); + + if(p.id === -1) + { + return Promise.resolve(null); + } + + const inode = this.GetInode(p.id); + + return this.Read(p.id, 0, inode.size); +}; diff --git a/lib/jor1k.js b/lib/jor1k.js new file mode 100644 index 0000000..d6852b0 --- /dev/null +++ b/lib/jor1k.js @@ -0,0 +1,107 @@ +"use strict"; + +// jor1k compatibility + +var VIRTIO_MAGIC_REG = 0x0; +var VIRTIO_VERSION_REG = 0x4; +var VIRTIO_DEVICE_REG = 0x8; +var VIRTIO_VENDOR_REG = 0xc; +var VIRTIO_HOSTFEATURES_REG = 0x10; +var VIRTIO_HOSTFEATURESSEL_REG = 0x14; +var VIRTIO_GUESTFEATURES_REG = 0x20; +var VIRTIO_GUESTFEATURESSEL_REG = 0x24; +var VIRTIO_GUEST_PAGE_SIZE_REG = 0x28; +var VIRTIO_QUEUESEL_REG = 0x30; +var VIRTIO_QUEUENUMMAX_REG = 0x34; +var VIRTIO_QUEUENUM_REG = 0x38; +var VIRTIO_QUEUEALIGN_REG = 0x3C; +var VIRTIO_QUEUEPFN_REG = 0x40; +var VIRTIO_QUEUENOTIFY_REG = 0x50; +var VIRTIO_INTERRUPTSTATUS_REG = 0x60; +var VIRTIO_INTERRUPTACK_REG = 0x64; +var VIRTIO_STATUS_REG = 0x70; + +/** @const */ +var VRING_DESC_F_NEXT = 1; /* This marks a buffer as continuing via the next field. */ +/** @const */ +var VRING_DESC_F_WRITE = 2; /* This marks a buffer as write-only (otherwise read-only). */ +/** @const */ +var VRING_DESC_F_INDIRECT = 4; /* This means the buffer contains a list of buffer descriptors. */ + + +function hex8(n) +{ + return h(n); +} + +var message = {}; + +/** @param {...string} log */ +message.Debug = function(log) +{ + dbg_log([].slice.apply(arguments).join(" "), LOG_9P); +}; + +message.Abort = function() +{ + if(DEBUG) + { + throw new Error("message.Abort()"); + } +}; + + +// XXX: Should go through emulator interface +var LoadBinaryResource; + +if(typeof XMLHttpRequest !== "undefined") +{ + LoadBinaryResource = function(url, OnSuccess, OnError) { + var req = new XMLHttpRequest(); + req.open('GET', url, true); + req.responseType = "arraybuffer"; + req.onreadystatechange = function () { + if (req.readyState != 4) { + return; + } + if ((req.status != 200) && (req.status != 0)) { + OnError("Error: Could not load file " + url); + return; + } + var arrayBuffer = req.response; + if (arrayBuffer) { + OnSuccess(arrayBuffer); + } else { + OnError("Error: No data received from: " + url); + } + }; + /* + req.onload = function(e) + { + var arrayBuffer = req.response; + if (arrayBuffer) { + OnLoadFunction(arrayBuffer); + } + }; + */ + req.send(null); + }; +} +else +{ + LoadBinaryResource = function(url, OnSuccess, OnError) + { + //console.log(url); + require("fs")["readFile"](url, function(err, data) + { + if(err) + { + OnError(err); + } + else + { + OnSuccess(data.buffer); + } + }); + }; +} diff --git a/lib/marshall.js b/lib/marshall.js new file mode 100644 index 0000000..7c4c7c7 --- /dev/null +++ b/lib/marshall.js @@ -0,0 +1,133 @@ +// ------------------------------------------------- +// ------------------ Marshall --------------------- +// ------------------------------------------------- +// helper functions for virtio and 9p. + +"use strict"; + +var marshall = {}; + + +// Inserts data from an array to a byte aligned struct in memory +marshall.Marshall = function(typelist, input, struct, offset) { + var item; + var size = 0; + for (var i=0; i < typelist.length; i++) { + item = input[i]; + switch (typelist[i]) { + case "w": + struct[offset++] = item & 0xFF; + struct[offset++] = (item >> 8) & 0xFF; + struct[offset++] = (item >> 16) & 0xFF; + struct[offset++] = (item >> 24) & 0xFF; + size += 4; + break; + case "d": // double word + struct[offset++] = item & 0xFF; + struct[offset++] = (item >> 8) & 0xFF; + struct[offset++] = (item >> 16) & 0xFF; + struct[offset++] = (item >> 24) & 0xFF; + struct[offset++] = 0x0; + struct[offset++] = 0x0; + struct[offset++] = 0x0; + struct[offset++] = 0x0; + size += 8; + break; + case "h": + struct[offset++] = item & 0xFF; + struct[offset++] = item >> 8; + size += 2; + break; + case "b": + struct[offset++] = item; + size += 1; + break; + case "s": + var lengthoffset = offset; + var length = 0; + struct[offset++] = 0; // set the length later + struct[offset++] = 0; + size += 2; + for (var j of item) { + var utf8 = UnicodeToUTF8Stream(j.charCodeAt(0)); + utf8.forEach( function(c) { + struct[offset++] = c; + size += 1; + length++; + }); + } + struct[lengthoffset+0] = length & 0xFF; + struct[lengthoffset+1] = (length >> 8) & 0xFF; + break; + case "Q": + marshall.Marshall(["b", "w", "d"], [item.type, item.version, item.path], struct, offset); + offset += 13; + size += 13; + break; + default: + message.Debug("Marshall: Unknown type=" + typelist[i]); + break; + } + } + return size; +}; + + +// Extracts data from a byte aligned struct in memory to an array +marshall.Unmarshall = function(typelist, struct, state) { + let offset = state.offset; + var output = []; + for (var i=0; i < typelist.length; i++) { + switch (typelist[i]) { + case "w": + var val = struct[offset++]; + val += struct[offset++] << 8; + val += struct[offset++] << 16; + val += (struct[offset++] << 24) >>> 0; + output.push(val); + break; + case "d": + var val = struct[offset++]; + val += struct[offset++] << 8; + val += struct[offset++] << 16; + val += (struct[offset++] << 24) >>> 0; + offset += 4; + output.push(val); + break; + case "h": + var val = struct[offset++]; + output.push(val + (struct[offset++] << 8)); + break; + case "b": + output.push(struct[offset++]); + break; + case "s": + var len = struct[offset++]; + len += struct[offset++] << 8; + var str = ''; + var utf8converter = new UTF8StreamToUnicode(); + for (var j=0; j < len; j++) { + var c = utf8converter.Put(struct[offset++]); + if (c == -1) continue; + str += String.fromCharCode(c); + } + output.push(str); + break; + case "Q": + state.offset = offset; + const qid = marshall.Unmarshall(["b", "w", "d"], struct, state); + offset = state.offset; + output.push({ + type: qid[0], + version: qid[1], + path: qid[2], + }); + break; + default: + message.Debug("Error in Unmarshall: Unknown type=" + typelist[i]); + break; + } + } + state.offset = offset; + return output; +}; diff --git a/lib/softfloat/softfloat.c b/lib/softfloat/softfloat.c new file mode 100644 index 0000000..a95347e --- /dev/null +++ b/lib/softfloat/softfloat.c @@ -0,0 +1,32501 @@ +/**** start inlining ../../source/8086-SSE/softfloat_raiseFlags.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +/**** start inlining platform.h ****/ + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +#define LITTLEENDIAN 1 + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +#ifdef __GNUC_STDC_INLINE__ +#define INLINE inline +#else +#define INLINE extern inline +#endif + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +#define SOFTFLOAT_BUILTIN_CLZ 1 +#define SOFTFLOAT_INTRINSIC_INT128 1 +/**** start inlining opts-GCC.h ****/ + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2017 The Regents of the University of California. All rights +reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#ifndef opts_GCC_h +#define opts_GCC_h 1 + +#ifdef INLINE + +#include +/**** start inlining primitiveTypes.h ****/ + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#ifndef primitiveTypes_h +#define primitiveTypes_h 1 + +#include + +#ifdef SOFTFLOAT_FAST_INT64 + +#ifdef LITTLEENDIAN +struct uint128 { uint64_t v0, v64; }; +struct uint64_extra { uint64_t extra, v; }; +struct uint128_extra { uint64_t extra; struct uint128 v; }; +#else +struct uint128 { uint64_t v64, v0; }; +struct uint64_extra { uint64_t v, extra; }; +struct uint128_extra { struct uint128 v; uint64_t extra; }; +#endif + +#endif + +/*---------------------------------------------------------------------------- +| These macros are used to isolate the differences in word order between big- +| endian and little-endian platforms. +*----------------------------------------------------------------------------*/ +#ifdef LITTLEENDIAN +#define wordIncr 1 +#define indexWord( total, n ) (n) +#define indexWordHi( total ) ((total) - 1) +#define indexWordLo( total ) 0 +#define indexMultiword( total, m, n ) (n) +#define indexMultiwordHi( total, n ) ((total) - (n)) +#define indexMultiwordLo( total, n ) 0 +#define indexMultiwordHiBut( total, n ) (n) +#define indexMultiwordLoBut( total, n ) 0 +#define INIT_UINTM4( v3, v2, v1, v0 ) { v0, v1, v2, v3 } +#else +#define wordIncr -1 +#define indexWord( total, n ) ((total) - 1 - (n)) +#define indexWordHi( total ) 0 +#define indexWordLo( total ) ((total) - 1) +#define indexMultiword( total, m, n ) ((total) - 1 - (m)) +#define indexMultiwordHi( total, n ) 0 +#define indexMultiwordLo( total, n ) ((total) - (n)) +#define indexMultiwordHiBut( total, n ) 0 +#define indexMultiwordLoBut( total, n ) (n) +#define INIT_UINTM4( v3, v2, v1, v0 ) { v3, v2, v1, v0 } +#endif + +#endif + +/**** ended inlining primitiveTypes.h ****/ + +#ifdef SOFTFLOAT_BUILTIN_CLZ + +INLINE uint_fast8_t softfloat_countLeadingZeros16( uint16_t a ) + { return a ? __builtin_clz( a ) - 16 : 16; } +#define softfloat_countLeadingZeros16 softfloat_countLeadingZeros16 + +INLINE uint_fast8_t softfloat_countLeadingZeros32( uint32_t a ) + { return a ? __builtin_clz( a ) : 32; } +#define softfloat_countLeadingZeros32 softfloat_countLeadingZeros32 + +INLINE uint_fast8_t softfloat_countLeadingZeros64( uint64_t a ) + { return a ? __builtin_clzll( a ) : 64; } +#define softfloat_countLeadingZeros64 softfloat_countLeadingZeros64 + +#endif + +#ifdef SOFTFLOAT_INTRINSIC_INT128 + +INLINE struct uint128 softfloat_mul64ByShifted32To128( uint64_t a, uint32_t b ) +{ + union { unsigned __int128 ui; struct uint128 s; } uZ; + uZ.ui = (unsigned __int128) a * ((uint_fast64_t) b<<32); + return uZ.s; +} +#define softfloat_mul64ByShifted32To128 softfloat_mul64ByShifted32To128 + +INLINE struct uint128 softfloat_mul64To128( uint64_t a, uint64_t b ) +{ + union { unsigned __int128 ui; struct uint128 s; } uZ; + uZ.ui = (unsigned __int128) a * b; + return uZ.s; +} +#define softfloat_mul64To128 softfloat_mul64To128 + +INLINE +struct uint128 softfloat_mul128By32( uint64_t a64, uint64_t a0, uint32_t b ) +{ + union { unsigned __int128 ui; struct uint128 s; } uZ; + uZ.ui = ((unsigned __int128) a64<<64 | a0) * b; + return uZ.s; +} +#define softfloat_mul128By32 softfloat_mul128By32 + +INLINE +void + softfloat_mul128To256M( + uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0, uint64_t *zPtr ) +{ + unsigned __int128 z0, mid1, mid, z128; + z0 = (unsigned __int128) a0 * b0; + mid1 = (unsigned __int128) a64 * b0; + mid = mid1 + (unsigned __int128) a0 * b64; + z128 = (unsigned __int128) a64 * b64; + z128 += (unsigned __int128) (mid < mid1)<<64 | mid>>64; + mid <<= 64; + z0 += mid; + z128 += (z0 < mid); + zPtr[indexWord( 4, 0 )] = z0; + zPtr[indexWord( 4, 1 )] = z0>>64; + zPtr[indexWord( 4, 2 )] = z128; + zPtr[indexWord( 4, 3 )] = z128>>64; +} +#define softfloat_mul128To256M softfloat_mul128To256M + +#endif + +#endif + +#endif + +/**** ended inlining opts-GCC.h ****/ + +/**** ended inlining platform.h ****/ +/**** start inlining softfloat.h ****/ + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + + +/*============================================================================ +| Note: If SoftFloat is made available as a general library for programs to +| use, it is strongly recommended that a platform-specific version of this +| header, "softfloat.h", be created that folds in "softfloat_types.h" and that +| eliminates all dependencies on compile-time macros. +*============================================================================*/ + + +#ifndef softfloat_h +#define softfloat_h 1 + +#include +#include +/**** start inlining softfloat_types.h ****/ + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#ifndef softfloat_types_h +#define softfloat_types_h 1 + +#include + +/*---------------------------------------------------------------------------- +| Types used to pass 16-bit, 32-bit, 64-bit, and 128-bit floating-point +| arguments and results to/from functions. These types must be exactly +| 16 bits, 32 bits, 64 bits, and 128 bits in size, respectively. Where a +| platform has "native" support for IEEE-Standard floating-point formats, +| the types below may, if desired, be defined as aliases for the native types +| (typically 'float' and 'double', and possibly 'long double'). +*----------------------------------------------------------------------------*/ +typedef struct { uint16_t v; } float16_t; +typedef struct { uint32_t v; } float32_t; +typedef struct { uint64_t v; } float64_t; +typedef struct { uint64_t v[2]; } float128_t; + +/*---------------------------------------------------------------------------- +| The format of an 80-bit extended floating-point number in memory. This +| structure must contain a 16-bit field named 'signExp' and a 64-bit field +| named 'signif'. +*----------------------------------------------------------------------------*/ +#ifdef LITTLEENDIAN +struct extFloat80M { uint64_t signif; uint16_t signExp; }; +#else +struct extFloat80M { uint16_t signExp; uint64_t signif; }; +#endif + +/*---------------------------------------------------------------------------- +| The type used to pass 80-bit extended floating-point arguments and +| results to/from functions. This type must have size identical to +| 'struct extFloat80M'. Type 'extFloat80_t' can be defined as an alias for +| 'struct extFloat80M'. Alternatively, if a platform has "native" support +| for IEEE-Standard 80-bit extended floating-point, it may be possible, +| if desired, to define 'extFloat80_t' as an alias for the native type +| (presumably either 'long double' or a nonstandard compiler-intrinsic type). +| In that case, the 'signif' and 'signExp' fields of 'struct extFloat80M' +| must align exactly with the locations in memory of the sign, exponent, and +| significand of the native type. +*----------------------------------------------------------------------------*/ +typedef struct extFloat80M extFloat80_t; + +#endif + +/**** ended inlining softfloat_types.h ****/ + +#ifndef THREAD_LOCAL +#define THREAD_LOCAL +#endif + +/*---------------------------------------------------------------------------- +| Software floating-point underflow tininess-detection mode. +*----------------------------------------------------------------------------*/ +extern THREAD_LOCAL uint_fast8_t softfloat_detectTininess; +enum { + softfloat_tininess_beforeRounding = 0, + softfloat_tininess_afterRounding = 1 +}; + +/*---------------------------------------------------------------------------- +| Software floating-point rounding mode. (Mode "odd" is supported only if +| SoftFloat is compiled with macro 'SOFTFLOAT_ROUND_ODD' defined.) +*----------------------------------------------------------------------------*/ +extern THREAD_LOCAL uint_fast8_t softfloat_roundingMode; +enum { + softfloat_round_near_even = 0, + softfloat_round_minMag = 1, + softfloat_round_min = 2, + softfloat_round_max = 3, + softfloat_round_near_maxMag = 4, + softfloat_round_odd = 6 +}; + +/*---------------------------------------------------------------------------- +| Software floating-point exception flags. +*----------------------------------------------------------------------------*/ +extern THREAD_LOCAL uint_fast8_t softfloat_exceptionFlags; +enum { + softfloat_flag_inexact = 1, + softfloat_flag_underflow = 2, + softfloat_flag_overflow = 4, + softfloat_flag_infinite = 8, + softfloat_flag_invalid = 16 +}; + +/*---------------------------------------------------------------------------- +| Routine to raise any or all of the software floating-point exception flags. +*----------------------------------------------------------------------------*/ +void softfloat_raiseFlags( uint_fast8_t ); + +/*---------------------------------------------------------------------------- +| Integer-to-floating-point conversion routines. +*----------------------------------------------------------------------------*/ +float16_t ui32_to_f16( uint32_t ); +float32_t ui32_to_f32( uint32_t ); +float64_t ui32_to_f64( uint32_t ); +#ifdef SOFTFLOAT_FAST_INT64 +extFloat80_t ui32_to_extF80( uint32_t ); +float128_t ui32_to_f128( uint32_t ); +#endif +void ui32_to_extF80M( uint32_t, extFloat80_t * ); +void ui32_to_f128M( uint32_t, float128_t * ); +float16_t ui64_to_f16( uint64_t ); +float32_t ui64_to_f32( uint64_t ); +float64_t ui64_to_f64( uint64_t ); +#ifdef SOFTFLOAT_FAST_INT64 +extFloat80_t ui64_to_extF80( uint64_t ); +float128_t ui64_to_f128( uint64_t ); +#endif +void ui64_to_extF80M( uint64_t, extFloat80_t * ); +void ui64_to_f128M( uint64_t, float128_t * ); +float16_t i32_to_f16( int32_t ); +float32_t i32_to_f32( int32_t ); +float64_t i32_to_f64( int32_t ); +#ifdef SOFTFLOAT_FAST_INT64 +extFloat80_t i32_to_extF80( int32_t ); +float128_t i32_to_f128( int32_t ); +#endif +void i32_to_extF80M( int32_t, extFloat80_t * ); +void i32_to_f128M( int32_t, float128_t * ); +float16_t i64_to_f16( int64_t ); +float32_t i64_to_f32( int64_t ); +float64_t i64_to_f64( int64_t ); +#ifdef SOFTFLOAT_FAST_INT64 +extFloat80_t i64_to_extF80( int64_t ); +float128_t i64_to_f128( int64_t ); +#endif +void i64_to_extF80M( int64_t, extFloat80_t * ); +void i64_to_f128M( int64_t, float128_t * ); + +/*---------------------------------------------------------------------------- +| 16-bit (half-precision) floating-point operations. +*----------------------------------------------------------------------------*/ +uint_fast32_t f16_to_ui32( float16_t, uint_fast8_t, bool ); +uint_fast64_t f16_to_ui64( float16_t, uint_fast8_t, bool ); +int_fast32_t f16_to_i32( float16_t, uint_fast8_t, bool ); +int_fast64_t f16_to_i64( float16_t, uint_fast8_t, bool ); +uint_fast32_t f16_to_ui32_r_minMag( float16_t, bool ); +uint_fast64_t f16_to_ui64_r_minMag( float16_t, bool ); +int_fast32_t f16_to_i32_r_minMag( float16_t, bool ); +int_fast64_t f16_to_i64_r_minMag( float16_t, bool ); +float32_t f16_to_f32( float16_t ); +float64_t f16_to_f64( float16_t ); +#ifdef SOFTFLOAT_FAST_INT64 +extFloat80_t f16_to_extF80( float16_t ); +float128_t f16_to_f128( float16_t ); +#endif +void f16_to_extF80M( float16_t, extFloat80_t * ); +void f16_to_f128M( float16_t, float128_t * ); +float16_t f16_roundToInt( float16_t, uint_fast8_t, bool ); +float16_t f16_add( float16_t, float16_t ); +float16_t f16_sub( float16_t, float16_t ); +float16_t f16_mul( float16_t, float16_t ); +float16_t f16_mulAdd( float16_t, float16_t, float16_t ); +float16_t f16_div( float16_t, float16_t ); +float16_t f16_rem( float16_t, float16_t ); +float16_t f16_sqrt( float16_t ); +bool f16_eq( float16_t, float16_t ); +bool f16_le( float16_t, float16_t ); +bool f16_lt( float16_t, float16_t ); +bool f16_eq_signaling( float16_t, float16_t ); +bool f16_le_quiet( float16_t, float16_t ); +bool f16_lt_quiet( float16_t, float16_t ); +bool f16_isSignalingNaN( float16_t ); + +/*---------------------------------------------------------------------------- +| 32-bit (single-precision) floating-point operations. +*----------------------------------------------------------------------------*/ +uint_fast32_t f32_to_ui32( float32_t, uint_fast8_t, bool ); +uint_fast64_t f32_to_ui64( float32_t, uint_fast8_t, bool ); +int_fast32_t f32_to_i32( float32_t, uint_fast8_t, bool ); +int_fast64_t f32_to_i64( float32_t, uint_fast8_t, bool ); +uint_fast32_t f32_to_ui32_r_minMag( float32_t, bool ); +uint_fast64_t f32_to_ui64_r_minMag( float32_t, bool ); +int_fast32_t f32_to_i32_r_minMag( float32_t, bool ); +int_fast64_t f32_to_i64_r_minMag( float32_t, bool ); +float16_t f32_to_f16( float32_t ); +float64_t f32_to_f64( float32_t ); +#ifdef SOFTFLOAT_FAST_INT64 +extFloat80_t f32_to_extF80( float32_t ); +float128_t f32_to_f128( float32_t ); +#endif +void f32_to_extF80M( float32_t, extFloat80_t * ); +void f32_to_f128M( float32_t, float128_t * ); +float32_t f32_roundToInt( float32_t, uint_fast8_t, bool ); +float32_t f32_add( float32_t, float32_t ); +float32_t f32_sub( float32_t, float32_t ); +float32_t f32_mul( float32_t, float32_t ); +float32_t f32_mulAdd( float32_t, float32_t, float32_t ); +float32_t f32_div( float32_t, float32_t ); +float32_t f32_rem( float32_t, float32_t ); +float32_t f32_sqrt( float32_t ); +bool f32_eq( float32_t, float32_t ); +bool f32_le( float32_t, float32_t ); +bool f32_lt( float32_t, float32_t ); +bool f32_eq_signaling( float32_t, float32_t ); +bool f32_le_quiet( float32_t, float32_t ); +bool f32_lt_quiet( float32_t, float32_t ); +bool f32_isSignalingNaN( float32_t ); + +/*---------------------------------------------------------------------------- +| 64-bit (double-precision) floating-point operations. +*----------------------------------------------------------------------------*/ +uint_fast32_t f64_to_ui32( float64_t, uint_fast8_t, bool ); +uint_fast64_t f64_to_ui64( float64_t, uint_fast8_t, bool ); +int_fast32_t f64_to_i32( float64_t, uint_fast8_t, bool ); +int_fast64_t f64_to_i64( float64_t, uint_fast8_t, bool ); +uint_fast32_t f64_to_ui32_r_minMag( float64_t, bool ); +uint_fast64_t f64_to_ui64_r_minMag( float64_t, bool ); +int_fast32_t f64_to_i32_r_minMag( float64_t, bool ); +int_fast64_t f64_to_i64_r_minMag( float64_t, bool ); +float16_t f64_to_f16( float64_t ); +float32_t f64_to_f32( float64_t ); +#ifdef SOFTFLOAT_FAST_INT64 +extFloat80_t f64_to_extF80( float64_t ); +float128_t f64_to_f128( float64_t ); +#endif +void f64_to_extF80M( float64_t, extFloat80_t * ); +void f64_to_f128M( float64_t, float128_t * ); +float64_t f64_roundToInt( float64_t, uint_fast8_t, bool ); +float64_t f64_add( float64_t, float64_t ); +float64_t f64_sub( float64_t, float64_t ); +float64_t f64_mul( float64_t, float64_t ); +float64_t f64_mulAdd( float64_t, float64_t, float64_t ); +float64_t f64_div( float64_t, float64_t ); +float64_t f64_rem( float64_t, float64_t ); +float64_t f64_sqrt( float64_t ); +bool f64_eq( float64_t, float64_t ); +bool f64_le( float64_t, float64_t ); +bool f64_lt( float64_t, float64_t ); +bool f64_eq_signaling( float64_t, float64_t ); +bool f64_le_quiet( float64_t, float64_t ); +bool f64_lt_quiet( float64_t, float64_t ); +bool f64_isSignalingNaN( float64_t ); + +/*---------------------------------------------------------------------------- +| Rounding precision for 80-bit extended double-precision floating-point. +| Valid values are 32, 64, and 80. +*----------------------------------------------------------------------------*/ +extern THREAD_LOCAL uint_fast8_t extF80_roundingPrecision; + +/*---------------------------------------------------------------------------- +| 80-bit extended double-precision floating-point operations. +*----------------------------------------------------------------------------*/ +#ifdef SOFTFLOAT_FAST_INT64 +uint_fast32_t extF80_to_ui32( extFloat80_t, uint_fast8_t, bool ); +uint_fast64_t extF80_to_ui64( extFloat80_t, uint_fast8_t, bool ); +int_fast32_t extF80_to_i32( extFloat80_t, uint_fast8_t, bool ); +int_fast64_t extF80_to_i64( extFloat80_t, uint_fast8_t, bool ); +uint_fast32_t extF80_to_ui32_r_minMag( extFloat80_t, bool ); +uint_fast64_t extF80_to_ui64_r_minMag( extFloat80_t, bool ); +int_fast32_t extF80_to_i32_r_minMag( extFloat80_t, bool ); +int_fast64_t extF80_to_i64_r_minMag( extFloat80_t, bool ); +float16_t extF80_to_f16( extFloat80_t ); +float32_t extF80_to_f32( extFloat80_t ); +float64_t extF80_to_f64( extFloat80_t ); +float128_t extF80_to_f128( extFloat80_t ); +extFloat80_t extF80_roundToInt( extFloat80_t, uint_fast8_t, bool ); +extFloat80_t extF80_add( extFloat80_t, extFloat80_t ); +extFloat80_t extF80_sub( extFloat80_t, extFloat80_t ); +extFloat80_t extF80_mul( extFloat80_t, extFloat80_t ); +extFloat80_t extF80_div( extFloat80_t, extFloat80_t ); +extFloat80_t extF80_rem( extFloat80_t, extFloat80_t ); +extFloat80_t extF80_sqrt( extFloat80_t ); +bool extF80_eq( extFloat80_t, extFloat80_t ); +bool extF80_le( extFloat80_t, extFloat80_t ); +bool extF80_lt( extFloat80_t, extFloat80_t ); +bool extF80_eq_signaling( extFloat80_t, extFloat80_t ); +bool extF80_le_quiet( extFloat80_t, extFloat80_t ); +bool extF80_lt_quiet( extFloat80_t, extFloat80_t ); +bool extF80_isSignalingNaN( extFloat80_t ); +#endif +uint_fast32_t extF80M_to_ui32( const extFloat80_t *, uint_fast8_t, bool ); +uint_fast64_t extF80M_to_ui64( const extFloat80_t *, uint_fast8_t, bool ); +int_fast32_t extF80M_to_i32( const extFloat80_t *, uint_fast8_t, bool ); +int_fast64_t extF80M_to_i64( const extFloat80_t *, uint_fast8_t, bool ); +uint_fast32_t extF80M_to_ui32_r_minMag( const extFloat80_t *, bool ); +uint_fast64_t extF80M_to_ui64_r_minMag( const extFloat80_t *, bool ); +int_fast32_t extF80M_to_i32_r_minMag( const extFloat80_t *, bool ); +int_fast64_t extF80M_to_i64_r_minMag( const extFloat80_t *, bool ); +float16_t extF80M_to_f16( const extFloat80_t * ); +float32_t extF80M_to_f32( const extFloat80_t * ); +float64_t extF80M_to_f64( const extFloat80_t * ); +void extF80M_to_f128M( const extFloat80_t *, float128_t * ); +void + extF80M_roundToInt( + const extFloat80_t *, uint_fast8_t, bool, extFloat80_t * ); +void extF80M_add( const extFloat80_t *, const extFloat80_t *, extFloat80_t * ); +void extF80M_sub( const extFloat80_t *, const extFloat80_t *, extFloat80_t * ); +void extF80M_mul( const extFloat80_t *, const extFloat80_t *, extFloat80_t * ); +void extF80M_div( const extFloat80_t *, const extFloat80_t *, extFloat80_t * ); +void extF80M_rem( const extFloat80_t *, const extFloat80_t *, extFloat80_t * ); +void extF80M_sqrt( const extFloat80_t *, extFloat80_t * ); +bool extF80M_eq( const extFloat80_t *, const extFloat80_t * ); +bool extF80M_le( const extFloat80_t *, const extFloat80_t * ); +bool extF80M_lt( const extFloat80_t *, const extFloat80_t * ); +bool extF80M_eq_signaling( const extFloat80_t *, const extFloat80_t * ); +bool extF80M_le_quiet( const extFloat80_t *, const extFloat80_t * ); +bool extF80M_lt_quiet( const extFloat80_t *, const extFloat80_t * ); +bool extF80M_isSignalingNaN( const extFloat80_t * ); + +/*---------------------------------------------------------------------------- +| 128-bit (quadruple-precision) floating-point operations. +*----------------------------------------------------------------------------*/ +#ifdef SOFTFLOAT_FAST_INT64 +uint_fast32_t f128_to_ui32( float128_t, uint_fast8_t, bool ); +uint_fast64_t f128_to_ui64( float128_t, uint_fast8_t, bool ); +int_fast32_t f128_to_i32( float128_t, uint_fast8_t, bool ); +int_fast64_t f128_to_i64( float128_t, uint_fast8_t, bool ); +uint_fast32_t f128_to_ui32_r_minMag( float128_t, bool ); +uint_fast64_t f128_to_ui64_r_minMag( float128_t, bool ); +int_fast32_t f128_to_i32_r_minMag( float128_t, bool ); +int_fast64_t f128_to_i64_r_minMag( float128_t, bool ); +float16_t f128_to_f16( float128_t ); +float32_t f128_to_f32( float128_t ); +float64_t f128_to_f64( float128_t ); +extFloat80_t f128_to_extF80( float128_t ); +float128_t f128_roundToInt( float128_t, uint_fast8_t, bool ); +float128_t f128_add( float128_t, float128_t ); +float128_t f128_sub( float128_t, float128_t ); +float128_t f128_mul( float128_t, float128_t ); +float128_t f128_mulAdd( float128_t, float128_t, float128_t ); +float128_t f128_div( float128_t, float128_t ); +float128_t f128_rem( float128_t, float128_t ); +float128_t f128_sqrt( float128_t ); +bool f128_eq( float128_t, float128_t ); +bool f128_le( float128_t, float128_t ); +bool f128_lt( float128_t, float128_t ); +bool f128_eq_signaling( float128_t, float128_t ); +bool f128_le_quiet( float128_t, float128_t ); +bool f128_lt_quiet( float128_t, float128_t ); +bool f128_isSignalingNaN( float128_t ); +#endif +uint_fast32_t f128M_to_ui32( const float128_t *, uint_fast8_t, bool ); +uint_fast64_t f128M_to_ui64( const float128_t *, uint_fast8_t, bool ); +int_fast32_t f128M_to_i32( const float128_t *, uint_fast8_t, bool ); +int_fast64_t f128M_to_i64( const float128_t *, uint_fast8_t, bool ); +uint_fast32_t f128M_to_ui32_r_minMag( const float128_t *, bool ); +uint_fast64_t f128M_to_ui64_r_minMag( const float128_t *, bool ); +int_fast32_t f128M_to_i32_r_minMag( const float128_t *, bool ); +int_fast64_t f128M_to_i64_r_minMag( const float128_t *, bool ); +float16_t f128M_to_f16( const float128_t * ); +float32_t f128M_to_f32( const float128_t * ); +float64_t f128M_to_f64( const float128_t * ); +void f128M_to_extF80M( const float128_t *, extFloat80_t * ); +void f128M_roundToInt( const float128_t *, uint_fast8_t, bool, float128_t * ); +void f128M_add( const float128_t *, const float128_t *, float128_t * ); +void f128M_sub( const float128_t *, const float128_t *, float128_t * ); +void f128M_mul( const float128_t *, const float128_t *, float128_t * ); +void + f128M_mulAdd( + const float128_t *, const float128_t *, const float128_t *, float128_t * + ); +void f128M_div( const float128_t *, const float128_t *, float128_t * ); +void f128M_rem( const float128_t *, const float128_t *, float128_t * ); +void f128M_sqrt( const float128_t *, float128_t * ); +bool f128M_eq( const float128_t *, const float128_t * ); +bool f128M_le( const float128_t *, const float128_t * ); +bool f128M_lt( const float128_t *, const float128_t * ); +bool f128M_eq_signaling( const float128_t *, const float128_t * ); +bool f128M_le_quiet( const float128_t *, const float128_t * ); +bool f128M_lt_quiet( const float128_t *, const float128_t * ); +bool f128M_isSignalingNaN( const float128_t * ); + +#endif + +/**** ended inlining softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Raises the exceptions specified by `flags'. Floating-point traps can be +| defined here if desired. It is currently not possible for such a trap +| to substitute a result value. If traps are not implemented, this routine +| should be simply `softfloat_exceptionFlags |= flags;'. +*----------------------------------------------------------------------------*/ +void softfloat_raiseFlags( uint_fast8_t flags ) +{ + + softfloat_exceptionFlags |= flags; + +} + +/**** ended inlining ../../source/8086-SSE/softfloat_raiseFlags.c ****/ +/**** start inlining ../../source/8086-SSE/s_f16UIToCommonNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** start inlining specialize.h ****/ + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2018 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#ifndef specialize_h +#define specialize_h 1 + +#include +#include +/**** skipping file: primitiveTypes.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Default value for 'softfloat_detectTininess'. +*----------------------------------------------------------------------------*/ +#define init_detectTininess softfloat_tininess_afterRounding + +/*---------------------------------------------------------------------------- +| The values to return on conversions to 32-bit integer formats that raise an +| invalid exception. +*----------------------------------------------------------------------------*/ +#define ui32_fromPosOverflow 0xFFFFFFFF +#define ui32_fromNegOverflow 0xFFFFFFFF +#define ui32_fromNaN 0xFFFFFFFF +#define i32_fromPosOverflow (-0x7FFFFFFF - 1) +#define i32_fromNegOverflow (-0x7FFFFFFF - 1) +#define i32_fromNaN (-0x7FFFFFFF - 1) + +/*---------------------------------------------------------------------------- +| The values to return on conversions to 64-bit integer formats that raise an +| invalid exception. +*----------------------------------------------------------------------------*/ +#define ui64_fromPosOverflow UINT64_C( 0xFFFFFFFFFFFFFFFF ) +#define ui64_fromNegOverflow UINT64_C( 0xFFFFFFFFFFFFFFFF ) +#define ui64_fromNaN UINT64_C( 0xFFFFFFFFFFFFFFFF ) +#define i64_fromPosOverflow (-INT64_C( 0x7FFFFFFFFFFFFFFF ) - 1) +#define i64_fromNegOverflow (-INT64_C( 0x7FFFFFFFFFFFFFFF ) - 1) +#define i64_fromNaN (-INT64_C( 0x7FFFFFFFFFFFFFFF ) - 1) + +/*---------------------------------------------------------------------------- +| "Common NaN" structure, used to transfer NaN representations from one format +| to another. +*----------------------------------------------------------------------------*/ +struct commonNaN { + bool sign; +#ifdef LITTLEENDIAN + uint64_t v0, v64; +#else + uint64_t v64, v0; +#endif +}; + +/*---------------------------------------------------------------------------- +| The bit pattern for a default generated 16-bit floating-point NaN. +*----------------------------------------------------------------------------*/ +#define defaultNaNF16UI 0xFE00 + +/*---------------------------------------------------------------------------- +| Returns true when 16-bit unsigned integer 'uiA' has the bit pattern of a +| 16-bit floating-point signaling NaN. +| Note: This macro evaluates its argument more than once. +*----------------------------------------------------------------------------*/ +#define softfloat_isSigNaNF16UI( uiA ) ((((uiA) & 0x7E00) == 0x7C00) && ((uiA) & 0x01FF)) + +/*---------------------------------------------------------------------------- +| Assuming 'uiA' has the bit pattern of a 16-bit floating-point NaN, converts +| this NaN to the common NaN form, and stores the resulting common NaN at the +| location pointed to by 'zPtr'. If the NaN is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +void softfloat_f16UIToCommonNaN( uint_fast16_t uiA, struct commonNaN *zPtr ); + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by 'aPtr' into a 16-bit floating-point +| NaN, and returns the bit pattern of this value as an unsigned integer. +*----------------------------------------------------------------------------*/ +uint_fast16_t softfloat_commonNaNToF16UI( const struct commonNaN *aPtr ); + +/*---------------------------------------------------------------------------- +| Interpreting 'uiA' and 'uiB' as the bit patterns of two 16-bit floating- +| point values, at least one of which is a NaN, returns the bit pattern of +| the combined NaN result. If either 'uiA' or 'uiB' has the pattern of a +| signaling NaN, the invalid exception is raised. +*----------------------------------------------------------------------------*/ +uint_fast16_t + softfloat_propagateNaNF16UI( uint_fast16_t uiA, uint_fast16_t uiB ); + +/*---------------------------------------------------------------------------- +| The bit pattern for a default generated 32-bit floating-point NaN. +*----------------------------------------------------------------------------*/ +#define defaultNaNF32UI 0xFFC00000 + +/*---------------------------------------------------------------------------- +| Returns true when 32-bit unsigned integer 'uiA' has the bit pattern of a +| 32-bit floating-point signaling NaN. +| Note: This macro evaluates its argument more than once. +*----------------------------------------------------------------------------*/ +#define softfloat_isSigNaNF32UI( uiA ) ((((uiA) & 0x7FC00000) == 0x7F800000) && ((uiA) & 0x003FFFFF)) + +/*---------------------------------------------------------------------------- +| Assuming 'uiA' has the bit pattern of a 32-bit floating-point NaN, converts +| this NaN to the common NaN form, and stores the resulting common NaN at the +| location pointed to by 'zPtr'. If the NaN is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +void softfloat_f32UIToCommonNaN( uint_fast32_t uiA, struct commonNaN *zPtr ); + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by 'aPtr' into a 32-bit floating-point +| NaN, and returns the bit pattern of this value as an unsigned integer. +*----------------------------------------------------------------------------*/ +uint_fast32_t softfloat_commonNaNToF32UI( const struct commonNaN *aPtr ); + +/*---------------------------------------------------------------------------- +| Interpreting 'uiA' and 'uiB' as the bit patterns of two 32-bit floating- +| point values, at least one of which is a NaN, returns the bit pattern of +| the combined NaN result. If either 'uiA' or 'uiB' has the pattern of a +| signaling NaN, the invalid exception is raised. +*----------------------------------------------------------------------------*/ +uint_fast32_t + softfloat_propagateNaNF32UI( uint_fast32_t uiA, uint_fast32_t uiB ); + +/*---------------------------------------------------------------------------- +| The bit pattern for a default generated 64-bit floating-point NaN. +*----------------------------------------------------------------------------*/ +#define defaultNaNF64UI UINT64_C( 0xFFF8000000000000 ) + +/*---------------------------------------------------------------------------- +| Returns true when 64-bit unsigned integer 'uiA' has the bit pattern of a +| 64-bit floating-point signaling NaN. +| Note: This macro evaluates its argument more than once. +*----------------------------------------------------------------------------*/ +#define softfloat_isSigNaNF64UI( uiA ) ((((uiA) & UINT64_C( 0x7FF8000000000000 )) == UINT64_C( 0x7FF0000000000000 )) && ((uiA) & UINT64_C( 0x0007FFFFFFFFFFFF ))) + +/*---------------------------------------------------------------------------- +| Assuming 'uiA' has the bit pattern of a 64-bit floating-point NaN, converts +| this NaN to the common NaN form, and stores the resulting common NaN at the +| location pointed to by 'zPtr'. If the NaN is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +void softfloat_f64UIToCommonNaN( uint_fast64_t uiA, struct commonNaN *zPtr ); + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by 'aPtr' into a 64-bit floating-point +| NaN, and returns the bit pattern of this value as an unsigned integer. +*----------------------------------------------------------------------------*/ +uint_fast64_t softfloat_commonNaNToF64UI( const struct commonNaN *aPtr ); + +/*---------------------------------------------------------------------------- +| Interpreting 'uiA' and 'uiB' as the bit patterns of two 64-bit floating- +| point values, at least one of which is a NaN, returns the bit pattern of +| the combined NaN result. If either 'uiA' or 'uiB' has the pattern of a +| signaling NaN, the invalid exception is raised. +*----------------------------------------------------------------------------*/ +uint_fast64_t + softfloat_propagateNaNF64UI( uint_fast64_t uiA, uint_fast64_t uiB ); + +/*---------------------------------------------------------------------------- +| The bit pattern for a default generated 80-bit extended floating-point NaN. +*----------------------------------------------------------------------------*/ +#define defaultNaNExtF80UI64 0xFFFF +#define defaultNaNExtF80UI0 UINT64_C( 0xC000000000000000 ) + +/*---------------------------------------------------------------------------- +| Returns true when the 80-bit unsigned integer formed from concatenating +| 16-bit 'uiA64' and 64-bit 'uiA0' has the bit pattern of an 80-bit extended +| floating-point signaling NaN. +| Note: This macro evaluates its arguments more than once. +*----------------------------------------------------------------------------*/ +#define softfloat_isSigNaNExtF80UI( uiA64, uiA0 ) ((((uiA64) & 0x7FFF) == 0x7FFF) && ! ((uiA0) & UINT64_C( 0x4000000000000000 )) && ((uiA0) & UINT64_C( 0x3FFFFFFFFFFFFFFF ))) + +#ifdef SOFTFLOAT_FAST_INT64 + +/*---------------------------------------------------------------------------- +| The following functions are needed only when 'SOFTFLOAT_FAST_INT64' is +| defined. +*----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------- +| Assuming the unsigned integer formed from concatenating 'uiA64' and 'uiA0' +| has the bit pattern of an 80-bit extended floating-point NaN, converts +| this NaN to the common NaN form, and stores the resulting common NaN at the +| location pointed to by 'zPtr'. If the NaN is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +void + softfloat_extF80UIToCommonNaN( + uint_fast16_t uiA64, uint_fast64_t uiA0, struct commonNaN *zPtr ); + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by 'aPtr' into an 80-bit extended +| floating-point NaN, and returns the bit pattern of this value as an unsigned +| integer. +*----------------------------------------------------------------------------*/ +struct uint128 softfloat_commonNaNToExtF80UI( const struct commonNaN *aPtr ); + +/*---------------------------------------------------------------------------- +| Interpreting the unsigned integer formed from concatenating 'uiA64' and +| 'uiA0' as an 80-bit extended floating-point value, and likewise interpreting +| the unsigned integer formed from concatenating 'uiB64' and 'uiB0' as another +| 80-bit extended floating-point value, and assuming at least on of these +| floating-point values is a NaN, returns the bit pattern of the combined NaN +| result. If either original floating-point value is a signaling NaN, the +| invalid exception is raised. +*----------------------------------------------------------------------------*/ +struct uint128 + softfloat_propagateNaNExtF80UI( + uint_fast16_t uiA64, + uint_fast64_t uiA0, + uint_fast16_t uiB64, + uint_fast64_t uiB0 + ); + +/*---------------------------------------------------------------------------- +| The bit pattern for a default generated 128-bit floating-point NaN. +*----------------------------------------------------------------------------*/ +#define defaultNaNF128UI64 UINT64_C( 0xFFFF800000000000 ) +#define defaultNaNF128UI0 UINT64_C( 0 ) + +/*---------------------------------------------------------------------------- +| Returns true when the 128-bit unsigned integer formed from concatenating +| 64-bit 'uiA64' and 64-bit 'uiA0' has the bit pattern of a 128-bit floating- +| point signaling NaN. +| Note: This macro evaluates its arguments more than once. +*----------------------------------------------------------------------------*/ +#define softfloat_isSigNaNF128UI( uiA64, uiA0 ) ((((uiA64) & UINT64_C( 0x7FFF800000000000 )) == UINT64_C( 0x7FFF000000000000 )) && ((uiA0) || ((uiA64) & UINT64_C( 0x00007FFFFFFFFFFF )))) + +/*---------------------------------------------------------------------------- +| Assuming the unsigned integer formed from concatenating 'uiA64' and 'uiA0' +| has the bit pattern of a 128-bit floating-point NaN, converts this NaN to +| the common NaN form, and stores the resulting common NaN at the location +| pointed to by 'zPtr'. If the NaN is a signaling NaN, the invalid exception +| is raised. +*----------------------------------------------------------------------------*/ +void + softfloat_f128UIToCommonNaN( + uint_fast64_t uiA64, uint_fast64_t uiA0, struct commonNaN *zPtr ); + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by 'aPtr' into a 128-bit floating-point +| NaN, and returns the bit pattern of this value as an unsigned integer. +*----------------------------------------------------------------------------*/ +struct uint128 softfloat_commonNaNToF128UI( const struct commonNaN * ); + +/*---------------------------------------------------------------------------- +| Interpreting the unsigned integer formed from concatenating 'uiA64' and +| 'uiA0' as a 128-bit floating-point value, and likewise interpreting the +| unsigned integer formed from concatenating 'uiB64' and 'uiB0' as another +| 128-bit floating-point value, and assuming at least on of these floating- +| point values is a NaN, returns the bit pattern of the combined NaN result. +| If either original floating-point value is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +struct uint128 + softfloat_propagateNaNF128UI( + uint_fast64_t uiA64, + uint_fast64_t uiA0, + uint_fast64_t uiB64, + uint_fast64_t uiB0 + ); + +#else + +/*---------------------------------------------------------------------------- +| The following functions are needed only when 'SOFTFLOAT_FAST_INT64' is not +| defined. +*----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------- +| Assuming the 80-bit extended floating-point value pointed to by 'aSPtr' is +| a NaN, converts this NaN to the common NaN form, and stores the resulting +| common NaN at the location pointed to by 'zPtr'. If the NaN is a signaling +| NaN, the invalid exception is raised. +*----------------------------------------------------------------------------*/ +void + softfloat_extF80MToCommonNaN( + const struct extFloat80M *aSPtr, struct commonNaN *zPtr ); + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by 'aPtr' into an 80-bit extended +| floating-point NaN, and stores this NaN at the location pointed to by +| 'zSPtr'. +*----------------------------------------------------------------------------*/ +void + softfloat_commonNaNToExtF80M( + const struct commonNaN *aPtr, struct extFloat80M *zSPtr ); + +/*---------------------------------------------------------------------------- +| Assuming at least one of the two 80-bit extended floating-point values +| pointed to by 'aSPtr' and 'bSPtr' is a NaN, stores the combined NaN result +| at the location pointed to by 'zSPtr'. If either original floating-point +| value is a signaling NaN, the invalid exception is raised. +*----------------------------------------------------------------------------*/ +void + softfloat_propagateNaNExtF80M( + const struct extFloat80M *aSPtr, + const struct extFloat80M *bSPtr, + struct extFloat80M *zSPtr + ); + +/*---------------------------------------------------------------------------- +| The bit pattern for a default generated 128-bit floating-point NaN. +*----------------------------------------------------------------------------*/ +#define defaultNaNF128UI96 0xFFFF8000 +#define defaultNaNF128UI64 0 +#define defaultNaNF128UI32 0 +#define defaultNaNF128UI0 0 + +/*---------------------------------------------------------------------------- +| Assuming the 128-bit floating-point value pointed to by 'aWPtr' is a NaN, +| converts this NaN to the common NaN form, and stores the resulting common +| NaN at the location pointed to by 'zPtr'. If the NaN is a signaling NaN, +| the invalid exception is raised. Argument 'aWPtr' points to an array of +| four 32-bit elements that concatenate in the platform's normal endian order +| to form a 128-bit floating-point value. +*----------------------------------------------------------------------------*/ +void + softfloat_f128MToCommonNaN( const uint32_t *aWPtr, struct commonNaN *zPtr ); + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by 'aPtr' into a 128-bit floating-point +| NaN, and stores this NaN at the location pointed to by 'zWPtr'. Argument +| 'zWPtr' points to an array of four 32-bit elements that concatenate in the +| platform's normal endian order to form a 128-bit floating-point value. +*----------------------------------------------------------------------------*/ +void + softfloat_commonNaNToF128M( const struct commonNaN *aPtr, uint32_t *zWPtr ); + +/*---------------------------------------------------------------------------- +| Assuming at least one of the two 128-bit floating-point values pointed to by +| 'aWPtr' and 'bWPtr' is a NaN, stores the combined NaN result at the location +| pointed to by 'zWPtr'. If either original floating-point value is a +| signaling NaN, the invalid exception is raised. Each of 'aWPtr', 'bWPtr', +| and 'zWPtr' points to an array of four 32-bit elements that concatenate in +| the platform's normal endian order to form a 128-bit floating-point value. +*----------------------------------------------------------------------------*/ +void + softfloat_propagateNaNF128M( + const uint32_t *aWPtr, const uint32_t *bWPtr, uint32_t *zWPtr ); + +#endif + +#endif + +/**** ended inlining specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Assuming `uiA' has the bit pattern of a 16-bit floating-point NaN, converts +| this NaN to the common NaN form, and stores the resulting common NaN at the +| location pointed to by `zPtr'. If the NaN is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +void softfloat_f16UIToCommonNaN( uint_fast16_t uiA, struct commonNaN *zPtr ) +{ + + if ( softfloat_isSigNaNF16UI( uiA ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + zPtr->sign = uiA>>15; + zPtr->v64 = (uint_fast64_t) uiA<<54; + zPtr->v0 = 0; + +} + +/**** ended inlining ../../source/8086-SSE/s_f16UIToCommonNaN.c ****/ +/**** start inlining ../../source/8086-SSE/s_commonNaNToF16UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: specialize.h ****/ + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by `aPtr' into a 16-bit floating-point +| NaN, and returns the bit pattern of this value as an unsigned integer. +*----------------------------------------------------------------------------*/ +uint_fast16_t softfloat_commonNaNToF16UI( const struct commonNaN *aPtr ) +{ + + return (uint_fast16_t) aPtr->sign<<15 | 0x7E00 | aPtr->v64>>54; + +} + +/**** ended inlining ../../source/8086-SSE/s_commonNaNToF16UI.c ****/ +/**** start inlining ../../source/8086-SSE/s_propagateNaNF16UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** start inlining internals.h ****/ + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#ifndef internals_h +#define internals_h 1 + +#include +#include +/**** start inlining primitives.h ****/ + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#ifndef primitives_h +#define primitives_h 1 + +#include +#include +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shortShiftRightJam64 +#define softfloat_shortShiftRightJam64 softfloat_shortShiftRightJam64 +/*---------------------------------------------------------------------------- +| Shifts 'a' right by the number of bits given in 'dist', which must be in +| the range 1 to 63. If any nonzero bits are shifted off, they are "jammed" +| into the least-significant bit of the shifted value by setting the least- +| significant bit to 1. This shifted-and-jammed value is returned. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) +INLINE +uint64_t softfloat_shortShiftRightJam64( uint64_t a, uint_fast8_t dist ) + { return a>>dist | ((a & (((uint_fast64_t) 1<>dist | ((uint32_t) (a<<(-dist & 31)) != 0) : (a != 0); +} +#else +uint32_t softfloat_shiftRightJam32( uint32_t a, uint_fast16_t dist ); +#endif +#endif + +#ifndef softfloat_shiftRightJam64 +#define softfloat_shiftRightJam64 softfloat_shiftRightJam64 +/*---------------------------------------------------------------------------- +| Shifts 'a' right by the number of bits given in 'dist', which must not +| be zero. If any nonzero bits are shifted off, they are "jammed" into the +| least-significant bit of the shifted value by setting the least-significant +| bit to 1. This shifted-and-jammed value is returned. +| The value of 'dist' can be arbitrarily large. In particular, if 'dist' is +| greater than 64, the result will be either 0 or 1, depending on whether 'a' +| is zero or nonzero. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (3 <= INLINE_LEVEL) +INLINE uint64_t softfloat_shiftRightJam64( uint64_t a, uint_fast32_t dist ) +{ + return + (dist < 63) ? a>>dist | ((uint64_t) (a<<(-dist & 63)) != 0) : (a != 0); +} +#else +uint64_t softfloat_shiftRightJam64( uint64_t a, uint_fast32_t dist ); +#endif +#endif + +/*---------------------------------------------------------------------------- +| A constant table that translates an 8-bit unsigned integer (the array index) +| into the number of leading 0 bits before the most-significant 1 of that +| integer. For integer zero (index 0), the corresponding table element is 8. +*----------------------------------------------------------------------------*/ +extern const uint_least8_t softfloat_countLeadingZeros8[256]; + +#ifndef softfloat_countLeadingZeros16 +#define softfloat_countLeadingZeros16 softfloat_countLeadingZeros16 +/*---------------------------------------------------------------------------- +| Returns the number of leading 0 bits before the most-significant 1 bit of +| 'a'. If 'a' is zero, 16 is returned. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) +INLINE uint_fast8_t softfloat_countLeadingZeros16( uint16_t a ) +{ + uint_fast8_t count = 8; + if ( 0x100 <= a ) { + count = 0; + a >>= 8; + } + count += softfloat_countLeadingZeros8[a]; + return count; +} +#else +uint_fast8_t softfloat_countLeadingZeros16( uint16_t a ); +#endif +#endif + +#ifndef softfloat_countLeadingZeros32 +#define softfloat_countLeadingZeros32 softfloat_countLeadingZeros32 +/*---------------------------------------------------------------------------- +| Returns the number of leading 0 bits before the most-significant 1 bit of +| 'a'. If 'a' is zero, 32 is returned. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (3 <= INLINE_LEVEL) +INLINE uint_fast8_t softfloat_countLeadingZeros32( uint32_t a ) +{ + uint_fast8_t count = 0; + if ( a < 0x10000 ) { + count = 16; + a <<= 16; + } + if ( a < 0x1000000 ) { + count += 8; + a <<= 8; + } + count += softfloat_countLeadingZeros8[a>>24]; + return count; +} +#else +uint_fast8_t softfloat_countLeadingZeros32( uint32_t a ); +#endif +#endif + +#ifndef softfloat_countLeadingZeros64 +#define softfloat_countLeadingZeros64 softfloat_countLeadingZeros64 +/*---------------------------------------------------------------------------- +| Returns the number of leading 0 bits before the most-significant 1 bit of +| 'a'. If 'a' is zero, 64 is returned. +*----------------------------------------------------------------------------*/ +uint_fast8_t softfloat_countLeadingZeros64( uint64_t a ); +#endif + +extern const uint16_t softfloat_approxRecip_1k0s[16]; +extern const uint16_t softfloat_approxRecip_1k1s[16]; + +#ifndef softfloat_approxRecip32_1 +/*---------------------------------------------------------------------------- +| Returns an approximation to the reciprocal of the number represented by 'a', +| where 'a' is interpreted as an unsigned fixed-point number with one integer +| bit and 31 fraction bits. The 'a' input must be "normalized", meaning that +| its most-significant bit (bit 31) must be 1. Thus, if A is the value of +| the fixed-point interpretation of 'a', then 1 <= A < 2. The returned value +| is interpreted as a pure unsigned fraction, having no integer bits and 32 +| fraction bits. The approximation returned is never greater than the true +| reciprocal 1/A, and it differs from the true reciprocal by at most 2.006 ulp +| (units in the last place). +*----------------------------------------------------------------------------*/ +#ifdef SOFTFLOAT_FAST_DIV64TO32 +#define softfloat_approxRecip32_1( a ) ((uint32_t) (UINT64_C( 0x7FFFFFFFFFFFFFFF ) / (uint32_t) (a))) +#else +uint32_t softfloat_approxRecip32_1( uint32_t a ); +#endif +#endif + +extern const uint16_t softfloat_approxRecipSqrt_1k0s[16]; +extern const uint16_t softfloat_approxRecipSqrt_1k1s[16]; + +#ifndef softfloat_approxRecipSqrt32_1 +/*---------------------------------------------------------------------------- +| Returns an approximation to the reciprocal of the square root of the number +| represented by 'a', where 'a' is interpreted as an unsigned fixed-point +| number either with one integer bit and 31 fraction bits or with two integer +| bits and 30 fraction bits. The format of 'a' is determined by 'oddExpA', +| which must be either 0 or 1. If 'oddExpA' is 1, 'a' is interpreted as +| having one integer bit, and if 'oddExpA' is 0, 'a' is interpreted as having +| two integer bits. The 'a' input must be "normalized", meaning that its +| most-significant bit (bit 31) must be 1. Thus, if A is the value of the +| fixed-point interpretation of 'a', it follows that 1 <= A < 2 when 'oddExpA' +| is 1, and 2 <= A < 4 when 'oddExpA' is 0. +| The returned value is interpreted as a pure unsigned fraction, having +| no integer bits and 32 fraction bits. The approximation returned is never +| greater than the true reciprocal 1/sqrt(A), and it differs from the true +| reciprocal by at most 2.06 ulp (units in the last place). The approximation +| returned is also always within the range 0.5 to 1; thus, the most- +| significant bit of the result is always set. +*----------------------------------------------------------------------------*/ +uint32_t softfloat_approxRecipSqrt32_1( unsigned int oddExpA, uint32_t a ); +#endif + +#ifdef SOFTFLOAT_FAST_INT64 + +/*---------------------------------------------------------------------------- +| The following functions are needed only when 'SOFTFLOAT_FAST_INT64' is +| defined. +*----------------------------------------------------------------------------*/ + +#ifndef softfloat_eq128 +#define softfloat_eq128 softfloat_eq128 +/*---------------------------------------------------------------------------- +| Returns true if the 128-bit unsigned integer formed by concatenating 'a64' +| and 'a0' is equal to the 128-bit unsigned integer formed by concatenating +| 'b64' and 'b0'. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (1 <= INLINE_LEVEL) +INLINE +bool softfloat_eq128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) + { return (a64 == b64) && (a0 == b0); } +#else +bool softfloat_eq128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ); +#endif +#endif + +#ifndef softfloat_le128 +#define softfloat_le128 softfloat_le128 +/*---------------------------------------------------------------------------- +| Returns true if the 128-bit unsigned integer formed by concatenating 'a64' +| and 'a0' is less than or equal to the 128-bit unsigned integer formed by +| concatenating 'b64' and 'b0'. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) +INLINE +bool softfloat_le128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) + { return (a64 < b64) || ((a64 == b64) && (a0 <= b0)); } +#else +bool softfloat_le128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ); +#endif +#endif + +#ifndef softfloat_lt128 +#define softfloat_lt128 softfloat_lt128 +/*---------------------------------------------------------------------------- +| Returns true if the 128-bit unsigned integer formed by concatenating 'a64' +| and 'a0' is less than the 128-bit unsigned integer formed by concatenating +| 'b64' and 'b0'. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) +INLINE +bool softfloat_lt128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) + { return (a64 < b64) || ((a64 == b64) && (a0 < b0)); } +#else +bool softfloat_lt128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ); +#endif +#endif + +#ifndef softfloat_shortShiftLeft128 +#define softfloat_shortShiftLeft128 softfloat_shortShiftLeft128 +/*---------------------------------------------------------------------------- +| Shifts the 128 bits formed by concatenating 'a64' and 'a0' left by the +| number of bits given in 'dist', which must be in the range 1 to 63. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) +INLINE +struct uint128 + softfloat_shortShiftLeft128( uint64_t a64, uint64_t a0, uint_fast8_t dist ) +{ + struct uint128 z; + z.v64 = a64<>(-dist & 63); + z.v0 = a0<>dist; + z.v0 = a64<<(-dist & 63) | a0>>dist; + return z; +} +#else +struct uint128 + softfloat_shortShiftRight128( uint64_t a64, uint64_t a0, uint_fast8_t dist ); +#endif +#endif + +#ifndef softfloat_shortShiftRightJam64Extra +#define softfloat_shortShiftRightJam64Extra softfloat_shortShiftRightJam64Extra +/*---------------------------------------------------------------------------- +| This function is the same as 'softfloat_shiftRightJam64Extra' (below), +| except that 'dist' must be in the range 1 to 63. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) +INLINE +struct uint64_extra + softfloat_shortShiftRightJam64Extra( + uint64_t a, uint64_t extra, uint_fast8_t dist ) +{ + struct uint64_extra z; + z.v = a>>dist; + z.extra = a<<(-dist & 63) | (extra != 0); + return z; +} +#else +struct uint64_extra + softfloat_shortShiftRightJam64Extra( + uint64_t a, uint64_t extra, uint_fast8_t dist ); +#endif +#endif + +#ifndef softfloat_shortShiftRightJam128 +#define softfloat_shortShiftRightJam128 softfloat_shortShiftRightJam128 +/*---------------------------------------------------------------------------- +| Shifts the 128 bits formed by concatenating 'a64' and 'a0' right by the +| number of bits given in 'dist', which must be in the range 1 to 63. If any +| nonzero bits are shifted off, they are "jammed" into the least-significant +| bit of the shifted value by setting the least-significant bit to 1. This +| shifted-and-jammed value is returned. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (3 <= INLINE_LEVEL) +INLINE +struct uint128 + softfloat_shortShiftRightJam128( + uint64_t a64, uint64_t a0, uint_fast8_t dist ) +{ + uint_fast8_t negDist = -dist; + struct uint128 z; + z.v64 = a64>>dist; + z.v0 = + a64<<(negDist & 63) | a0>>dist + | ((uint64_t) (a0<<(negDist & 63)) != 0); + return z; +} +#else +struct uint128 + softfloat_shortShiftRightJam128( + uint64_t a64, uint64_t a0, uint_fast8_t dist ); +#endif +#endif + +#ifndef softfloat_shortShiftRightJam128Extra +#define softfloat_shortShiftRightJam128Extra softfloat_shortShiftRightJam128Extra +/*---------------------------------------------------------------------------- +| This function is the same as 'softfloat_shiftRightJam128Extra' (below), +| except that 'dist' must be in the range 1 to 63. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (3 <= INLINE_LEVEL) +INLINE +struct uint128_extra + softfloat_shortShiftRightJam128Extra( + uint64_t a64, uint64_t a0, uint64_t extra, uint_fast8_t dist ) +{ + uint_fast8_t negDist = -dist; + struct uint128_extra z; + z.v.v64 = a64>>dist; + z.v.v0 = a64<<(negDist & 63) | a0>>dist; + z.extra = a0<<(negDist & 63) | (extra != 0); + return z; +} +#else +struct uint128_extra + softfloat_shortShiftRightJam128Extra( + uint64_t a64, uint64_t a0, uint64_t extra, uint_fast8_t dist ); +#endif +#endif + +#ifndef softfloat_shiftRightJam64Extra +#define softfloat_shiftRightJam64Extra softfloat_shiftRightJam64Extra +/*---------------------------------------------------------------------------- +| Shifts the 128 bits formed by concatenating 'a' and 'extra' right by 64 +| _plus_ the number of bits given in 'dist', which must not be zero. This +| shifted value is at most 64 nonzero bits and is returned in the 'v' field +| of the 'struct uint64_extra' result. The 64-bit 'extra' field of the result +| contains a value formed as follows from the bits that were shifted off: The +| _last_ bit shifted off is the most-significant bit of the 'extra' field, and +| the other 63 bits of the 'extra' field are all zero if and only if _all_but_ +| _the_last_ bits shifted off were all zero. +| (This function makes more sense if 'a' and 'extra' are considered to form +| an unsigned fixed-point number with binary point between 'a' and 'extra'. +| This fixed-point value is shifted right by the number of bits given in +| 'dist', and the integer part of this shifted value is returned in the 'v' +| field of the result. The fractional part of the shifted value is modified +| as described above and returned in the 'extra' field of the result.) +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (4 <= INLINE_LEVEL) +INLINE +struct uint64_extra + softfloat_shiftRightJam64Extra( + uint64_t a, uint64_t extra, uint_fast32_t dist ) +{ + struct uint64_extra z; + if ( dist < 64 ) { + z.v = a>>dist; + z.extra = a<<(-dist & 63); + } else { + z.v = 0; + z.extra = (dist == 64) ? a : (a != 0); + } + z.extra |= (extra != 0); + return z; +} +#else +struct uint64_extra + softfloat_shiftRightJam64Extra( + uint64_t a, uint64_t extra, uint_fast32_t dist ); +#endif +#endif + +#ifndef softfloat_shiftRightJam128 +//#define softfloat_shiftRightJam128 softfloat_shiftRightJam128 +/*---------------------------------------------------------------------------- +| Shifts the 128 bits formed by concatenating 'a64' and 'a0' right by the +| number of bits given in 'dist', which must not be zero. If any nonzero bits +| are shifted off, they are "jammed" into the least-significant bit of the +| shifted value by setting the least-significant bit to 1. This shifted-and- +| jammed value is returned. +| The value of 'dist' can be arbitrarily large. In particular, if 'dist' is +| greater than 128, the result will be either 0 or 1, depending on whether the +| original 128 bits are all zeros. +*----------------------------------------------------------------------------*/ +struct uint128 + softfloat_shiftRightJam128( uint64_t a64, uint64_t a0, uint_fast32_t dist ); +#endif + +#ifndef softfloat_shiftRightJam128Extra +#define softfloat_shiftRightJam128Extra softfloat_shiftRightJam128Extra +/*---------------------------------------------------------------------------- +| Shifts the 192 bits formed by concatenating 'a64', 'a0', and 'extra' right +| by 64 _plus_ the number of bits given in 'dist', which must not be zero. +| This shifted value is at most 128 nonzero bits and is returned in the 'v' +| field of the 'struct uint128_extra' result. The 64-bit 'extra' field of the +| result contains a value formed as follows from the bits that were shifted +| off: The _last_ bit shifted off is the most-significant bit of the 'extra' +| field, and the other 63 bits of the 'extra' field are all zero if and only +| if _all_but_the_last_ bits shifted off were all zero. +| (This function makes more sense if 'a64', 'a0', and 'extra' are considered +| to form an unsigned fixed-point number with binary point between 'a0' and +| 'extra'. This fixed-point value is shifted right by the number of bits +| given in 'dist', and the integer part of this shifted value is returned +| in the 'v' field of the result. The fractional part of the shifted value +| is modified as described above and returned in the 'extra' field of the +| result.) +*----------------------------------------------------------------------------*/ +struct uint128_extra + softfloat_shiftRightJam128Extra( + uint64_t a64, uint64_t a0, uint64_t extra, uint_fast32_t dist ); +#endif + +#ifndef softfloat_shiftRightJam256M +#define softfloat_shiftRightJam256M softfloat_shiftRightJam256M +/*---------------------------------------------------------------------------- +| Shifts the 256-bit unsigned integer pointed to by 'aPtr' right by the number +| of bits given in 'dist', which must not be zero. If any nonzero bits are +| shifted off, they are "jammed" into the least-significant bit of the shifted +| value by setting the least-significant bit to 1. This shifted-and-jammed +| value is stored at the location pointed to by 'zPtr'. Each of 'aPtr' and +| 'zPtr' points to an array of four 64-bit elements that concatenate in the +| platform's normal endian order to form a 256-bit integer. +| The value of 'dist' can be arbitrarily large. In particular, if 'dist' +| is greater than 256, the stored result will be either 0 or 1, depending on +| whether the original 256 bits are all zeros. +*----------------------------------------------------------------------------*/ +void + softfloat_shiftRightJam256M( + const uint64_t *aPtr, uint_fast32_t dist, uint64_t *zPtr ); +#endif + +#ifndef softfloat_add128 +#define softfloat_add128 softfloat_add128 +/*---------------------------------------------------------------------------- +| Returns the sum of the 128-bit integer formed by concatenating 'a64' and +| 'a0' and the 128-bit integer formed by concatenating 'b64' and 'b0'. The +| addition is modulo 2^128, so any carry out is lost. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) +INLINE +struct uint128 + softfloat_add128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) +{ + struct uint128 z; + z.v0 = a0 + b0; + z.v64 = a64 + b64 + (z.v0 < a0); + return z; +} +#else +struct uint128 + softfloat_add128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ); +#endif +#endif + +#ifndef softfloat_add256M +/*---------------------------------------------------------------------------- +| Adds the two 256-bit integers pointed to by 'aPtr' and 'bPtr'. The addition +| is modulo 2^256, so any carry out is lost. The sum is stored at the +| location pointed to by 'zPtr'. Each of 'aPtr', 'bPtr', and 'zPtr' points to +| an array of four 64-bit elements that concatenate in the platform's normal +| endian order to form a 256-bit integer. +*----------------------------------------------------------------------------*/ +void + softfloat_add256M( + const uint64_t *aPtr, const uint64_t *bPtr, uint64_t *zPtr ); +#endif + +#ifndef softfloat_sub128 +#define softfloat_sub128 softfloat_sub128 +/*---------------------------------------------------------------------------- +| Returns the difference of the 128-bit integer formed by concatenating 'a64' +| and 'a0' and the 128-bit integer formed by concatenating 'b64' and 'b0'. +| The subtraction is modulo 2^128, so any borrow out (carry out) is lost. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) +INLINE +struct uint128 + softfloat_sub128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) +{ + struct uint128 z; + z.v0 = a0 - b0; + z.v64 = a64 - b64; + z.v64 -= (a0 < b0); + return z; +} +#else +struct uint128 + softfloat_sub128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ); +#endif +#endif + +#ifndef softfloat_sub256M +/*---------------------------------------------------------------------------- +| Subtracts the 256-bit integer pointed to by 'bPtr' from the 256-bit integer +| pointed to by 'aPtr'. The addition is modulo 2^256, so any borrow out +| (carry out) is lost. The difference is stored at the location pointed to +| by 'zPtr'. Each of 'aPtr', 'bPtr', and 'zPtr' points to an array of four +| 64-bit elements that concatenate in the platform's normal endian order to +| form a 256-bit integer. +*----------------------------------------------------------------------------*/ +void + softfloat_sub256M( + const uint64_t *aPtr, const uint64_t *bPtr, uint64_t *zPtr ); +#endif + +#ifndef softfloat_mul64ByShifted32To128 +/*---------------------------------------------------------------------------- +| Returns the 128-bit product of 'a', 'b', and 2^32. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (3 <= INLINE_LEVEL) +INLINE struct uint128 softfloat_mul64ByShifted32To128( uint64_t a, uint32_t b ) +{ + uint_fast64_t mid; + struct uint128 z; + mid = (uint_fast64_t) (uint32_t) a * b; + z.v0 = mid<<32; + z.v64 = (uint_fast64_t) (uint32_t) (a>>32) * b + (mid>>32); + return z; +} +#else +struct uint128 softfloat_mul64ByShifted32To128( uint64_t a, uint32_t b ); +#endif +#endif + +#ifndef softfloat_mul64To128 +/*---------------------------------------------------------------------------- +| Returns the 128-bit product of 'a' and 'b'. +*----------------------------------------------------------------------------*/ +struct uint128 softfloat_mul64To128( uint64_t a, uint64_t b ); +#endif + +#ifndef softfloat_mul128By32 +/*---------------------------------------------------------------------------- +| Returns the product of the 128-bit integer formed by concatenating 'a64' and +| 'a0', multiplied by 'b'. The multiplication is modulo 2^128; any overflow +| bits are discarded. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (4 <= INLINE_LEVEL) +INLINE +struct uint128 softfloat_mul128By32( uint64_t a64, uint64_t a0, uint32_t b ) +{ + struct uint128 z; + uint_fast64_t mid; + uint_fast32_t carry; + z.v0 = a0 * b; + mid = (uint_fast64_t) (uint32_t) (a0>>32) * b; + carry = (uint32_t) ((uint_fast32_t) (z.v0>>32) - (uint_fast32_t) mid); + z.v64 = a64 * b + (uint_fast32_t) ((mid + carry)>>32); + return z; +} +#else +struct uint128 softfloat_mul128By32( uint64_t a64, uint64_t a0, uint32_t b ); +#endif +#endif + +#ifndef softfloat_mul128To256M +/*---------------------------------------------------------------------------- +| Multiplies the 128-bit unsigned integer formed by concatenating 'a64' and +| 'a0' by the 128-bit unsigned integer formed by concatenating 'b64' and +| 'b0'. The 256-bit product is stored at the location pointed to by 'zPtr'. +| Argument 'zPtr' points to an array of four 64-bit elements that concatenate +| in the platform's normal endian order to form a 256-bit integer. +*----------------------------------------------------------------------------*/ +void + softfloat_mul128To256M( + uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0, uint64_t *zPtr ); +#endif + +#else + +/*---------------------------------------------------------------------------- +| The following functions are needed only when 'SOFTFLOAT_FAST_INT64' is not +| defined. +*----------------------------------------------------------------------------*/ + +#ifndef softfloat_compare96M +/*---------------------------------------------------------------------------- +| Compares the two 96-bit unsigned integers pointed to by 'aPtr' and 'bPtr'. +| Returns -1 if the first integer (A) is less than the second (B); returns 0 +| if the two integers are equal; and returns +1 if the first integer (A) +| is greater than the second (B). (The result is thus the signum of A - B.) +| Each of 'aPtr' and 'bPtr' points to an array of three 32-bit elements that +| concatenate in the platform's normal endian order to form a 96-bit integer. +*----------------------------------------------------------------------------*/ +int_fast8_t softfloat_compare96M( const uint32_t *aPtr, const uint32_t *bPtr ); +#endif + +#ifndef softfloat_compare128M +/*---------------------------------------------------------------------------- +| Compares the two 128-bit unsigned integers pointed to by 'aPtr' and 'bPtr'. +| Returns -1 if the first integer (A) is less than the second (B); returns 0 +| if the two integers are equal; and returns +1 if the first integer (A) +| is greater than the second (B). (The result is thus the signum of A - B.) +| Each of 'aPtr' and 'bPtr' points to an array of four 32-bit elements that +| concatenate in the platform's normal endian order to form a 128-bit integer. +*----------------------------------------------------------------------------*/ +int_fast8_t + softfloat_compare128M( const uint32_t *aPtr, const uint32_t *bPtr ); +#endif + +#ifndef softfloat_shortShiftLeft64To96M +/*---------------------------------------------------------------------------- +| Extends 'a' to 96 bits and shifts the value left by the number of bits given +| in 'dist', which must be in the range 1 to 31. The result is stored at the +| location pointed to by 'zPtr'. Argument 'zPtr' points to an array of three +| 32-bit elements that concatenate in the platform's normal endian order to +| form a 96-bit integer. +*----------------------------------------------------------------------------*/ +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) +INLINE +void + softfloat_shortShiftLeft64To96M( + uint64_t a, uint_fast8_t dist, uint32_t *zPtr ) +{ + zPtr[indexWord( 3, 0 )] = (uint32_t) a<>= 32 - dist; + zPtr[indexWord( 3, 2 )] = a>>32; + zPtr[indexWord( 3, 1 )] = a; +} +#else +void + softfloat_shortShiftLeft64To96M( + uint64_t a, uint_fast8_t dist, uint32_t *zPtr ); +#endif +#endif + +#ifndef softfloat_shortShiftLeftM +/*---------------------------------------------------------------------------- +| Shifts the N-bit unsigned integer pointed to by 'aPtr' left by the number +| of bits given in 'dist', where N = 'size_words' * 32. The value of 'dist' +| must be in the range 1 to 31. Any nonzero bits shifted off are lost. The +| shifted N-bit result is stored at the location pointed to by 'zPtr'. Each +| of 'aPtr' and 'zPtr' points to a 'size_words'-long array of 32-bit elements +| that concatenate in the platform's normal endian order to form an N-bit +| integer. +*----------------------------------------------------------------------------*/ +void + softfloat_shortShiftLeftM( + uint_fast8_t size_words, + const uint32_t *aPtr, + uint_fast8_t dist, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_shortShiftLeft96M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shortShiftLeftM' with +| 'size_words' = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_shortShiftLeft96M( aPtr, dist, zPtr ) softfloat_shortShiftLeftM( 3, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shortShiftLeft128M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shortShiftLeftM' with +| 'size_words' = 4 (N = 128). +*----------------------------------------------------------------------------*/ +#define softfloat_shortShiftLeft128M( aPtr, dist, zPtr ) softfloat_shortShiftLeftM( 4, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shortShiftLeft160M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shortShiftLeftM' with +| 'size_words' = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_shortShiftLeft160M( aPtr, dist, zPtr ) softfloat_shortShiftLeftM( 5, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shiftLeftM +/*---------------------------------------------------------------------------- +| Shifts the N-bit unsigned integer pointed to by 'aPtr' left by the number +| of bits given in 'dist', where N = 'size_words' * 32. The value of 'dist' +| must not be zero. Any nonzero bits shifted off are lost. The shifted +| N-bit result is stored at the location pointed to by 'zPtr'. Each of 'aPtr' +| and 'zPtr' points to a 'size_words'-long array of 32-bit elements that +| concatenate in the platform's normal endian order to form an N-bit integer. +| The value of 'dist' can be arbitrarily large. In particular, if 'dist' is +| greater than N, the stored result will be 0. +*----------------------------------------------------------------------------*/ +void + softfloat_shiftLeftM( + uint_fast8_t size_words, + const uint32_t *aPtr, + uint32_t dist, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_shiftLeft96M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shiftLeftM' with +| 'size_words' = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_shiftLeft96M( aPtr, dist, zPtr ) softfloat_shiftLeftM( 3, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shiftLeft128M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shiftLeftM' with +| 'size_words' = 4 (N = 128). +*----------------------------------------------------------------------------*/ +#define softfloat_shiftLeft128M( aPtr, dist, zPtr ) softfloat_shiftLeftM( 4, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shiftLeft160M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shiftLeftM' with +| 'size_words' = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_shiftLeft160M( aPtr, dist, zPtr ) softfloat_shiftLeftM( 5, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shortShiftRightM +/*---------------------------------------------------------------------------- +| Shifts the N-bit unsigned integer pointed to by 'aPtr' right by the number +| of bits given in 'dist', where N = 'size_words' * 32. The value of 'dist' +| must be in the range 1 to 31. Any nonzero bits shifted off are lost. The +| shifted N-bit result is stored at the location pointed to by 'zPtr'. Each +| of 'aPtr' and 'zPtr' points to a 'size_words'-long array of 32-bit elements +| that concatenate in the platform's normal endian order to form an N-bit +| integer. +*----------------------------------------------------------------------------*/ +void + softfloat_shortShiftRightM( + uint_fast8_t size_words, + const uint32_t *aPtr, + uint_fast8_t dist, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_shortShiftRight128M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shortShiftRightM' with +| 'size_words' = 4 (N = 128). +*----------------------------------------------------------------------------*/ +#define softfloat_shortShiftRight128M( aPtr, dist, zPtr ) softfloat_shortShiftRightM( 4, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shortShiftRight160M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shortShiftRightM' with +| 'size_words' = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_shortShiftRight160M( aPtr, dist, zPtr ) softfloat_shortShiftRightM( 5, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shortShiftRightJamM +/*---------------------------------------------------------------------------- +| Shifts the N-bit unsigned integer pointed to by 'aPtr' right by the number +| of bits given in 'dist', where N = 'size_words' * 32. The value of 'dist' +| must be in the range 1 to 31. If any nonzero bits are shifted off, they are +| "jammed" into the least-significant bit of the shifted value by setting the +| least-significant bit to 1. This shifted-and-jammed N-bit result is stored +| at the location pointed to by 'zPtr'. Each of 'aPtr' and 'zPtr' points +| to a 'size_words'-long array of 32-bit elements that concatenate in the +| platform's normal endian order to form an N-bit integer. +*----------------------------------------------------------------------------*/ +void + softfloat_shortShiftRightJamM( + uint_fast8_t, const uint32_t *, uint_fast8_t, uint32_t * ); +#endif + +#ifndef softfloat_shortShiftRightJam160M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shortShiftRightJamM' with +| 'size_words' = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_shortShiftRightJam160M( aPtr, dist, zPtr ) softfloat_shortShiftRightJamM( 5, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shiftRightM +/*---------------------------------------------------------------------------- +| Shifts the N-bit unsigned integer pointed to by 'aPtr' right by the number +| of bits given in 'dist', where N = 'size_words' * 32. The value of 'dist' +| must not be zero. Any nonzero bits shifted off are lost. The shifted +| N-bit result is stored at the location pointed to by 'zPtr'. Each of 'aPtr' +| and 'zPtr' points to a 'size_words'-long array of 32-bit elements that +| concatenate in the platform's normal endian order to form an N-bit integer. +| The value of 'dist' can be arbitrarily large. In particular, if 'dist' is +| greater than N, the stored result will be 0. +*----------------------------------------------------------------------------*/ +void + softfloat_shiftRightM( + uint_fast8_t size_words, + const uint32_t *aPtr, + uint32_t dist, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_shiftRight96M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shiftRightM' with +| 'size_words' = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_shiftRight96M( aPtr, dist, zPtr ) softfloat_shiftRightM( 3, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shiftRightJamM +/*---------------------------------------------------------------------------- +| Shifts the N-bit unsigned integer pointed to by 'aPtr' right by the number +| of bits given in 'dist', where N = 'size_words' * 32. The value of 'dist' +| must not be zero. If any nonzero bits are shifted off, they are "jammed" +| into the least-significant bit of the shifted value by setting the least- +| significant bit to 1. This shifted-and-jammed N-bit result is stored +| at the location pointed to by 'zPtr'. Each of 'aPtr' and 'zPtr' points +| to a 'size_words'-long array of 32-bit elements that concatenate in the +| platform's normal endian order to form an N-bit integer. +| The value of 'dist' can be arbitrarily large. In particular, if 'dist' +| is greater than N, the stored result will be either 0 or 1, depending on +| whether the original N bits are all zeros. +*----------------------------------------------------------------------------*/ +void + softfloat_shiftRightJamM( + uint_fast8_t size_words, + const uint32_t *aPtr, + uint32_t dist, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_shiftRightJam96M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shiftRightJamM' with +| 'size_words' = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_shiftRightJam96M( aPtr, dist, zPtr ) softfloat_shiftRightJamM( 3, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shiftRightJam128M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shiftRightJamM' with +| 'size_words' = 4 (N = 128). +*----------------------------------------------------------------------------*/ +#define softfloat_shiftRightJam128M( aPtr, dist, zPtr ) softfloat_shiftRightJamM( 4, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_shiftRightJam160M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_shiftRightJamM' with +| 'size_words' = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_shiftRightJam160M( aPtr, dist, zPtr ) softfloat_shiftRightJamM( 5, aPtr, dist, zPtr ) +#endif + +#ifndef softfloat_addM +/*---------------------------------------------------------------------------- +| Adds the two N-bit integers pointed to by 'aPtr' and 'bPtr', where N = +| 'size_words' * 32. The addition is modulo 2^N, so any carry out is lost. +| The N-bit sum is stored at the location pointed to by 'zPtr'. Each of +| 'aPtr', 'bPtr', and 'zPtr' points to a 'size_words'-long array of 32-bit +| elements that concatenate in the platform's normal endian order to form an +| N-bit integer. +*----------------------------------------------------------------------------*/ +void + softfloat_addM( + uint_fast8_t size_words, + const uint32_t *aPtr, + const uint32_t *bPtr, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_add96M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_addM' with 'size_words' +| = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_add96M( aPtr, bPtr, zPtr ) softfloat_addM( 3, aPtr, bPtr, zPtr ) +#endif + +#ifndef softfloat_add128M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_addM' with 'size_words' +| = 4 (N = 128). +*----------------------------------------------------------------------------*/ +#define softfloat_add128M( aPtr, bPtr, zPtr ) softfloat_addM( 4, aPtr, bPtr, zPtr ) +#endif + +#ifndef softfloat_add160M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_addM' with 'size_words' +| = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_add160M( aPtr, bPtr, zPtr ) softfloat_addM( 5, aPtr, bPtr, zPtr ) +#endif + +#ifndef softfloat_addCarryM +/*---------------------------------------------------------------------------- +| Adds the two N-bit unsigned integers pointed to by 'aPtr' and 'bPtr', where +| N = 'size_words' * 32, plus 'carry', which must be either 0 or 1. The N-bit +| sum (modulo 2^N) is stored at the location pointed to by 'zPtr', and any +| carry out is returned as the result. Each of 'aPtr', 'bPtr', and 'zPtr' +| points to a 'size_words'-long array of 32-bit elements that concatenate in +| the platform's normal endian order to form an N-bit integer. +*----------------------------------------------------------------------------*/ +uint_fast8_t + softfloat_addCarryM( + uint_fast8_t size_words, + const uint32_t *aPtr, + const uint32_t *bPtr, + uint_fast8_t carry, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_addComplCarryM +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_addCarryM', except that +| the value of the unsigned integer pointed to by 'bPtr' is bit-wise completed +| before the addition. +*----------------------------------------------------------------------------*/ +uint_fast8_t + softfloat_addComplCarryM( + uint_fast8_t size_words, + const uint32_t *aPtr, + const uint32_t *bPtr, + uint_fast8_t carry, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_addComplCarry96M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_addComplCarryM' with +| 'size_words' = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_addComplCarry96M( aPtr, bPtr, carry, zPtr ) softfloat_addComplCarryM( 3, aPtr, bPtr, carry, zPtr ) +#endif + +#ifndef softfloat_negXM +/*---------------------------------------------------------------------------- +| Replaces the N-bit unsigned integer pointed to by 'zPtr' by the +| 2s-complement of itself, where N = 'size_words' * 32. Argument 'zPtr' +| points to a 'size_words'-long array of 32-bit elements that concatenate in +| the platform's normal endian order to form an N-bit integer. +*----------------------------------------------------------------------------*/ +void softfloat_negXM( uint_fast8_t size_words, uint32_t *zPtr ); +#endif + +#ifndef softfloat_negX96M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_negXM' with 'size_words' +| = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_negX96M( zPtr ) softfloat_negXM( 3, zPtr ) +#endif + +#ifndef softfloat_negX128M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_negXM' with 'size_words' +| = 4 (N = 128). +*----------------------------------------------------------------------------*/ +#define softfloat_negX128M( zPtr ) softfloat_negXM( 4, zPtr ) +#endif + +#ifndef softfloat_negX160M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_negXM' with 'size_words' +| = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_negX160M( zPtr ) softfloat_negXM( 5, zPtr ) +#endif + +#ifndef softfloat_negX256M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_negXM' with 'size_words' +| = 8 (N = 256). +*----------------------------------------------------------------------------*/ +#define softfloat_negX256M( zPtr ) softfloat_negXM( 8, zPtr ) +#endif + +#ifndef softfloat_sub1XM +/*---------------------------------------------------------------------------- +| Subtracts 1 from the N-bit integer pointed to by 'zPtr', where N = +| 'size_words' * 32. The subtraction is modulo 2^N, so any borrow out (carry +| out) is lost. Argument 'zPtr' points to a 'size_words'-long array of 32-bit +| elements that concatenate in the platform's normal endian order to form an +| N-bit integer. +*----------------------------------------------------------------------------*/ +void softfloat_sub1XM( uint_fast8_t size_words, uint32_t *zPtr ); +#endif + +#ifndef softfloat_sub1X96M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_sub1XM' with 'size_words' +| = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_sub1X96M( zPtr ) softfloat_sub1XM( 3, zPtr ) +#endif + +#ifndef softfloat_sub1X160M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_sub1XM' with 'size_words' +| = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_sub1X160M( zPtr ) softfloat_sub1XM( 5, zPtr ) +#endif + +#ifndef softfloat_subM +/*---------------------------------------------------------------------------- +| Subtracts the two N-bit integers pointed to by 'aPtr' and 'bPtr', where N = +| 'size_words' * 32. The subtraction is modulo 2^N, so any borrow out (carry +| out) is lost. The N-bit difference is stored at the location pointed to by +| 'zPtr'. Each of 'aPtr', 'bPtr', and 'zPtr' points to a 'size_words'-long +| array of 32-bit elements that concatenate in the platform's normal endian +| order to form an N-bit integer. +*----------------------------------------------------------------------------*/ +void + softfloat_subM( + uint_fast8_t size_words, + const uint32_t *aPtr, + const uint32_t *bPtr, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_sub96M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_subM' with 'size_words' +| = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_sub96M( aPtr, bPtr, zPtr ) softfloat_subM( 3, aPtr, bPtr, zPtr ) +#endif + +#ifndef softfloat_sub128M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_subM' with 'size_words' +| = 4 (N = 128). +*----------------------------------------------------------------------------*/ +#define softfloat_sub128M( aPtr, bPtr, zPtr ) softfloat_subM( 4, aPtr, bPtr, zPtr ) +#endif + +#ifndef softfloat_sub160M +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_subM' with 'size_words' +| = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_sub160M( aPtr, bPtr, zPtr ) softfloat_subM( 5, aPtr, bPtr, zPtr ) +#endif + +#ifndef softfloat_mul64To128M +/*---------------------------------------------------------------------------- +| Multiplies 'a' and 'b' and stores the 128-bit product at the location +| pointed to by 'zPtr'. Argument 'zPtr' points to an array of four 32-bit +| elements that concatenate in the platform's normal endian order to form a +| 128-bit integer. +*----------------------------------------------------------------------------*/ +void softfloat_mul64To128M( uint64_t a, uint64_t b, uint32_t *zPtr ); +#endif + +#ifndef softfloat_mul128MTo256M +/*---------------------------------------------------------------------------- +| Multiplies the two 128-bit unsigned integers pointed to by 'aPtr' and +| 'bPtr', and stores the 256-bit product at the location pointed to by 'zPtr'. +| Each of 'aPtr' and 'bPtr' points to an array of four 32-bit elements that +| concatenate in the platform's normal endian order to form a 128-bit integer. +| Argument 'zPtr' points to an array of eight 32-bit elements that concatenate +| to form a 256-bit integer. +*----------------------------------------------------------------------------*/ +void + softfloat_mul128MTo256M( + const uint32_t *aPtr, const uint32_t *bPtr, uint32_t *zPtr ); +#endif + +#ifndef softfloat_remStepMBy32 +/*---------------------------------------------------------------------------- +| Performs a "remainder reduction step" as follows: Arguments 'remPtr' and +| 'bPtr' both point to N-bit unsigned integers, where N = 'size_words' * 32. +| Defining R and B as the values of those integers, the expression (R<<'dist') +| - B * q is computed modulo 2^N, and the N-bit result is stored at the +| location pointed to by 'zPtr'. Each of 'remPtr', 'bPtr', and 'zPtr' points +| to a 'size_words'-long array of 32-bit elements that concatenate in the +| platform's normal endian order to form an N-bit integer. +*----------------------------------------------------------------------------*/ +void + softfloat_remStepMBy32( + uint_fast8_t size_words, + const uint32_t *remPtr, + uint_fast8_t dist, + const uint32_t *bPtr, + uint32_t q, + uint32_t *zPtr + ); +#endif + +#ifndef softfloat_remStep96MBy32 +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_remStepMBy32' with +| 'size_words' = 3 (N = 96). +*----------------------------------------------------------------------------*/ +#define softfloat_remStep96MBy32( remPtr, dist, bPtr, q, zPtr ) softfloat_remStepMBy32( 3, remPtr, dist, bPtr, q, zPtr ) +#endif + +#ifndef softfloat_remStep128MBy32 +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_remStepMBy32' with +| 'size_words' = 4 (N = 128). +*----------------------------------------------------------------------------*/ +#define softfloat_remStep128MBy32( remPtr, dist, bPtr, q, zPtr ) softfloat_remStepMBy32( 4, remPtr, dist, bPtr, q, zPtr ) +#endif + +#ifndef softfloat_remStep160MBy32 +/*---------------------------------------------------------------------------- +| This function or macro is the same as 'softfloat_remStepMBy32' with +| 'size_words' = 5 (N = 160). +*----------------------------------------------------------------------------*/ +#define softfloat_remStep160MBy32( remPtr, dist, bPtr, q, zPtr ) softfloat_remStepMBy32( 5, remPtr, dist, bPtr, q, zPtr ) +#endif + +#endif + +#endif + +/**** ended inlining primitives.h ****/ +/**** skipping file: softfloat_types.h ****/ + +union ui16_f16 { uint16_t ui; float16_t f; }; +union ui32_f32 { uint32_t ui; float32_t f; }; +union ui64_f64 { uint64_t ui; float64_t f; }; + +#ifdef SOFTFLOAT_FAST_INT64 +union extF80M_extF80 { struct extFloat80M fM; extFloat80_t f; }; +union ui128_f128 { struct uint128 ui; float128_t f; }; +#endif + +enum { + softfloat_mulAdd_subC = 1, + softfloat_mulAdd_subProd = 2 +}; + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +uint_fast32_t softfloat_roundToUI32( bool, uint_fast64_t, uint_fast8_t, bool ); + +#ifdef SOFTFLOAT_FAST_INT64 +uint_fast64_t + softfloat_roundToUI64( + bool, uint_fast64_t, uint_fast64_t, uint_fast8_t, bool ); +#else +uint_fast64_t softfloat_roundMToUI64( bool, uint32_t *, uint_fast8_t, bool ); +#endif + +int_fast32_t softfloat_roundToI32( bool, uint_fast64_t, uint_fast8_t, bool ); + +#ifdef SOFTFLOAT_FAST_INT64 +int_fast64_t + softfloat_roundToI64( + bool, uint_fast64_t, uint_fast64_t, uint_fast8_t, bool ); +#else +int_fast64_t softfloat_roundMToI64( bool, uint32_t *, uint_fast8_t, bool ); +#endif + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +#define signF16UI( a ) ((bool) ((uint16_t) (a)>>15)) +#define expF16UI( a ) ((int_fast8_t) ((a)>>10) & 0x1F) +#define fracF16UI( a ) ((a) & 0x03FF) +#define packToF16UI( sign, exp, sig ) (((uint16_t) (sign)<<15) + ((uint16_t) (exp)<<10) + (sig)) + +#define isNaNF16UI( a ) (((~(a) & 0x7C00) == 0) && ((a) & 0x03FF)) + +struct exp8_sig16 { int_fast8_t exp; uint_fast16_t sig; }; +struct exp8_sig16 softfloat_normSubnormalF16Sig( uint_fast16_t ); + +float16_t softfloat_roundPackToF16( bool, int_fast16_t, uint_fast16_t ); +float16_t softfloat_normRoundPackToF16( bool, int_fast16_t, uint_fast16_t ); + +float16_t softfloat_addMagsF16( uint_fast16_t, uint_fast16_t ); +float16_t softfloat_subMagsF16( uint_fast16_t, uint_fast16_t ); +float16_t + softfloat_mulAddF16( + uint_fast16_t, uint_fast16_t, uint_fast16_t, uint_fast8_t ); + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +#define signF32UI( a ) ((bool) ((uint32_t) (a)>>31)) +#define expF32UI( a ) ((int_fast16_t) ((a)>>23) & 0xFF) +#define fracF32UI( a ) ((a) & 0x007FFFFF) +#define packToF32UI( sign, exp, sig ) (((uint32_t) (sign)<<31) + ((uint32_t) (exp)<<23) + (sig)) + +#define isNaNF32UI( a ) (((~(a) & 0x7F800000) == 0) && ((a) & 0x007FFFFF)) + +struct exp16_sig32 { int_fast16_t exp; uint_fast32_t sig; }; +struct exp16_sig32 softfloat_normSubnormalF32Sig( uint_fast32_t ); + +float32_t softfloat_roundPackToF32( bool, int_fast16_t, uint_fast32_t ); +float32_t softfloat_normRoundPackToF32( bool, int_fast16_t, uint_fast32_t ); + +float32_t softfloat_addMagsF32( uint_fast32_t, uint_fast32_t ); +float32_t softfloat_subMagsF32( uint_fast32_t, uint_fast32_t ); +float32_t + softfloat_mulAddF32( + uint_fast32_t, uint_fast32_t, uint_fast32_t, uint_fast8_t ); + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +#define signF64UI( a ) ((bool) ((uint64_t) (a)>>63)) +#define expF64UI( a ) ((int_fast16_t) ((a)>>52) & 0x7FF) +#define fracF64UI( a ) ((a) & UINT64_C( 0x000FFFFFFFFFFFFF )) +#define packToF64UI( sign, exp, sig ) ((uint64_t) (((uint_fast64_t) (sign)<<63) + ((uint_fast64_t) (exp)<<52) + (sig))) + +#define isNaNF64UI( a ) (((~(a) & UINT64_C( 0x7FF0000000000000 )) == 0) && ((a) & UINT64_C( 0x000FFFFFFFFFFFFF ))) + +struct exp16_sig64 { int_fast16_t exp; uint_fast64_t sig; }; +struct exp16_sig64 softfloat_normSubnormalF64Sig( uint_fast64_t ); + +float64_t softfloat_roundPackToF64( bool, int_fast16_t, uint_fast64_t ); +float64_t softfloat_normRoundPackToF64( bool, int_fast16_t, uint_fast64_t ); + +float64_t softfloat_addMagsF64( uint_fast64_t, uint_fast64_t, bool ); +float64_t softfloat_subMagsF64( uint_fast64_t, uint_fast64_t, bool ); +float64_t + softfloat_mulAddF64( + uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast8_t ); + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +#define signExtF80UI64( a64 ) ((bool) ((uint16_t) (a64)>>15)) +#define expExtF80UI64( a64 ) ((a64) & 0x7FFF) +#define packToExtF80UI64( sign, exp ) ((uint_fast16_t) (sign)<<15 | (exp)) + +#define isNaNExtF80UI( a64, a0 ) ((((a64) & 0x7FFF) == 0x7FFF) && ((a0) & UINT64_C( 0x7FFFFFFFFFFFFFFF ))) + +#ifdef SOFTFLOAT_FAST_INT64 + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ + +struct exp32_sig64 { int_fast32_t exp; uint64_t sig; }; +struct exp32_sig64 softfloat_normSubnormalExtF80Sig( uint_fast64_t ); + +extFloat80_t + softfloat_roundPackToExtF80( + bool, int_fast32_t, uint_fast64_t, uint_fast64_t, uint_fast8_t ); +extFloat80_t + softfloat_normRoundPackToExtF80( + bool, int_fast32_t, uint_fast64_t, uint_fast64_t, uint_fast8_t ); + +extFloat80_t + softfloat_addMagsExtF80( + uint_fast16_t, uint_fast64_t, uint_fast16_t, uint_fast64_t, bool ); +extFloat80_t + softfloat_subMagsExtF80( + uint_fast16_t, uint_fast64_t, uint_fast16_t, uint_fast64_t, bool ); + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +#define signF128UI64( a64 ) ((bool) ((uint64_t) (a64)>>63)) +#define expF128UI64( a64 ) ((int_fast32_t) ((a64)>>48) & 0x7FFF) +#define fracF128UI64( a64 ) ((a64) & UINT64_C( 0x0000FFFFFFFFFFFF )) +#define packToF128UI64( sign, exp, sig64 ) (((uint_fast64_t) (sign)<<63) + ((uint_fast64_t) (exp)<<48) + (sig64)) + +#define isNaNF128UI( a64, a0 ) (((~(a64) & UINT64_C( 0x7FFF000000000000 )) == 0) && (a0 || ((a64) & UINT64_C( 0x0000FFFFFFFFFFFF )))) + +struct exp32_sig128 { int_fast32_t exp; struct uint128 sig; }; +struct exp32_sig128 + softfloat_normSubnormalF128Sig( uint_fast64_t, uint_fast64_t ); + +float128_t + softfloat_roundPackToF128( + bool, int_fast32_t, uint_fast64_t, uint_fast64_t, uint_fast64_t ); +float128_t + softfloat_normRoundPackToF128( + bool, int_fast32_t, uint_fast64_t, uint_fast64_t ); + +float128_t + softfloat_addMagsF128( + uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool ); +float128_t + softfloat_subMagsF128( + uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool ); +float128_t + softfloat_mulAddF128( + uint_fast64_t, + uint_fast64_t, + uint_fast64_t, + uint_fast64_t, + uint_fast64_t, + uint_fast64_t, + uint_fast8_t + ); + +#else + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ + +bool + softfloat_tryPropagateNaNExtF80M( + const struct extFloat80M *, + const struct extFloat80M *, + struct extFloat80M * + ); +void softfloat_invalidExtF80M( struct extFloat80M * ); + +int softfloat_normExtF80SigM( uint64_t * ); + +void + softfloat_roundPackMToExtF80M( + bool, int32_t, uint32_t *, uint_fast8_t, struct extFloat80M * ); +void + softfloat_normRoundPackMToExtF80M( + bool, int32_t, uint32_t *, uint_fast8_t, struct extFloat80M * ); + +void + softfloat_addExtF80M( + const struct extFloat80M *, + const struct extFloat80M *, + struct extFloat80M *, + bool + ); + +int + softfloat_compareNonnormExtF80M( + const struct extFloat80M *, const struct extFloat80M * ); + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +#define signF128UI96( a96 ) ((bool) ((uint32_t) (a96)>>31)) +#define expF128UI96( a96 ) ((int32_t) ((a96)>>16) & 0x7FFF) +#define fracF128UI96( a96 ) ((a96) & 0x0000FFFF) +#define packToF128UI96( sign, exp, sig96 ) (((uint32_t) (sign)<<31) + ((uint32_t) (exp)<<16) + (sig96)) + +bool softfloat_isNaNF128M( const uint32_t * ); + +bool + softfloat_tryPropagateNaNF128M( + const uint32_t *, const uint32_t *, uint32_t * ); +void softfloat_invalidF128M( uint32_t * ); + +int softfloat_shiftNormSigF128M( const uint32_t *, uint_fast8_t, uint32_t * ); + +void softfloat_roundPackMToF128M( bool, int32_t, uint32_t *, uint32_t * ); +void softfloat_normRoundPackMToF128M( bool, int32_t, uint32_t *, uint32_t * ); + +void + softfloat_addF128M( const uint32_t *, const uint32_t *, uint32_t *, bool ); +void + softfloat_mulAddF128M( + const uint32_t *, + const uint32_t *, + const uint32_t *, + uint32_t *, + uint_fast8_t + ); + +#endif + +#endif + +/**** ended inlining internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Interpreting `uiA' and `uiB' as the bit patterns of two 16-bit floating- +| point values, at least one of which is a NaN, returns the bit pattern of +| the combined NaN result. If either `uiA' or `uiB' has the pattern of a +| signaling NaN, the invalid exception is raised. +*----------------------------------------------------------------------------*/ +uint_fast16_t + softfloat_propagateNaNF16UI( uint_fast16_t uiA, uint_fast16_t uiB ) +{ + bool isSigNaNA; + + isSigNaNA = softfloat_isSigNaNF16UI( uiA ); + if ( isSigNaNA || softfloat_isSigNaNF16UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + if ( isSigNaNA ) return uiA | 0x0200; + } + return (isNaNF16UI( uiA ) ? uiA : uiB) | 0x0200; + +} + +/**** ended inlining ../../source/8086-SSE/s_propagateNaNF16UI.c ****/ +/**** start inlining ../../source/8086-SSE/s_f32UIToCommonNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Assuming `uiA' has the bit pattern of a 32-bit floating-point NaN, converts +| this NaN to the common NaN form, and stores the resulting common NaN at the +| location pointed to by `zPtr'. If the NaN is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +void softfloat_f32UIToCommonNaN( uint_fast32_t uiA, struct commonNaN *zPtr ) +{ + + if ( softfloat_isSigNaNF32UI( uiA ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + zPtr->sign = uiA>>31; + zPtr->v64 = (uint_fast64_t) uiA<<41; + zPtr->v0 = 0; + +} + +/**** ended inlining ../../source/8086-SSE/s_f32UIToCommonNaN.c ****/ +/**** start inlining ../../source/8086-SSE/s_commonNaNToF32UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: specialize.h ****/ + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by `aPtr' into a 32-bit floating-point +| NaN, and returns the bit pattern of this value as an unsigned integer. +*----------------------------------------------------------------------------*/ +uint_fast32_t softfloat_commonNaNToF32UI( const struct commonNaN *aPtr ) +{ + + return (uint_fast32_t) aPtr->sign<<31 | 0x7FC00000 | aPtr->v64>>41; + +} + +/**** ended inlining ../../source/8086-SSE/s_commonNaNToF32UI.c ****/ +/**** start inlining ../../source/8086-SSE/s_propagateNaNF32UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Interpreting `uiA' and `uiB' as the bit patterns of two 32-bit floating- +| point values, at least one of which is a NaN, returns the bit pattern of +| the combined NaN result. If either `uiA' or `uiB' has the pattern of a +| signaling NaN, the invalid exception is raised. +*----------------------------------------------------------------------------*/ +uint_fast32_t + softfloat_propagateNaNF32UI( uint_fast32_t uiA, uint_fast32_t uiB ) +{ + bool isSigNaNA; + + isSigNaNA = softfloat_isSigNaNF32UI( uiA ); + if ( isSigNaNA || softfloat_isSigNaNF32UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + if ( isSigNaNA ) return uiA | 0x00400000; + } + return (isNaNF32UI( uiA ) ? uiA : uiB) | 0x00400000; + +} + +/**** ended inlining ../../source/8086-SSE/s_propagateNaNF32UI.c ****/ +/**** start inlining ../../source/8086-SSE/s_f64UIToCommonNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Assuming `uiA' has the bit pattern of a 64-bit floating-point NaN, converts +| this NaN to the common NaN form, and stores the resulting common NaN at the +| location pointed to by `zPtr'. If the NaN is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +void softfloat_f64UIToCommonNaN( uint_fast64_t uiA, struct commonNaN *zPtr ) +{ + + if ( softfloat_isSigNaNF64UI( uiA ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + zPtr->sign = uiA>>63; + zPtr->v64 = uiA<<12; + zPtr->v0 = 0; + +} + +/**** ended inlining ../../source/8086-SSE/s_f64UIToCommonNaN.c ****/ +/**** start inlining ../../source/8086-SSE/s_commonNaNToF64UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: specialize.h ****/ + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by `aPtr' into a 64-bit floating-point +| NaN, and returns the bit pattern of this value as an unsigned integer. +*----------------------------------------------------------------------------*/ +uint_fast64_t softfloat_commonNaNToF64UI( const struct commonNaN *aPtr ) +{ + + return + (uint_fast64_t) aPtr->sign<<63 | UINT64_C( 0x7FF8000000000000 ) + | aPtr->v64>>12; + +} + +/**** ended inlining ../../source/8086-SSE/s_commonNaNToF64UI.c ****/ +/**** start inlining ../../source/8086-SSE/s_propagateNaNF64UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Interpreting `uiA' and `uiB' as the bit patterns of two 64-bit floating- +| point values, at least one of which is a NaN, returns the bit pattern of +| the combined NaN result. If either `uiA' or `uiB' has the pattern of a +| signaling NaN, the invalid exception is raised. +*----------------------------------------------------------------------------*/ +uint_fast64_t + softfloat_propagateNaNF64UI( uint_fast64_t uiA, uint_fast64_t uiB ) +{ + bool isSigNaNA; + + isSigNaNA = softfloat_isSigNaNF64UI( uiA ); + if ( isSigNaNA || softfloat_isSigNaNF64UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + if ( isSigNaNA ) return uiA | UINT64_C( 0x0008000000000000 ); + } + return (isNaNF64UI( uiA ) ? uiA : uiB) | UINT64_C( 0x0008000000000000 ); + +} + +/**** ended inlining ../../source/8086-SSE/s_propagateNaNF64UI.c ****/ +/**** start inlining ../../source/8086-SSE/extF80M_isSignalingNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +bool extF80M_isSignalingNaN( const extFloat80_t *aPtr ) +{ + const struct extFloat80M *aSPtr; + uint64_t uiA0; + + aSPtr = (const struct extFloat80M *) aPtr; + if ( (aSPtr->signExp & 0x7FFF) != 0x7FFF ) return false; + uiA0 = aSPtr->signif; + return + ! (uiA0 & UINT64_C( 0x4000000000000000 )) + && (uiA0 & UINT64_C( 0x3FFFFFFFFFFFFFFF)); + +} + +/**** ended inlining ../../source/8086-SSE/extF80M_isSignalingNaN.c ****/ +/**** start inlining ../../source/8086-SSE/s_extF80UIToCommonNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Assuming the unsigned integer formed from concatenating `uiA64' and `uiA0' +| has the bit pattern of an 80-bit extended floating-point NaN, converts +| this NaN to the common NaN form, and stores the resulting common NaN at the +| location pointed to by `zPtr'. If the NaN is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +void + softfloat_extF80UIToCommonNaN( + uint_fast16_t uiA64, uint_fast64_t uiA0, struct commonNaN *zPtr ) +{ + + if ( softfloat_isSigNaNExtF80UI( uiA64, uiA0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + zPtr->sign = uiA64>>15; + zPtr->v64 = uiA0<<1; + zPtr->v0 = 0; + +} + +/**** ended inlining ../../source/8086-SSE/s_extF80UIToCommonNaN.c ****/ +/**** start inlining ../../source/8086-SSE/s_commonNaNToExtF80UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitives.h ****/ +/**** skipping file: specialize.h ****/ + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by `aPtr' into an 80-bit extended +| floating-point NaN, and returns the bit pattern of this value as an unsigned +| integer. +*----------------------------------------------------------------------------*/ +struct uint128 softfloat_commonNaNToExtF80UI( const struct commonNaN *aPtr ) +{ + struct uint128 uiZ; + + uiZ.v64 = (uint_fast16_t) aPtr->sign<<15 | 0x7FFF; + uiZ.v0 = UINT64_C( 0xC000000000000000 ) | aPtr->v64>>1; + return uiZ; + +} + +/**** ended inlining ../../source/8086-SSE/s_commonNaNToExtF80UI.c ****/ +/**** start inlining ../../source/8086-SSE/s_propagateNaNExtF80UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2018 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Interpreting the unsigned integer formed from concatenating 'uiA64' and +| 'uiA0' as an 80-bit extended floating-point value, and likewise interpreting +| the unsigned integer formed from concatenating 'uiB64' and 'uiB0' as another +| 80-bit extended floating-point value, and assuming at least on of these +| floating-point values is a NaN, returns the bit pattern of the combined NaN +| result. If either original floating-point value is a signaling NaN, the +| invalid exception is raised. +*----------------------------------------------------------------------------*/ +struct uint128 + softfloat_propagateNaNExtF80UI( + uint_fast16_t uiA64, + uint_fast64_t uiA0, + uint_fast16_t uiB64, + uint_fast64_t uiB0 + ) +{ + bool isSigNaNA, isSigNaNB; + uint_fast64_t uiNonsigA0, uiNonsigB0; + uint_fast16_t uiMagA64, uiMagB64; + struct uint128 uiZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + isSigNaNA = softfloat_isSigNaNExtF80UI( uiA64, uiA0 ); + isSigNaNB = softfloat_isSigNaNExtF80UI( uiB64, uiB0 ); + /*------------------------------------------------------------------------ + | Make NaNs non-signaling. + *------------------------------------------------------------------------*/ + uiNonsigA0 = uiA0 | UINT64_C( 0xC000000000000000 ); + uiNonsigB0 = uiB0 | UINT64_C( 0xC000000000000000 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( isSigNaNA | isSigNaNB ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + if ( isSigNaNA ) { + if ( isSigNaNB ) goto returnLargerMag; + if ( isNaNExtF80UI( uiB64, uiB0 ) ) goto returnB; + goto returnA; + } else { + if ( isNaNExtF80UI( uiA64, uiA0 ) ) goto returnA; + goto returnB; + } + } + returnLargerMag: + uiMagA64 = uiA64 & 0x7FFF; + uiMagB64 = uiB64 & 0x7FFF; + if ( uiMagA64 < uiMagB64 ) goto returnB; + if ( uiMagB64 < uiMagA64 ) goto returnA; + if ( uiA0 < uiB0 ) goto returnB; + if ( uiB0 < uiA0 ) goto returnA; + if ( uiA64 < uiB64 ) goto returnA; + returnB: + uiZ.v64 = uiB64; + uiZ.v0 = uiNonsigB0; + return uiZ; + returnA: + uiZ.v64 = uiA64; + uiZ.v0 = uiNonsigA0; + return uiZ; + +} + +/**** ended inlining ../../source/8086-SSE/s_propagateNaNExtF80UI.c ****/ +/**** start inlining ../../source/8086-SSE/f128M_isSignalingNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitives.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ +bool f128M_isSignalingNaN( const float128_t *aPtr ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + if ( (uiA96 & 0x7FFF8000) != 0x7FFF0000 ) return false; + return + ((uiA96 & 0x00007FFF) != 0) + || ((aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )] + | aWPtr[indexWord( 4, 0 )]) + != 0); + +} + +/**** ended inlining ../../source/8086-SSE/f128M_isSignalingNaN.c ****/ +/**** start inlining ../../source/8086-SSE/s_f128UIToCommonNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitives.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Assuming the unsigned integer formed from concatenating `uiA64' and `uiA0' +| has the bit pattern of a 128-bit floating-point NaN, converts this NaN to +| the common NaN form, and stores the resulting common NaN at the location +| pointed to by `zPtr'. If the NaN is a signaling NaN, the invalid exception +| is raised. +*----------------------------------------------------------------------------*/ +void + softfloat_f128UIToCommonNaN( + uint_fast64_t uiA64, uint_fast64_t uiA0, struct commonNaN *zPtr ) +{ + struct uint128 NaNSig; + + if ( softfloat_isSigNaNF128UI( uiA64, uiA0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + NaNSig = softfloat_shortShiftLeft128( uiA64, uiA0, 16 ); + zPtr->sign = uiA64>>63; + zPtr->v64 = NaNSig.v64; + zPtr->v0 = NaNSig.v0; + +} + +/**** ended inlining ../../source/8086-SSE/s_f128UIToCommonNaN.c ****/ +/**** start inlining ../../source/8086-SSE/s_commonNaNToF128UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitives.h ****/ +/**** skipping file: specialize.h ****/ + +/*---------------------------------------------------------------------------- +| Converts the common NaN pointed to by `aPtr' into a 128-bit floating-point +| NaN, and returns the bit pattern of this value as an unsigned integer. +*----------------------------------------------------------------------------*/ +struct uint128 softfloat_commonNaNToF128UI( const struct commonNaN *aPtr ) +{ + struct uint128 uiZ; + + uiZ = softfloat_shortShiftRight128( aPtr->v64, aPtr->v0, 16 ); + uiZ.v64 |= (uint_fast64_t) aPtr->sign<<63 | UINT64_C( 0x7FFF800000000000 ); + return uiZ; + +} + +/**** ended inlining ../../source/8086-SSE/s_commonNaNToF128UI.c ****/ +/**** start inlining ../../source/8086-SSE/s_propagateNaNF128UI.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +/*---------------------------------------------------------------------------- +| Interpreting the unsigned integer formed from concatenating `uiA64' and +| `uiA0' as a 128-bit floating-point value, and likewise interpreting the +| unsigned integer formed from concatenating `uiB64' and `uiB0' as another +| 128-bit floating-point value, and assuming at least on of these floating- +| point values is a NaN, returns the bit pattern of the combined NaN result. +| If either original floating-point value is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +struct uint128 + softfloat_propagateNaNF128UI( + uint_fast64_t uiA64, + uint_fast64_t uiA0, + uint_fast64_t uiB64, + uint_fast64_t uiB0 + ) +{ + bool isSigNaNA; + struct uint128 uiZ; + + isSigNaNA = softfloat_isSigNaNF128UI( uiA64, uiA0 ); + if ( isSigNaNA || softfloat_isSigNaNF128UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + if ( isSigNaNA ) goto returnNonsigA; + } + if ( isNaNF128UI( uiA64, uiA0 ) ) { + returnNonsigA: + uiZ.v64 = uiA64; + uiZ.v0 = uiA0; + } else { + uiZ.v64 = uiB64; + uiZ.v0 = uiB0; + } + uiZ.v64 |= UINT64_C( 0x0000800000000000 ); + return uiZ; + +} + +/**** ended inlining ../../source/8086-SSE/s_propagateNaNF128UI.c ****/ + +/**** start inlining ../../source/s_eq128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_eq128 +#define softfloat_eq128 softfloat_eq128 + +bool softfloat_eq128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) +{ + + return (a64 == b64) && (a0 == b0); + +} + +#endif + +/**** ended inlining ../../source/s_eq128.c ****/ +/**** start inlining ../../source/s_le128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_le128 +#define softfloat_le128 softfloat_le128 + +bool softfloat_le128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) +{ + + return (a64 < b64) || ((a64 == b64) && (a0 <= b0)); + +} + +#endif + +/**** ended inlining ../../source/s_le128.c ****/ +/**** start inlining ../../source/s_lt128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_lt128 +#define softfloat_lt128 softfloat_lt128 + +bool softfloat_lt128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) +{ + + return (a64 < b64) || ((a64 == b64) && (a0 < b0)); + +} + +#endif + +/**** ended inlining ../../source/s_lt128.c ****/ +/**** start inlining ../../source/s_shortShiftLeft128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shortShiftLeft128 +#define softfloat_shortShiftLeft128 softfloat_shortShiftLeft128 + +struct uint128 + softfloat_shortShiftLeft128( uint64_t a64, uint64_t a0, uint_fast8_t dist ) +{ + struct uint128 z; + + z.v64 = a64<>(-dist & 63); + z.v0 = a0< +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shortShiftRight128 +#define softfloat_shortShiftRight128 softfloat_shortShiftRight128 + +struct uint128 + softfloat_shortShiftRight128( uint64_t a64, uint64_t a0, uint_fast8_t dist ) +{ + struct uint128 z; + + z.v64 = a64>>dist; + z.v0 = a64<<(-dist & 63) | a0>>dist; + return z; + +} + +#endif + +/**** ended inlining ../../source/s_shortShiftRight128.c ****/ +/**** start inlining ../../source/s_shortShiftRightJam64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_shortShiftRightJam64 +#define softfloat_shortShiftRightJam64 softfloat_shortShiftRightJam64 + +uint64_t softfloat_shortShiftRightJam64( uint64_t a, uint_fast8_t dist ) +{ + + return a>>dist | ((a & (((uint_fast64_t) 1< +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shortShiftRightJam64Extra +#define softfloat_shortShiftRightJam64Extra softfloat_shortShiftRightJam64Extra + +struct uint64_extra + softfloat_shortShiftRightJam64Extra( + uint64_t a, uint64_t extra, uint_fast8_t dist ) +{ + struct uint64_extra z; + + z.v = a>>dist; + z.extra = a<<(-dist & 63) | (extra != 0); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_shortShiftRightJam64Extra.c ****/ +/**** start inlining ../../source/s_shortShiftRightJam128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shortShiftRightJam128 +#define softfloat_shortShiftRightJam128 softfloat_shortShiftRightJam128 + +struct uint128 + softfloat_shortShiftRightJam128( + uint64_t a64, uint64_t a0, uint_fast8_t dist ) +{ + uint_fast8_t uNegDist; + struct uint128 z; + + uNegDist = -dist; + z.v64 = a64>>dist; + z.v0 = + a64<<(uNegDist & 63) | a0>>dist + | ((uint64_t) (a0<<(uNegDist & 63)) != 0); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_shortShiftRightJam128.c ****/ +/**** start inlining ../../source/s_shortShiftRightJam128Extra.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shortShiftRightJam128Extra +#define softfloat_shortShiftRightJam128Extra softfloat_shortShiftRightJam128Extra + +struct uint128_extra + softfloat_shortShiftRightJam128Extra( + uint64_t a64, uint64_t a0, uint64_t extra, uint_fast8_t dist ) +{ + uint_fast8_t uNegDist; + struct uint128_extra z; + + uNegDist = -dist; + z.v.v64 = a64>>dist; + z.v.v0 = a64<<(uNegDist & 63) | a0>>dist; + z.extra = a0<<(uNegDist & 63) | (extra != 0); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_shortShiftRightJam128Extra.c ****/ +/**** start inlining ../../source/s_shiftRightJam32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_shiftRightJam32 +#define softfloat_shiftRightJam32 softfloat_shiftRightJam32 + +uint32_t softfloat_shiftRightJam32( uint32_t a, uint_fast16_t dist ) +{ + + return + (dist < 31) ? a>>dist | ((uint32_t) (a<<(-dist & 31)) != 0) : (a != 0); + +} + +#endif + +/**** ended inlining ../../source/s_shiftRightJam32.c ****/ +/**** start inlining ../../source/s_shiftRightJam64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_shiftRightJam64 +#define softfloat_shiftRightJam64 softfloat_shiftRightJam64 + +uint64_t softfloat_shiftRightJam64( uint64_t a, uint_fast32_t dist ) +{ + + return + (dist < 63) ? a>>dist | ((uint64_t) (a<<(-dist & 63)) != 0) : (a != 0); + +} + +#endif + +/**** ended inlining ../../source/s_shiftRightJam64.c ****/ +/**** start inlining ../../source/s_shiftRightJam64Extra.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shiftRightJam64Extra +#define softfloat_shiftRightJam64Extra softfloat_shiftRightJam64Extra + +struct uint64_extra + softfloat_shiftRightJam64Extra( + uint64_t a, uint64_t extra, uint_fast32_t dist ) +{ + struct uint64_extra z; + + if ( dist < 64 ) { + z.v = a>>dist; + z.extra = a<<(-dist & 63); + } else { + z.v = 0; + z.extra = (dist == 64) ? a : (a != 0); + } + z.extra |= (extra != 0); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_shiftRightJam64Extra.c ****/ +/**** start inlining ../../source/s_shiftRightJam128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shiftRightJam128 + +struct uint128 + softfloat_shiftRightJam128( uint64_t a64, uint64_t a0, uint_fast32_t dist ) +{ + uint_fast8_t u8NegDist; + struct uint128 z; + + if ( dist < 64 ) { + u8NegDist = -dist; + z.v64 = a64>>dist; + z.v0 = + a64<<(u8NegDist & 63) | a0>>dist + | ((uint64_t) (a0<<(u8NegDist & 63)) != 0); + } else { + z.v64 = 0; + z.v0 = + (dist < 127) + ? a64>>(dist & 63) + | (((a64 & (((uint_fast64_t) 1<<(dist & 63)) - 1)) | a0) + != 0) + : ((a64 | a0) != 0); + } + return z; + +} + +#endif + +/**** ended inlining ../../source/s_shiftRightJam128.c ****/ +/**** start inlining ../../source/s_shiftRightJam128Extra.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shiftRightJam128Extra + +struct uint128_extra + softfloat_shiftRightJam128Extra( + uint64_t a64, uint64_t a0, uint64_t extra, uint_fast32_t dist ) +{ + uint_fast8_t u8NegDist; + struct uint128_extra z; + + u8NegDist = -dist; + if ( dist < 64 ) { + z.v.v64 = a64>>dist; + z.v.v0 = a64<<(u8NegDist & 63) | a0>>dist; + z.extra = a0<<(u8NegDist & 63); + } else { + z.v.v64 = 0; + if ( dist == 64 ) { + z.v.v0 = a64; + z.extra = a0; + } else { + extra |= a0; + if ( dist < 128 ) { + z.v.v0 = a64>>(dist & 63); + z.extra = a64<<(u8NegDist & 63); + } else { + z.v.v0 = 0; + z.extra = (dist == 128) ? a64 : (a64 != 0); + } + } + } + z.extra |= (extra != 0); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_shiftRightJam128Extra.c ****/ +/**** start inlining ../../source/s_shiftRightJam256M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_shiftRightJam256M + +static + void + softfloat_shortShiftRightJamM( + uint_fast8_t size_words, + const uint64_t *aPtr, + uint_fast8_t dist, + uint64_t *zPtr + ) +{ + uint_fast8_t uNegDist; + unsigned int index, lastIndex; + uint64_t partWordZ, wordA; + + uNegDist = -dist; + index = indexWordLo( size_words ); + lastIndex = indexWordHi( size_words ); + wordA = aPtr[index]; + partWordZ = wordA>>dist; + if ( partWordZ<>dist; + } + zPtr[index] = partWordZ; + +} + +void + softfloat_shiftRightJam256M( + const uint64_t *aPtr, uint_fast32_t dist, uint64_t *zPtr ) +{ + uint64_t wordJam; + uint_fast32_t wordDist; + uint64_t *ptr; + uint_fast8_t i, innerDist; + + wordJam = 0; + wordDist = dist>>6; + if ( wordDist ) { + if ( 4 < wordDist ) wordDist = 4; + ptr = (uint64_t *) (aPtr + indexMultiwordLo( 4, wordDist )); + i = wordDist; + do { + wordJam = *ptr++; + if ( wordJam ) break; + --i; + } while ( i ); + ptr = zPtr; + } + if ( wordDist < 4 ) { + aPtr += indexMultiwordHiBut( 4, wordDist ); + innerDist = dist & 63; + if ( innerDist ) { + softfloat_shortShiftRightJamM( + 4 - wordDist, + aPtr, + innerDist, + zPtr + indexMultiwordLoBut( 4, wordDist ) + ); + if ( ! wordDist ) goto wordJam; + } else { + aPtr += indexWordLo( 4 - wordDist ); + ptr = zPtr + indexWordLo( 4 ); + for ( i = 4 - wordDist; i; --i ) { + *ptr = *aPtr; + aPtr += wordIncr; + ptr += wordIncr; + } + } + ptr = zPtr + indexMultiwordHi( 4, wordDist ); + } + do { + *ptr++ = 0; + --wordDist; + } while ( wordDist ); + wordJam: + if ( wordJam ) zPtr[indexWordLo( 4 )] |= 1; + +} + +#endif + +/**** ended inlining ../../source/s_shiftRightJam256M.c ****/ +/**** start inlining ../../source/s_countLeadingZeros8.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitives.h ****/ + +const uint_least8_t softfloat_countLeadingZeros8[256] = { + 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +/**** ended inlining ../../source/s_countLeadingZeros8.c ****/ +/**** start inlining ../../source/s_countLeadingZeros16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_countLeadingZeros16 + +#define softfloat_countLeadingZeros16 softfloat_countLeadingZeros16 +/**** skipping file: primitives.h ****/ + +uint_fast8_t softfloat_countLeadingZeros16( uint16_t a ) +{ + uint_fast8_t count; + + count = 8; + if ( 0x100 <= a ) { + count = 0; + a >>= 8; + } + count += softfloat_countLeadingZeros8[a]; + return count; + +} + +#endif + +/**** ended inlining ../../source/s_countLeadingZeros16.c ****/ +/**** start inlining ../../source/s_countLeadingZeros32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_countLeadingZeros32 + +#define softfloat_countLeadingZeros32 softfloat_countLeadingZeros32 +/**** skipping file: primitives.h ****/ + +uint_fast8_t softfloat_countLeadingZeros32( uint32_t a ) +{ + uint_fast8_t count; + + count = 0; + if ( a < 0x10000 ) { + count = 16; + a <<= 16; + } + if ( a < 0x1000000 ) { + count += 8; + a <<= 8; + } + count += softfloat_countLeadingZeros8[a>>24]; + return count; + +} + +#endif + +/**** ended inlining ../../source/s_countLeadingZeros32.c ****/ +/**** start inlining ../../source/s_countLeadingZeros64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_countLeadingZeros64 + +#define softfloat_countLeadingZeros64 softfloat_countLeadingZeros64 +/**** skipping file: primitives.h ****/ + +uint_fast8_t softfloat_countLeadingZeros64( uint64_t a ) +{ + uint_fast8_t count; + uint32_t a32; + + count = 0; + a32 = a>>32; + if ( ! a32 ) { + count = 32; + a32 = a; + } + /*------------------------------------------------------------------------ + | From here, result is current count + count leading zeros of `a32'. + *------------------------------------------------------------------------*/ + if ( a32 < 0x10000 ) { + count += 16; + a32 <<= 16; + } + if ( a32 < 0x1000000 ) { + count += 8; + a32 <<= 8; + } + count += softfloat_countLeadingZeros8[a32>>24]; + return count; + +} + +#endif + +/**** ended inlining ../../source/s_countLeadingZeros64.c ****/ +/**** start inlining ../../source/s_add128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_add128 + +struct uint128 + softfloat_add128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) +{ + struct uint128 z; + + z.v0 = a0 + b0; + z.v64 = a64 + b64 + (z.v0 < a0); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_add128.c ****/ +/**** start inlining ../../source/s_add256M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_add256M + +void + softfloat_add256M( + const uint64_t *aPtr, const uint64_t *bPtr, uint64_t *zPtr ) +{ + unsigned int index; + uint_fast8_t carry; + uint64_t wordA, wordZ; + + index = indexWordLo( 4 ); + carry = 0; + for (;;) { + wordA = aPtr[index]; + wordZ = wordA + bPtr[index] + carry; + zPtr[index] = wordZ; + if ( index == indexWordHi( 4 ) ) break; + if ( wordZ != wordA ) carry = (wordZ < wordA); + index += wordIncr; + } + +} + +#endif + +/**** ended inlining ../../source/s_add256M.c ****/ +/**** start inlining ../../source/s_sub128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_sub128 +#define softfloat_sub128 softfloat_sub128 + +struct uint128 + softfloat_sub128( uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0 ) +{ + struct uint128 z; + + z.v0 = a0 - b0; + z.v64 = a64 - b64 - (a0 < b0); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_sub128.c ****/ +/**** start inlining ../../source/s_sub256M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_sub256M + +void + softfloat_sub256M( + const uint64_t *aPtr, const uint64_t *bPtr, uint64_t *zPtr ) +{ + unsigned int index; + uint_fast8_t borrow; + uint64_t wordA, wordB; + + index = indexWordLo( 4 ); + borrow = 0; + for (;;) { + wordA = aPtr[index]; + wordB = bPtr[index]; + zPtr[index] = wordA - wordB - borrow; + if ( index == indexWordHi( 4 ) ) break; + borrow = borrow ? (wordA <= wordB) : (wordA < wordB); + index += wordIncr; + } + +} + +#endif + +/**** ended inlining ../../source/s_sub256M.c ****/ +/**** start inlining ../../source/s_mul64ByShifted32To128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_mul64ByShifted32To128 + +struct uint128 softfloat_mul64ByShifted32To128( uint64_t a, uint32_t b ) +{ + uint_fast64_t mid; + struct uint128 z; + + mid = (uint_fast64_t) (uint32_t) a * b; + z.v0 = mid<<32; + z.v64 = (uint_fast64_t) (uint32_t) (a>>32) * b + (mid>>32); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_mul64ByShifted32To128.c ****/ +/**** start inlining ../../source/s_mul64To128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_mul64To128 + +struct uint128 softfloat_mul64To128( uint64_t a, uint64_t b ) +{ + uint32_t a32, a0, b32, b0; + struct uint128 z; + uint64_t mid1, mid; + + a32 = a>>32; + a0 = a; + b32 = b>>32; + b0 = b; + z.v0 = (uint_fast64_t) a0 * b0; + mid1 = (uint_fast64_t) a32 * b0; + mid = mid1 + (uint_fast64_t) a0 * b32; + z.v64 = (uint_fast64_t) a32 * b32; + z.v64 += (uint_fast64_t) (mid < mid1)<<32 | mid>>32; + mid <<= 32; + z.v0 += mid; + z.v64 += (z.v0 < mid); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_mul64To128.c ****/ +/**** start inlining ../../source/s_mul128By32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitiveTypes.h ****/ + +#ifndef softfloat_mul128By32 + +struct uint128 softfloat_mul128By32( uint64_t a64, uint64_t a0, uint32_t b ) +{ + struct uint128 z; + uint_fast64_t mid; + uint_fast32_t carry; + + z.v0 = a0 * b; + mid = (uint_fast64_t) (uint32_t) (a0>>32) * b; + carry = (uint32_t) ((uint_fast32_t) (z.v0>>32) - (uint_fast32_t) mid); + z.v64 = a64 * b + (uint_fast32_t) ((mid + carry)>>32); + return z; + +} + +#endif + +/**** ended inlining ../../source/s_mul128By32.c ****/ +/**** start inlining ../../source/s_mul128To256M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_mul128To256M + +#define softfloat_mul128To256M softfloat_mul128To256M +/**** skipping file: primitives.h ****/ + +void + softfloat_mul128To256M( + uint64_t a64, uint64_t a0, uint64_t b64, uint64_t b0, uint64_t *zPtr ) +{ + struct uint128 p0, p64, p128; + uint_fast64_t z64, z128, z192; + + p0 = softfloat_mul64To128( a0, b0 ); + zPtr[indexWord( 4, 0 )] = p0.v0; + p64 = softfloat_mul64To128( a64, b0 ); + z64 = p64.v0 + p0.v64; + z128 = p64.v64 + (z64 < p64.v0); + p128 = softfloat_mul64To128( a64, b64 ); + z128 += p128.v0; + z192 = p128.v64 + (z128 < p128.v0); + p64 = softfloat_mul64To128( a0, b64 ); + z64 += p64.v0; + zPtr[indexWord( 4, 1 )] = z64; + p64.v64 += (z64 < p64.v0); + z128 += p64.v64; + zPtr[indexWord( 4, 2 )] = z128; + zPtr[indexWord( 4, 3 )] = z192 + (z128 < p64.v64); + +} + +#endif + +/**** ended inlining ../../source/s_mul128To256M.c ****/ +/**** start inlining ../../source/s_approxRecip_1Ks.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitives.h ****/ + +const uint16_t softfloat_approxRecip_1k0s[16] = { + 0xFFC4, 0xF0BE, 0xE363, 0xD76F, 0xCCAD, 0xC2F0, 0xBA16, 0xB201, + 0xAA97, 0xA3C6, 0x9D7A, 0x97A6, 0x923C, 0x8D32, 0x887E, 0x8417 +}; +const uint16_t softfloat_approxRecip_1k1s[16] = { + 0xF0F1, 0xD62C, 0xBFA1, 0xAC77, 0x9C0A, 0x8DDB, 0x8185, 0x76BA, + 0x6D3B, 0x64D4, 0x5D5C, 0x56B1, 0x50B6, 0x4B55, 0x4679, 0x4211 +}; + +/**** ended inlining ../../source/s_approxRecip_1Ks.c ****/ +/**** start inlining ../../source/s_approxRecip32_1.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_approxRecip32_1 + +extern const uint16_t softfloat_approxRecip_1k0s[16]; +extern const uint16_t softfloat_approxRecip_1k1s[16]; + +uint32_t softfloat_approxRecip32_1( uint32_t a ) +{ + int index; + uint16_t eps, r0; + uint32_t sigma0; + uint_fast32_t r; + uint32_t sqrSigma0; + + index = a>>27 & 0xF; + eps = (uint16_t) (a>>11); + r0 = softfloat_approxRecip_1k0s[index] + - ((softfloat_approxRecip_1k1s[index] * (uint_fast32_t) eps)>>20); + sigma0 = ~(uint_fast32_t) ((r0 * (uint_fast64_t) a)>>7); + r = ((uint_fast32_t) r0<<16) + ((r0 * (uint_fast64_t) sigma0)>>24); + sqrSigma0 = ((uint_fast64_t) sigma0 * sigma0)>>32; + r += ((uint32_t) r * (uint_fast64_t) sqrSigma0)>>48; + return r; + +} + +#endif + +/**** ended inlining ../../source/s_approxRecip32_1.c ****/ +/**** start inlining ../../source/s_approxRecipSqrt_1Ks.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: primitives.h ****/ + +const uint16_t softfloat_approxRecipSqrt_1k0s[16] = { + 0xB4C9, 0xFFAB, 0xAA7D, 0xF11C, 0xA1C5, 0xE4C7, 0x9A43, 0xDA29, + 0x93B5, 0xD0E5, 0x8DED, 0xC8B7, 0x88C6, 0xC16D, 0x8424, 0xBAE1 +}; +const uint16_t softfloat_approxRecipSqrt_1k1s[16] = { + 0xA5A5, 0xEA42, 0x8C21, 0xC62D, 0x788F, 0xAA7F, 0x6928, 0x94B6, + 0x5CC7, 0x8335, 0x52A6, 0x74E2, 0x4A3E, 0x68FE, 0x432B, 0x5EFD +}; + +/**** ended inlining ../../source/s_approxRecipSqrt_1Ks.c ****/ +/**** start inlining ../../source/s_approxRecipSqrt32_1.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ + +#ifndef softfloat_approxRecipSqrt32_1 + +extern const uint16_t softfloat_approxRecipSqrt_1k0s[]; +extern const uint16_t softfloat_approxRecipSqrt_1k1s[]; + +uint32_t softfloat_approxRecipSqrt32_1( unsigned int oddExpA, uint32_t a ) +{ + int index; + uint16_t eps, r0; + uint_fast32_t ESqrR0; + uint32_t sigma0; + uint_fast32_t r; + uint32_t sqrSigma0; + + index = (a>>27 & 0xE) + oddExpA; + eps = (uint16_t) (a>>12); + r0 = softfloat_approxRecipSqrt_1k0s[index] + - ((softfloat_approxRecipSqrt_1k1s[index] * (uint_fast32_t) eps) + >>20); + ESqrR0 = (uint_fast32_t) r0 * r0; + if ( ! oddExpA ) ESqrR0 <<= 1; + sigma0 = ~(uint_fast32_t) (((uint32_t) ESqrR0 * (uint_fast64_t) a)>>23); + r = ((uint_fast32_t) r0<<16) + ((r0 * (uint_fast64_t) sigma0)>>25); + sqrSigma0 = ((uint_fast64_t) sigma0 * sigma0)>>32; + r += ((uint32_t) ((r>>1) + (r>>3) - ((uint_fast32_t) r0<<14)) + * (uint_fast64_t) sqrSigma0) + >>48; + if ( ! (r & 0x80000000) ) r = 0x80000000; + return r; + +} + +#endif + +/**** ended inlining ../../source/s_approxRecipSqrt32_1.c ****/ +/**** start inlining ../../source/s_roundToUI32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t + softfloat_roundToUI32( + bool sign, uint_fast64_t sig, uint_fast8_t roundingMode, bool exact ) +{ + uint_fast16_t roundIncrement, roundBits; + uint_fast32_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + roundIncrement = 0x800; + if ( + (roundingMode != softfloat_round_near_maxMag) + && (roundingMode != softfloat_round_near_even) + ) { + roundIncrement = 0; + if ( sign ) { + if ( !sig ) return 0; + if ( roundingMode == softfloat_round_min ) goto invalid; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) goto invalid; +#endif + } else { + if ( roundingMode == softfloat_round_max ) roundIncrement = 0xFFF; + } + } + roundBits = sig & 0xFFF; + sig += roundIncrement; + if ( sig & UINT64_C( 0xFFFFF00000000000 ) ) goto invalid; + z = sig>>12; + if ( + (roundBits == 0x800) && (roundingMode == softfloat_round_near_even) + ) { + z &= ~(uint_fast32_t) 1; + } + if ( sign && z ) goto invalid; + if ( roundBits ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) z |= 1; +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return z; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return sign ? ui32_fromNegOverflow : ui32_fromPosOverflow; + +} + +/**** ended inlining ../../source/s_roundToUI32.c ****/ +/**** start inlining ../../source/s_roundToUI64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t + softfloat_roundToUI64( + bool sign, + uint_fast64_t sig, + uint_fast64_t sigExtra, + uint_fast8_t roundingMode, + bool exact + ) +{ + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( + (roundingMode == softfloat_round_near_maxMag) + || (roundingMode == softfloat_round_near_even) + ) { + if ( UINT64_C( 0x8000000000000000 ) <= sigExtra ) goto increment; + } else { + if ( sign ) { + if ( !(sig | sigExtra) ) return 0; + if ( roundingMode == softfloat_round_min ) goto invalid; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) goto invalid; +#endif + } else { + if ( (roundingMode == softfloat_round_max) && sigExtra ) { + increment: + ++sig; + if ( !sig ) goto invalid; + if ( + (sigExtra == UINT64_C( 0x8000000000000000 )) + && (roundingMode == softfloat_round_near_even) + ) { + sig &= ~(uint_fast64_t) 1; + } + } + } + } + if ( sign && sig ) goto invalid; + if ( sigExtra ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) sig |= 1; +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return sig; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + +} + +/**** ended inlining ../../source/s_roundToUI64.c ****/ +/**** start inlining ../../source/s_roundToI32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t + softfloat_roundToI32( + bool sign, uint_fast64_t sig, uint_fast8_t roundingMode, bool exact ) +{ + uint_fast16_t roundIncrement, roundBits; + uint_fast32_t sig32; + union { uint32_t ui; int32_t i; } uZ; + int_fast32_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + roundIncrement = 0x800; + if ( + (roundingMode != softfloat_round_near_maxMag) + && (roundingMode != softfloat_round_near_even) + ) { + roundIncrement = 0; + if ( + sign + ? (roundingMode == softfloat_round_min) +#ifdef SOFTFLOAT_ROUND_ODD + || (roundingMode == softfloat_round_odd) +#endif + : (roundingMode == softfloat_round_max) + ) { + roundIncrement = 0xFFF; + } + } + roundBits = sig & 0xFFF; + sig += roundIncrement; + if ( sig & UINT64_C( 0xFFFFF00000000000 ) ) goto invalid; + sig32 = sig>>12; + if ( + (roundBits == 0x800) && (roundingMode == softfloat_round_near_even) + ) { + sig32 &= ~(uint_fast32_t) 1; + } + uZ.ui = sign ? -sig32 : sig32; + z = uZ.i; + if ( z && ((z < 0) ^ sign) ) goto invalid; + if ( roundBits ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) z |= 1; +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return z; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return sign ? i32_fromNegOverflow : i32_fromPosOverflow; + +} + +/**** ended inlining ../../source/s_roundToI32.c ****/ +/**** start inlining ../../source/s_roundToI64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t + softfloat_roundToI64( + bool sign, + uint_fast64_t sig, + uint_fast64_t sigExtra, + uint_fast8_t roundingMode, + bool exact + ) +{ + union { uint64_t ui; int64_t i; } uZ; + int_fast64_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( + (roundingMode == softfloat_round_near_maxMag) + || (roundingMode == softfloat_round_near_even) + ) { + if ( UINT64_C( 0x8000000000000000 ) <= sigExtra ) goto increment; + } else { + if ( + sigExtra + && (sign + ? (roundingMode == softfloat_round_min) +#ifdef SOFTFLOAT_ROUND_ODD + || (roundingMode == softfloat_round_odd) +#endif + : (roundingMode == softfloat_round_max)) + ) { + increment: + ++sig; + if ( !sig ) goto invalid; + if ( + (sigExtra == UINT64_C( 0x8000000000000000 )) + && (roundingMode == softfloat_round_near_even) + ) { + sig &= ~(uint_fast64_t) 1; + } + } + } + uZ.ui = sign ? -sig : sig; + z = uZ.i; + if ( z && ((z < 0) ^ sign) ) goto invalid; + if ( sigExtra ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) z |= 1; +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return z; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return sign ? i64_fromNegOverflow : i64_fromPosOverflow; + +} + +/**** ended inlining ../../source/s_roundToI64.c ****/ +/**** start inlining ../../source/s_normSubnormalF16Sig.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +struct exp8_sig16 softfloat_normSubnormalF16Sig( uint_fast16_t sig ) +{ + int_fast8_t shiftDist; + struct exp8_sig16 z; + + shiftDist = softfloat_countLeadingZeros16( sig ) - 5; + z.exp = 1 - shiftDist; + z.sig = sig< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t + softfloat_roundPackToF16( bool sign, int_fast16_t exp, uint_fast16_t sig ) +{ + uint_fast8_t roundingMode; + bool roundNearEven; + uint_fast8_t roundIncrement, roundBits; + bool isTiny; + uint_fast16_t uiZ; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + roundingMode = softfloat_roundingMode; + roundNearEven = (roundingMode == softfloat_round_near_even); + roundIncrement = 0x8; + if ( ! roundNearEven && (roundingMode != softfloat_round_near_maxMag) ) { + roundIncrement = + (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + ? 0xF + : 0; + } + roundBits = sig & 0xF; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x1D <= (unsigned int) exp ) { + if ( exp < 0 ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + isTiny = + (softfloat_detectTininess == softfloat_tininess_beforeRounding) + || (exp < -1) || (sig + roundIncrement < 0x8000); + sig = softfloat_shiftRightJam32( sig, -exp ); + exp = 0; + roundBits = sig & 0xF; + if ( isTiny && roundBits ) { + softfloat_raiseFlags( softfloat_flag_underflow ); + } + } else if ( (0x1D < exp) || (0x8000 <= sig + roundIncrement) ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + softfloat_raiseFlags( + softfloat_flag_overflow | softfloat_flag_inexact ); + uiZ = packToF16UI( sign, 0x1F, 0 ) - ! roundIncrement; + goto uiZ; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig = (sig + roundIncrement)>>4; + if ( roundBits ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) { + sig |= 1; + goto packReturn; + } +#endif + } + sig &= ~(uint_fast16_t) (! (roundBits ^ 8) & roundNearEven); + if ( ! sig ) exp = 0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + packReturn: + uiZ = packToF16UI( sign, exp, sig ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_roundPackToF16.c ****/ +/**** start inlining ../../source/s_normRoundPackToF16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +float16_t + softfloat_normRoundPackToF16( bool sign, int_fast16_t exp, uint_fast16_t sig ) +{ + int_fast8_t shiftDist; + union ui16_f16 uZ; + + shiftDist = softfloat_countLeadingZeros16( sig ) - 1; + exp -= shiftDist; + if ( (4 <= shiftDist) && ((unsigned int) exp < 0x1D) ) { + uZ.ui = packToF16UI( sign, sig ? exp : 0, sig<<(shiftDist - 4) ); + return uZ.f; + } else { + return softfloat_roundPackToF16( sign, exp, sig< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t softfloat_addMagsF16( uint_fast16_t uiA, uint_fast16_t uiB ) +{ + int_fast8_t expA; + uint_fast16_t sigA; + int_fast8_t expB; + uint_fast16_t sigB; + int_fast8_t expDiff; + uint_fast16_t uiZ; + bool signZ; + int_fast8_t expZ; + uint_fast16_t sigZ; + uint_fast16_t sigX, sigY; + int_fast8_t shiftDist; + uint_fast32_t sig32Z; + int_fast8_t roundingMode; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = expF16UI( uiA ); + sigA = fracF16UI( uiA ); + expB = expF16UI( uiB ); + sigB = fracF16UI( uiB ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( ! expDiff ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( ! expA ) { + uiZ = uiA + sigB; + goto uiZ; + } + if ( expA == 0x1F ) { + if ( sigA | sigB ) goto propagateNaN; + uiZ = uiA; + goto uiZ; + } + signZ = signF16UI( uiA ); + expZ = expA; + sigZ = 0x0800 + sigA + sigB; + if ( ! (sigZ & 1) && (expZ < 0x1E) ) { + sigZ >>= 1; + goto pack; + } + sigZ <<= 3; + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + signZ = signF16UI( uiA ); + if ( expDiff < 0 ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + if ( expB == 0x1F ) { + if ( sigB ) goto propagateNaN; + uiZ = packToF16UI( signZ, 0x1F, 0 ); + goto uiZ; + } + if ( expDiff <= -13 ) { + uiZ = packToF16UI( signZ, expB, sigB ); + if ( expA | sigA ) goto addEpsilon; + goto uiZ; + } + expZ = expB; + sigX = sigB | 0x0400; + sigY = sigA + (expA ? 0x0400 : sigA); + shiftDist = 19 + expDiff; + } else { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + uiZ = uiA; + if ( expA == 0x1F ) { + if ( sigA ) goto propagateNaN; + goto uiZ; + } + if ( 13 <= expDiff ) { + if ( expB | sigB ) goto addEpsilon; + goto uiZ; + } + expZ = expA; + sigX = sigA | 0x0400; + sigY = sigB + (expB ? 0x0400 : sigB); + shiftDist = 19 - expDiff; + } + sig32Z = + ((uint_fast32_t) sigX<<19) + ((uint_fast32_t) sigY<>16; + if ( sig32Z & 0xFFFF ) { + sigZ |= 1; + } else { + if ( ! (sigZ & 0xF) && (expZ < 0x1E) ) { + sigZ >>= 4; + goto pack; + } + } + } + return softfloat_roundPackToF16( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF16UI( uiA, uiB ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + addEpsilon: + roundingMode = softfloat_roundingMode; + if ( roundingMode != softfloat_round_near_even ) { + if ( + roundingMode + == (signF16UI( uiZ ) ? softfloat_round_min + : softfloat_round_max) + ) { + ++uiZ; + if ( (uint16_t) (uiZ<<1) == 0xF800 ) { + softfloat_raiseFlags( + softfloat_flag_overflow | softfloat_flag_inexact ); + } + } +#ifdef SOFTFLOAT_ROUND_ODD + else if ( roundingMode == softfloat_round_odd ) { + uiZ |= 1; + } +#endif + } + softfloat_exceptionFlags |= softfloat_flag_inexact; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + pack: + uiZ = packToF16UI( signZ, expZ, sigZ ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_addMagsF16.c ****/ +/**** start inlining ../../source/s_subMagsF16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t softfloat_subMagsF16( uint_fast16_t uiA, uint_fast16_t uiB ) +{ + int_fast8_t expA; + uint_fast16_t sigA; + int_fast8_t expB; + uint_fast16_t sigB; + int_fast8_t expDiff; + uint_fast16_t uiZ; + int_fast16_t sigDiff; + bool signZ; + int_fast8_t shiftDist, expZ; + uint_fast16_t sigZ, sigX, sigY; + uint_fast32_t sig32Z; + int_fast8_t roundingMode; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = expF16UI( uiA ); + sigA = fracF16UI( uiA ); + expB = expF16UI( uiB ); + sigB = fracF16UI( uiB ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( ! expDiff ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expA == 0x1F ) { + if ( sigA | sigB ) goto propagateNaN; + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF16UI; + goto uiZ; + } + sigDiff = sigA - sigB; + if ( ! sigDiff ) { + uiZ = + packToF16UI( + (softfloat_roundingMode == softfloat_round_min), 0, 0 ); + goto uiZ; + } + if ( expA ) --expA; + signZ = signF16UI( uiA ); + if ( sigDiff < 0 ) { + signZ = ! signZ; + sigDiff = -sigDiff; + } + shiftDist = softfloat_countLeadingZeros16( sigDiff ) - 5; + expZ = expA - shiftDist; + if ( expZ < 0 ) { + shiftDist = expA; + expZ = 0; + } + sigZ = sigDiff<>16; + if ( sig32Z & 0xFFFF ) { + sigZ |= 1; + } else { + if ( ! (sigZ & 0xF) && ((unsigned int) expZ < 0x1E) ) { + sigZ >>= 4; + goto pack; + } + } + return softfloat_roundPackToF16( signZ, expZ, sigZ ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF16UI( uiA, uiB ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + subEpsilon: + roundingMode = softfloat_roundingMode; + if ( roundingMode != softfloat_round_near_even ) { + if ( + (roundingMode == softfloat_round_minMag) + || (roundingMode + == (signF16UI( uiZ ) ? softfloat_round_max + : softfloat_round_min)) + ) { + --uiZ; + } +#ifdef SOFTFLOAT_ROUND_ODD + else if ( roundingMode == softfloat_round_odd ) { + uiZ = (uiZ - 1) | 1; + } +#endif + } + softfloat_exceptionFlags |= softfloat_flag_inexact; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + pack: + uiZ = packToF16UI( signZ, expZ, sigZ ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_subMagsF16.c ****/ +/**** start inlining ../../source/s_mulAddF16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t + softfloat_mulAddF16( + uint_fast16_t uiA, uint_fast16_t uiB, uint_fast16_t uiC, uint_fast8_t op ) +{ + bool signA; + int_fast8_t expA; + uint_fast16_t sigA; + bool signB; + int_fast8_t expB; + uint_fast16_t sigB; + bool signC; + int_fast8_t expC; + uint_fast16_t sigC; + bool signProd; + uint_fast16_t magBits, uiZ; + struct exp8_sig16 normExpSig; + int_fast8_t expProd; + uint_fast32_t sigProd; + bool signZ; + int_fast8_t expZ; + uint_fast16_t sigZ; + int_fast8_t expDiff; + uint_fast32_t sig32Z, sig32C; + int_fast8_t shiftDist; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + signA = signF16UI( uiA ); + expA = expF16UI( uiA ); + sigA = fracF16UI( uiA ); + signB = signF16UI( uiB ); + expB = expF16UI( uiB ); + sigB = fracF16UI( uiB ); + signC = signF16UI( uiC ) ^ (op == softfloat_mulAdd_subC); + expC = expF16UI( uiC ); + sigC = fracF16UI( uiC ); + signProd = signA ^ signB ^ (op == softfloat_mulAdd_subProd); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x1F ) { + if ( sigA || ((expB == 0x1F) && sigB) ) goto propagateNaN_ABC; + magBits = expB | sigB; + goto infProdArg; + } + if ( expB == 0x1F ) { + if ( sigB ) goto propagateNaN_ABC; + magBits = expA | sigA; + goto infProdArg; + } + if ( expC == 0x1F ) { + if ( sigC ) { + uiZ = 0; + goto propagateNaN_ZC; + } + uiZ = uiC; + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) goto zeroProd; + normExpSig = softfloat_normSubnormalF16Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! sigB ) goto zeroProd; + normExpSig = softfloat_normSubnormalF16Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expProd = expA + expB - 0xE; + sigA = (sigA | 0x0400)<<4; + sigB = (sigB | 0x0400)<<4; + sigProd = (uint_fast32_t) sigA * sigB; + if ( sigProd < 0x20000000 ) { + --expProd; + sigProd <<= 1; + } + signZ = signProd; + if ( ! expC ) { + if ( ! sigC ) { + expZ = expProd - 1; + sigZ = sigProd>>15 | ((sigProd & 0x7FFF) != 0); + goto roundPack; + } + normExpSig = softfloat_normSubnormalF16Sig( sigC ); + expC = normExpSig.exp; + sigC = normExpSig.sig; + } + sigC = (sigC | 0x0400)<<3; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expProd - expC; + if ( signProd == signC ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expDiff <= 0 ) { + expZ = expC; + sigZ = sigC + softfloat_shiftRightJam32( sigProd, 16 - expDiff ); + } else { + expZ = expProd; + sig32Z = + sigProd + + softfloat_shiftRightJam32( + (uint_fast32_t) sigC<<16, expDiff ); + sigZ = sig32Z>>16 | ((sig32Z & 0xFFFF) != 0 ); + } + if ( sigZ < 0x4000 ) { + --expZ; + sigZ <<= 1; + } + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sig32C = (uint_fast32_t) sigC<<16; + if ( expDiff < 0 ) { + signZ = signC; + expZ = expC; + sig32Z = sig32C - softfloat_shiftRightJam32( sigProd, -expDiff ); + } else if ( ! expDiff ) { + expZ = expProd; + sig32Z = sigProd - sig32C; + if ( ! sig32Z ) goto completeCancellation; + if ( sig32Z & 0x80000000 ) { + signZ = ! signZ; + sig32Z = -sig32Z; + } + } else { + expZ = expProd; + sig32Z = sigProd - softfloat_shiftRightJam32( sig32C, expDiff ); + } + shiftDist = softfloat_countLeadingZeros32( sig32Z ) - 1; + expZ -= shiftDist; + shiftDist -= 16; + if ( shiftDist < 0 ) { + sigZ = + sig32Z>>(-shiftDist) + | ((uint32_t) (sig32Z<<(shiftDist & 31)) != 0); + } else { + sigZ = (uint_fast16_t) sig32Z< +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +struct exp16_sig32 softfloat_normSubnormalF32Sig( uint_fast32_t sig ) +{ + int_fast8_t shiftDist; + struct exp16_sig32 z; + + shiftDist = softfloat_countLeadingZeros32( sig ) - 8; + z.exp = 1 - shiftDist; + z.sig = sig< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t + softfloat_roundPackToF32( bool sign, int_fast16_t exp, uint_fast32_t sig ) +{ + uint_fast8_t roundingMode; + bool roundNearEven; + uint_fast8_t roundIncrement, roundBits; + bool isTiny; + uint_fast32_t uiZ; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + roundingMode = softfloat_roundingMode; + roundNearEven = (roundingMode == softfloat_round_near_even); + roundIncrement = 0x40; + if ( ! roundNearEven && (roundingMode != softfloat_round_near_maxMag) ) { + roundIncrement = + (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + ? 0x7F + : 0; + } + roundBits = sig & 0x7F; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0xFD <= (unsigned int) exp ) { + if ( exp < 0 ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + isTiny = + (softfloat_detectTininess == softfloat_tininess_beforeRounding) + || (exp < -1) || (sig + roundIncrement < 0x80000000); + sig = softfloat_shiftRightJam32( sig, -exp ); + exp = 0; + roundBits = sig & 0x7F; + if ( isTiny && roundBits ) { + softfloat_raiseFlags( softfloat_flag_underflow ); + } + } else if ( (0xFD < exp) || (0x80000000 <= sig + roundIncrement) ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + softfloat_raiseFlags( + softfloat_flag_overflow | softfloat_flag_inexact ); + uiZ = packToF32UI( sign, 0xFF, 0 ) - ! roundIncrement; + goto uiZ; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig = (sig + roundIncrement)>>7; + if ( roundBits ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) { + sig |= 1; + goto packReturn; + } +#endif + } + sig &= ~(uint_fast32_t) (! (roundBits ^ 0x40) & roundNearEven); + if ( ! sig ) exp = 0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + packReturn: + uiZ = packToF32UI( sign, exp, sig ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_roundPackToF32.c ****/ +/**** start inlining ../../source/s_normRoundPackToF32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +float32_t + softfloat_normRoundPackToF32( bool sign, int_fast16_t exp, uint_fast32_t sig ) +{ + int_fast8_t shiftDist; + union ui32_f32 uZ; + + shiftDist = softfloat_countLeadingZeros32( sig ) - 1; + exp -= shiftDist; + if ( (7 <= shiftDist) && ((unsigned int) exp < 0xFD) ) { + uZ.ui = packToF32UI( sign, sig ? exp : 0, sig<<(shiftDist - 7) ); + return uZ.f; + } else { + return softfloat_roundPackToF32( sign, exp, sig< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ + +float32_t softfloat_addMagsF32( uint_fast32_t uiA, uint_fast32_t uiB ) +{ + int_fast16_t expA; + uint_fast32_t sigA; + int_fast16_t expB; + uint_fast32_t sigB; + int_fast16_t expDiff; + uint_fast32_t uiZ; + bool signZ; + int_fast16_t expZ; + uint_fast32_t sigZ; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = expF32UI( uiA ); + sigA = fracF32UI( uiA ); + expB = expF32UI( uiB ); + sigB = fracF32UI( uiB ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( ! expDiff ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( ! expA ) { + uiZ = uiA + sigB; + goto uiZ; + } + if ( expA == 0xFF ) { + if ( sigA | sigB ) goto propagateNaN; + uiZ = uiA; + goto uiZ; + } + signZ = signF32UI( uiA ); + expZ = expA; + sigZ = 0x01000000 + sigA + sigB; + if ( ! (sigZ & 1) && (expZ < 0xFE) ) { + uiZ = packToF32UI( signZ, expZ, sigZ>>1 ); + goto uiZ; + } + sigZ <<= 6; + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + signZ = signF32UI( uiA ); + sigA <<= 6; + sigB <<= 6; + if ( expDiff < 0 ) { + if ( expB == 0xFF ) { + if ( sigB ) goto propagateNaN; + uiZ = packToF32UI( signZ, 0xFF, 0 ); + goto uiZ; + } + expZ = expB; + sigA += expA ? 0x20000000 : sigA; + sigA = softfloat_shiftRightJam32( sigA, -expDiff ); + } else { + if ( expA == 0xFF ) { + if ( sigA ) goto propagateNaN; + uiZ = uiA; + goto uiZ; + } + expZ = expA; + sigB += expB ? 0x20000000 : sigB; + sigB = softfloat_shiftRightJam32( sigB, expDiff ); + } + sigZ = 0x20000000 + sigA + sigB; + if ( sigZ < 0x40000000 ) { + --expZ; + sigZ <<= 1; + } + } + return softfloat_roundPackToF32( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF32UI( uiA, uiB ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_addMagsF32.c ****/ +/**** start inlining ../../source/s_subMagsF32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t softfloat_subMagsF32( uint_fast32_t uiA, uint_fast32_t uiB ) +{ + int_fast16_t expA; + uint_fast32_t sigA; + int_fast16_t expB; + uint_fast32_t sigB; + int_fast16_t expDiff; + uint_fast32_t uiZ; + int_fast32_t sigDiff; + bool signZ; + int_fast8_t shiftDist; + int_fast16_t expZ; + uint_fast32_t sigX, sigY; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = expF32UI( uiA ); + sigA = fracF32UI( uiA ); + expB = expF32UI( uiB ); + sigB = fracF32UI( uiB ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( ! expDiff ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expA == 0xFF ) { + if ( sigA | sigB ) goto propagateNaN; + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF32UI; + goto uiZ; + } + sigDiff = sigA - sigB; + if ( ! sigDiff ) { + uiZ = + packToF32UI( + (softfloat_roundingMode == softfloat_round_min), 0, 0 ); + goto uiZ; + } + if ( expA ) --expA; + signZ = signF32UI( uiA ); + if ( sigDiff < 0 ) { + signZ = ! signZ; + sigDiff = -sigDiff; + } + shiftDist = softfloat_countLeadingZeros32( sigDiff ) - 8; + expZ = expA - shiftDist; + if ( expZ < 0 ) { + shiftDist = expA; + expZ = 0; + } + uiZ = packToF32UI( signZ, expZ, sigDiff< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t + softfloat_mulAddF32( + uint_fast32_t uiA, uint_fast32_t uiB, uint_fast32_t uiC, uint_fast8_t op ) +{ + bool signA; + int_fast16_t expA; + uint_fast32_t sigA; + bool signB; + int_fast16_t expB; + uint_fast32_t sigB; + bool signC; + int_fast16_t expC; + uint_fast32_t sigC; + bool signProd; + uint_fast32_t magBits, uiZ; + struct exp16_sig32 normExpSig; + int_fast16_t expProd; + uint_fast64_t sigProd; + bool signZ; + int_fast16_t expZ; + uint_fast32_t sigZ; + int_fast16_t expDiff; + uint_fast64_t sig64Z, sig64C; + int_fast8_t shiftDist; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + signA = signF32UI( uiA ); + expA = expF32UI( uiA ); + sigA = fracF32UI( uiA ); + signB = signF32UI( uiB ); + expB = expF32UI( uiB ); + sigB = fracF32UI( uiB ); + signC = signF32UI( uiC ) ^ (op == softfloat_mulAdd_subC); + expC = expF32UI( uiC ); + sigC = fracF32UI( uiC ); + signProd = signA ^ signB ^ (op == softfloat_mulAdd_subProd); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0xFF ) { + if ( sigA || ((expB == 0xFF) && sigB) ) goto propagateNaN_ABC; + magBits = expB | sigB; + goto infProdArg; + } + if ( expB == 0xFF ) { + if ( sigB ) goto propagateNaN_ABC; + magBits = expA | sigA; + goto infProdArg; + } + if ( expC == 0xFF ) { + if ( sigC ) { + uiZ = 0; + goto propagateNaN_ZC; + } + uiZ = uiC; + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) goto zeroProd; + normExpSig = softfloat_normSubnormalF32Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! sigB ) goto zeroProd; + normExpSig = softfloat_normSubnormalF32Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expProd = expA + expB - 0x7E; + sigA = (sigA | 0x00800000)<<7; + sigB = (sigB | 0x00800000)<<7; + sigProd = (uint_fast64_t) sigA * sigB; + if ( sigProd < UINT64_C( 0x2000000000000000 ) ) { + --expProd; + sigProd <<= 1; + } + signZ = signProd; + if ( ! expC ) { + if ( ! sigC ) { + expZ = expProd - 1; + sigZ = softfloat_shortShiftRightJam64( sigProd, 31 ); + goto roundPack; + } + normExpSig = softfloat_normSubnormalF32Sig( sigC ); + expC = normExpSig.exp; + sigC = normExpSig.sig; + } + sigC = (sigC | 0x00800000)<<6; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expProd - expC; + if ( signProd == signC ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expDiff <= 0 ) { + expZ = expC; + sigZ = sigC + softfloat_shiftRightJam64( sigProd, 32 - expDiff ); + } else { + expZ = expProd; + sig64Z = + sigProd + + softfloat_shiftRightJam64( + (uint_fast64_t) sigC<<32, expDiff ); + sigZ = softfloat_shortShiftRightJam64( sig64Z, 32 ); + } + if ( sigZ < 0x40000000 ) { + --expZ; + sigZ <<= 1; + } + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sig64C = (uint_fast64_t) sigC<<32; + if ( expDiff < 0 ) { + signZ = signC; + expZ = expC; + sig64Z = sig64C - softfloat_shiftRightJam64( sigProd, -expDiff ); + } else if ( ! expDiff ) { + expZ = expProd; + sig64Z = sigProd - sig64C; + if ( ! sig64Z ) goto completeCancellation; + if ( sig64Z & UINT64_C( 0x8000000000000000 ) ) { + signZ = ! signZ; + sig64Z = -sig64Z; + } + } else { + expZ = expProd; + sig64Z = sigProd - softfloat_shiftRightJam64( sig64C, expDiff ); + } + shiftDist = softfloat_countLeadingZeros64( sig64Z ) - 1; + expZ -= shiftDist; + shiftDist -= 32; + if ( shiftDist < 0 ) { + sigZ = softfloat_shortShiftRightJam64( sig64Z, -shiftDist ); + } else { + sigZ = (uint_fast32_t) sig64Z< +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +struct exp16_sig64 softfloat_normSubnormalF64Sig( uint_fast64_t sig ) +{ + int_fast8_t shiftDist; + struct exp16_sig64 z; + + shiftDist = softfloat_countLeadingZeros64( sig ) - 11; + z.exp = 1 - shiftDist; + z.sig = sig< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t + softfloat_roundPackToF64( bool sign, int_fast16_t exp, uint_fast64_t sig ) +{ + uint_fast8_t roundingMode; + bool roundNearEven; + uint_fast16_t roundIncrement, roundBits; + bool isTiny; + uint_fast64_t uiZ; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + roundingMode = softfloat_roundingMode; + roundNearEven = (roundingMode == softfloat_round_near_even); + roundIncrement = 0x200; + if ( ! roundNearEven && (roundingMode != softfloat_round_near_maxMag) ) { + roundIncrement = + (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + ? 0x3FF + : 0; + } + roundBits = sig & 0x3FF; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x7FD <= (uint16_t) exp ) { + if ( exp < 0 ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + isTiny = + (softfloat_detectTininess == softfloat_tininess_beforeRounding) + || (exp < -1) + || (sig + roundIncrement < UINT64_C( 0x8000000000000000 )); + sig = softfloat_shiftRightJam64( sig, -exp ); + exp = 0; + roundBits = sig & 0x3FF; + if ( isTiny && roundBits ) { + softfloat_raiseFlags( softfloat_flag_underflow ); + } + } else if ( + (0x7FD < exp) + || (UINT64_C( 0x8000000000000000 ) <= sig + roundIncrement) + ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + softfloat_raiseFlags( + softfloat_flag_overflow | softfloat_flag_inexact ); + uiZ = packToF64UI( sign, 0x7FF, 0 ) - ! roundIncrement; + goto uiZ; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig = (sig + roundIncrement)>>10; + if ( roundBits ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) { + sig |= 1; + goto packReturn; + } +#endif + } + sig &= ~(uint_fast64_t) (! (roundBits ^ 0x200) & roundNearEven); + if ( ! sig ) exp = 0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + packReturn: + uiZ = packToF64UI( sign, exp, sig ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_roundPackToF64.c ****/ +/**** start inlining ../../source/s_normRoundPackToF64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +float64_t + softfloat_normRoundPackToF64( bool sign, int_fast16_t exp, uint_fast64_t sig ) +{ + int_fast8_t shiftDist; + union ui64_f64 uZ; + + shiftDist = softfloat_countLeadingZeros64( sig ) - 1; + exp -= shiftDist; + if ( (10 <= shiftDist) && ((unsigned int) exp < 0x7FD) ) { + uZ.ui = packToF64UI( sign, sig ? exp : 0, sig<<(shiftDist - 10) ); + return uZ.f; + } else { + return softfloat_roundPackToF64( sign, exp, sig< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ + +float64_t + softfloat_addMagsF64( uint_fast64_t uiA, uint_fast64_t uiB, bool signZ ) +{ + int_fast16_t expA; + uint_fast64_t sigA; + int_fast16_t expB; + uint_fast64_t sigB; + int_fast16_t expDiff; + uint_fast64_t uiZ; + int_fast16_t expZ; + uint_fast64_t sigZ; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = expF64UI( uiA ); + sigA = fracF64UI( uiA ); + expB = expF64UI( uiB ); + sigB = fracF64UI( uiB ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( ! expDiff ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( ! expA ) { + uiZ = uiA + sigB; + goto uiZ; + } + if ( expA == 0x7FF ) { + if ( sigA | sigB ) goto propagateNaN; + uiZ = uiA; + goto uiZ; + } + expZ = expA; + sigZ = UINT64_C( 0x0020000000000000 ) + sigA + sigB; + sigZ <<= 9; + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sigA <<= 9; + sigB <<= 9; + if ( expDiff < 0 ) { + if ( expB == 0x7FF ) { + if ( sigB ) goto propagateNaN; + uiZ = packToF64UI( signZ, 0x7FF, 0 ); + goto uiZ; + } + expZ = expB; + if ( expA ) { + sigA += UINT64_C( 0x2000000000000000 ); + } else { + sigA <<= 1; + } + sigA = softfloat_shiftRightJam64( sigA, -expDiff ); + } else { + if ( expA == 0x7FF ) { + if ( sigA ) goto propagateNaN; + uiZ = uiA; + goto uiZ; + } + expZ = expA; + if ( expB ) { + sigB += UINT64_C( 0x2000000000000000 ); + } else { + sigB <<= 1; + } + sigB = softfloat_shiftRightJam64( sigB, expDiff ); + } + sigZ = UINT64_C( 0x2000000000000000 ) + sigA + sigB; + if ( sigZ < UINT64_C( 0x4000000000000000 ) ) { + --expZ; + sigZ <<= 1; + } + } + return softfloat_roundPackToF64( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF64UI( uiA, uiB ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_addMagsF64.c ****/ +/**** start inlining ../../source/s_subMagsF64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t + softfloat_subMagsF64( uint_fast64_t uiA, uint_fast64_t uiB, bool signZ ) +{ + int_fast16_t expA; + uint_fast64_t sigA; + int_fast16_t expB; + uint_fast64_t sigB; + int_fast16_t expDiff; + uint_fast64_t uiZ; + int_fast64_t sigDiff; + int_fast8_t shiftDist; + int_fast16_t expZ; + uint_fast64_t sigZ; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = expF64UI( uiA ); + sigA = fracF64UI( uiA ); + expB = expF64UI( uiB ); + sigB = fracF64UI( uiB ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( ! expDiff ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expA == 0x7FF ) { + if ( sigA | sigB ) goto propagateNaN; + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF64UI; + goto uiZ; + } + sigDiff = sigA - sigB; + if ( ! sigDiff ) { + uiZ = + packToF64UI( + (softfloat_roundingMode == softfloat_round_min), 0, 0 ); + goto uiZ; + } + if ( expA ) --expA; + if ( sigDiff < 0 ) { + signZ = ! signZ; + sigDiff = -sigDiff; + } + shiftDist = softfloat_countLeadingZeros64( sigDiff ) - 11; + expZ = expA - shiftDist; + if ( expZ < 0 ) { + shiftDist = expA; + expZ = 0; + } + uiZ = packToF64UI( signZ, expZ, sigDiff< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +float64_t + softfloat_mulAddF64( + uint_fast64_t uiA, uint_fast64_t uiB, uint_fast64_t uiC, uint_fast8_t op ) +{ + bool signA; + int_fast16_t expA; + uint_fast64_t sigA; + bool signB; + int_fast16_t expB; + uint_fast64_t sigB; + bool signC; + int_fast16_t expC; + uint_fast64_t sigC; + bool signZ; + uint_fast64_t magBits, uiZ; + struct exp16_sig64 normExpSig; + int_fast16_t expZ; + struct uint128 sig128Z; + uint_fast64_t sigZ; + int_fast16_t expDiff; + struct uint128 sig128C; + int_fast8_t shiftDist; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + signA = signF64UI( uiA ); + expA = expF64UI( uiA ); + sigA = fracF64UI( uiA ); + signB = signF64UI( uiB ); + expB = expF64UI( uiB ); + sigB = fracF64UI( uiB ); + signC = signF64UI( uiC ) ^ (op == softfloat_mulAdd_subC); + expC = expF64UI( uiC ); + sigC = fracF64UI( uiC ); + signZ = signA ^ signB ^ (op == softfloat_mulAdd_subProd); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FF ) { + if ( sigA || ((expB == 0x7FF) && sigB) ) goto propagateNaN_ABC; + magBits = expB | sigB; + goto infProdArg; + } + if ( expB == 0x7FF ) { + if ( sigB ) goto propagateNaN_ABC; + magBits = expA | sigA; + goto infProdArg; + } + if ( expC == 0x7FF ) { + if ( sigC ) { + uiZ = 0; + goto propagateNaN_ZC; + } + uiZ = uiC; + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) goto zeroProd; + normExpSig = softfloat_normSubnormalF64Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! sigB ) goto zeroProd; + normExpSig = softfloat_normSubnormalF64Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x3FE; + sigA = (sigA | UINT64_C( 0x0010000000000000 ))<<10; + sigB = (sigB | UINT64_C( 0x0010000000000000 ))<<10; + sig128Z = softfloat_mul64To128( sigA, sigB ); + if ( sig128Z.v64 < UINT64_C( 0x2000000000000000 ) ) { + --expZ; + sig128Z = + softfloat_add128( + sig128Z.v64, sig128Z.v0, sig128Z.v64, sig128Z.v0 ); + } + if ( ! expC ) { + if ( ! sigC ) { + --expZ; + sigZ = sig128Z.v64<<1 | (sig128Z.v0 != 0); + goto roundPack; + } + normExpSig = softfloat_normSubnormalF64Sig( sigC ); + expC = normExpSig.exp; + sigC = normExpSig.sig; + } + sigC = (sigC | UINT64_C( 0x0010000000000000 ))<<9; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expZ - expC; + if ( expDiff < 0 ) { + expZ = expC; + if ( (signZ == signC) || (expDiff < -1) ) { + sig128Z.v64 = softfloat_shiftRightJam64( sig128Z.v64, -expDiff ); + } else { + sig128Z = + softfloat_shortShiftRightJam128( sig128Z.v64, sig128Z.v0, 1 ); + } + } else if ( expDiff ) { + sig128C = softfloat_shiftRightJam128( sigC, 0, expDiff ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( signZ == signC ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expDiff <= 0 ) { + sigZ = (sigC + sig128Z.v64) | (sig128Z.v0 != 0); + } else { + sig128Z = + softfloat_add128( + sig128Z.v64, sig128Z.v0, sig128C.v64, sig128C.v0 ); + sigZ = sig128Z.v64 | (sig128Z.v0 != 0); + } + if ( sigZ < UINT64_C( 0x4000000000000000 ) ) { + --expZ; + sigZ <<= 1; + } + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expDiff < 0 ) { + signZ = signC; + sig128Z = softfloat_sub128( sigC, 0, sig128Z.v64, sig128Z.v0 ); + } else if ( ! expDiff ) { + sig128Z.v64 = sig128Z.v64 - sigC; + if ( ! (sig128Z.v64 | sig128Z.v0) ) goto completeCancellation; + if ( sig128Z.v64 & UINT64_C( 0x8000000000000000 ) ) { + signZ = ! signZ; + sig128Z = softfloat_sub128( 0, 0, sig128Z.v64, sig128Z.v0 ); + } + } else { + sig128Z = + softfloat_sub128( + sig128Z.v64, sig128Z.v0, sig128C.v64, sig128C.v0 ); + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( ! sig128Z.v64 ) { + expZ -= 64; + sig128Z.v64 = sig128Z.v0; + sig128Z.v0 = 0; + } + shiftDist = softfloat_countLeadingZeros64( sig128Z.v64 ) - 1; + expZ -= shiftDist; + if ( shiftDist < 0 ) { + sigZ = softfloat_shortShiftRightJam64( sig128Z.v64, -shiftDist ); + } else { + sig128Z = + softfloat_shortShiftLeft128( + sig128Z.v64, sig128Z.v0, shiftDist ); + sigZ = sig128Z.v64; + } + sigZ |= (sig128Z.v0 != 0); + } + roundPack: + return softfloat_roundPackToF64( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN_ABC: + uiZ = softfloat_propagateNaNF64UI( uiA, uiB ); + goto propagateNaN_ZC; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infProdArg: + if ( magBits ) { + uiZ = packToF64UI( signZ, 0x7FF, 0 ); + if ( expC != 0x7FF ) goto uiZ; + if ( sigC ) goto propagateNaN_ZC; + if ( signZ == signC ) goto uiZ; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF64UI; + propagateNaN_ZC: + uiZ = softfloat_propagateNaNF64UI( uiZ, uiC ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zeroProd: + uiZ = uiC; + if ( ! (expC | sigC) && (signZ != signC) ) { + completeCancellation: + uiZ = + packToF64UI( + (softfloat_roundingMode == softfloat_round_min), 0, 0 ); + } + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +#else + +float64_t + softfloat_mulAddF64( + uint_fast64_t uiA, uint_fast64_t uiB, uint_fast64_t uiC, uint_fast8_t op ) +{ + bool signA; + int_fast16_t expA; + uint64_t sigA; + bool signB; + int_fast16_t expB; + uint64_t sigB; + bool signC; + int_fast16_t expC; + uint64_t sigC; + bool signZ; + uint64_t magBits, uiZ; + struct exp16_sig64 normExpSig; + int_fast16_t expZ; + uint32_t sig128Z[4]; + uint64_t sigZ; + int_fast16_t shiftDist, expDiff; + uint32_t sig128C[4]; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + signA = signF64UI( uiA ); + expA = expF64UI( uiA ); + sigA = fracF64UI( uiA ); + signB = signF64UI( uiB ); + expB = expF64UI( uiB ); + sigB = fracF64UI( uiB ); + signC = signF64UI( uiC ) ^ (op == softfloat_mulAdd_subC); + expC = expF64UI( uiC ); + sigC = fracF64UI( uiC ); + signZ = signA ^ signB ^ (op == softfloat_mulAdd_subProd); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FF ) { + if ( sigA || ((expB == 0x7FF) && sigB) ) goto propagateNaN_ABC; + magBits = expB | sigB; + goto infProdArg; + } + if ( expB == 0x7FF ) { + if ( sigB ) goto propagateNaN_ABC; + magBits = expA | sigA; + goto infProdArg; + } + if ( expC == 0x7FF ) { + if ( sigC ) { + uiZ = 0; + goto propagateNaN_ZC; + } + uiZ = uiC; + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) goto zeroProd; + normExpSig = softfloat_normSubnormalF64Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! sigB ) goto zeroProd; + normExpSig = softfloat_normSubnormalF64Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x3FE; + sigA = (sigA | UINT64_C( 0x0010000000000000 ))<<10; + sigB = (sigB | UINT64_C( 0x0010000000000000 ))<<11; + softfloat_mul64To128M( sigA, sigB, sig128Z ); + sigZ = + (uint64_t) sig128Z[indexWord( 4, 3 )]<<32 | sig128Z[indexWord( 4, 2 )]; + shiftDist = 0; + if ( ! (sigZ & UINT64_C( 0x4000000000000000 )) ) { + --expZ; + shiftDist = -1; + } + if ( ! expC ) { + if ( ! sigC ) { + if ( shiftDist ) sigZ <<= 1; + goto sigZ; + } + normExpSig = softfloat_normSubnormalF64Sig( sigC ); + expC = normExpSig.exp; + sigC = normExpSig.sig; + } + sigC = (sigC | UINT64_C( 0x0010000000000000 ))<<10; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expZ - expC; + if ( expDiff < 0 ) { + expZ = expC; + if ( (signZ == signC) || (expDiff < -1) ) { + shiftDist -= expDiff; + if ( shiftDist) { + sigZ = softfloat_shiftRightJam64( sigZ, shiftDist ); + } + } else { + if ( ! shiftDist ) { + softfloat_shortShiftRight128M( sig128Z, 1, sig128Z ); + } + } + } else { + if ( shiftDist ) softfloat_add128M( sig128Z, sig128Z, sig128Z ); + if ( ! expDiff ) { + sigZ = + (uint64_t) sig128Z[indexWord( 4, 3 )]<<32 + | sig128Z[indexWord( 4, 2 )]; + } else { + sig128C[indexWord( 4, 3 )] = sigC>>32; + sig128C[indexWord( 4, 2 )] = sigC; + sig128C[indexWord( 4, 1 )] = 0; + sig128C[indexWord( 4, 0 )] = 0; + softfloat_shiftRightJam128M( sig128C, expDiff, sig128C ); + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( signZ == signC ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expDiff <= 0 ) { + sigZ += sigC; + } else { + softfloat_add128M( sig128Z, sig128C, sig128Z ); + sigZ = + (uint64_t) sig128Z[indexWord( 4, 3 )]<<32 + | sig128Z[indexWord( 4, 2 )]; + } + if ( sigZ & UINT64_C( 0x8000000000000000 ) ) { + ++expZ; + sigZ = softfloat_shortShiftRightJam64( sigZ, 1 ); + } + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expDiff < 0 ) { + signZ = signC; + if ( expDiff < -1 ) { + sigZ = sigC - sigZ; + if ( + sig128Z[indexWord( 4, 1 )] || sig128Z[indexWord( 4, 0 )] + ) { + sigZ = (sigZ - 1) | 1; + } + if ( ! (sigZ & UINT64_C( 0x4000000000000000 )) ) { + --expZ; + sigZ <<= 1; + } + goto roundPack; + } else { + sig128C[indexWord( 4, 3 )] = sigC>>32; + sig128C[indexWord( 4, 2 )] = sigC; + sig128C[indexWord( 4, 1 )] = 0; + sig128C[indexWord( 4, 0 )] = 0; + softfloat_sub128M( sig128C, sig128Z, sig128Z ); + } + } else if ( ! expDiff ) { + sigZ -= sigC; + if ( + ! sigZ && ! sig128Z[indexWord( 4, 1 )] + && ! sig128Z[indexWord( 4, 0 )] + ) { + goto completeCancellation; + } + sig128Z[indexWord( 4, 3 )] = sigZ>>32; + sig128Z[indexWord( 4, 2 )] = sigZ; + if ( sigZ & UINT64_C( 0x8000000000000000 ) ) { + signZ = ! signZ; + softfloat_negX128M( sig128Z ); + } + } else { + softfloat_sub128M( sig128Z, sig128C, sig128Z ); + if ( 1 < expDiff ) { + sigZ = + (uint64_t) sig128Z[indexWord( 4, 3 )]<<32 + | sig128Z[indexWord( 4, 2 )]; + if ( ! (sigZ & UINT64_C( 0x4000000000000000 )) ) { + --expZ; + sigZ <<= 1; + } + goto sigZ; + } + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + shiftDist = 0; + sigZ = + (uint64_t) sig128Z[indexWord( 4, 3 )]<<32 + | sig128Z[indexWord( 4, 2 )]; + if ( ! sigZ ) { + shiftDist = 64; + sigZ = + (uint64_t) sig128Z[indexWord( 4, 1 )]<<32 + | sig128Z[indexWord( 4, 0 )]; + } + shiftDist += softfloat_countLeadingZeros64( sigZ ) - 1; + if ( shiftDist ) { + expZ -= shiftDist; + softfloat_shiftLeft128M( sig128Z, shiftDist, sig128Z ); + sigZ = + (uint64_t) sig128Z[indexWord( 4, 3 )]<<32 + | sig128Z[indexWord( 4, 2 )]; + } + } + sigZ: + if ( sig128Z[indexWord( 4, 1 )] || sig128Z[indexWord( 4, 0 )] ) sigZ |= 1; + roundPack: + return softfloat_roundPackToF64( signZ, expZ - 1, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN_ABC: + uiZ = softfloat_propagateNaNF64UI( uiA, uiB ); + goto propagateNaN_ZC; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infProdArg: + if ( magBits ) { + uiZ = packToF64UI( signZ, 0x7FF, 0 ); + if ( expC != 0x7FF ) goto uiZ; + if ( sigC ) goto propagateNaN_ZC; + if ( signZ == signC ) goto uiZ; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF64UI; + propagateNaN_ZC: + uiZ = softfloat_propagateNaNF64UI( uiZ, uiC ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zeroProd: + uiZ = uiC; + if ( ! (expC | sigC) && (signZ != signC) ) { + completeCancellation: + uiZ = + packToF64UI( + (softfloat_roundingMode == softfloat_round_min), 0, 0 ); + } + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +#endif + +/**** ended inlining ../../source/s_mulAddF64.c ****/ +/**** start inlining ../../source/s_normSubnormalExtF80Sig.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +struct exp32_sig64 softfloat_normSubnormalExtF80Sig( uint_fast64_t sig ) +{ + int_fast8_t shiftDist; + struct exp32_sig64 z; + + shiftDist = softfloat_countLeadingZeros64( sig ); + z.exp = -shiftDist; + z.sig = sig< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t + softfloat_roundPackToExtF80( + bool sign, + int_fast32_t exp, + uint_fast64_t sig, + uint_fast64_t sigExtra, + uint_fast8_t roundingPrecision + ) +{ + uint_fast8_t roundingMode; + bool roundNearEven; + uint_fast64_t roundIncrement, roundMask, roundBits; + bool isTiny, doIncrement; + struct uint64_extra sig64Extra; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + roundingMode = softfloat_roundingMode; + roundNearEven = (roundingMode == softfloat_round_near_even); + if ( roundingPrecision == 80 ) goto precision80; + if ( roundingPrecision == 64 ) { + roundIncrement = UINT64_C( 0x0000000000000400 ); + roundMask = UINT64_C( 0x00000000000007FF ); + } else if ( roundingPrecision == 32 ) { + roundIncrement = UINT64_C( 0x0000008000000000 ); + roundMask = UINT64_C( 0x000000FFFFFFFFFF ); + } else { + goto precision80; + } + sig |= (sigExtra != 0); + if ( ! roundNearEven && (roundingMode != softfloat_round_near_maxMag) ) { + roundIncrement = + (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + ? roundMask + : 0; + } + roundBits = sig & roundMask; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x7FFD <= (uint32_t) (exp - 1) ) { + if ( exp <= 0 ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + isTiny = + (softfloat_detectTininess + == softfloat_tininess_beforeRounding) + || (exp < 0) + || (sig <= (uint64_t) (sig + roundIncrement)); + sig = softfloat_shiftRightJam64( sig, 1 - exp ); + roundBits = sig & roundMask; + if ( roundBits ) { + if ( isTiny ) softfloat_raiseFlags( softfloat_flag_underflow ); + softfloat_exceptionFlags |= softfloat_flag_inexact; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) { + sig |= roundMask + 1; + } +#endif + } + sig += roundIncrement; + exp = ((sig & UINT64_C( 0x8000000000000000 )) != 0); + roundIncrement = roundMask + 1; + if ( roundNearEven && (roundBits<<1 == roundIncrement) ) { + roundMask |= roundIncrement; + } + sig &= ~roundMask; + goto packReturn; + } + if ( + (0x7FFE < exp) + || ((exp == 0x7FFE) && ((uint64_t) (sig + roundIncrement) < sig)) + ) { + goto overflow; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( roundBits ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) { + sig = (sig & ~roundMask) | (roundMask + 1); + goto packReturn; + } +#endif + } + sig = (uint64_t) (sig + roundIncrement); + if ( sig < roundIncrement ) { + ++exp; + sig = UINT64_C( 0x8000000000000000 ); + } + roundIncrement = roundMask + 1; + if ( roundNearEven && (roundBits<<1 == roundIncrement) ) { + roundMask |= roundIncrement; + } + sig &= ~roundMask; + goto packReturn; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + precision80: + doIncrement = (UINT64_C( 0x8000000000000000 ) <= sigExtra); + if ( ! roundNearEven && (roundingMode != softfloat_round_near_maxMag) ) { + doIncrement = + (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + && sigExtra; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x7FFD <= (uint32_t) (exp - 1) ) { + if ( exp <= 0 ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + isTiny = + (softfloat_detectTininess + == softfloat_tininess_beforeRounding) + || (exp < 0) + || ! doIncrement + || (sig < UINT64_C( 0xFFFFFFFFFFFFFFFF )); + sig64Extra = + softfloat_shiftRightJam64Extra( sig, sigExtra, 1 - exp ); + exp = 0; + sig = sig64Extra.v; + sigExtra = sig64Extra.extra; + if ( sigExtra ) { + if ( isTiny ) softfloat_raiseFlags( softfloat_flag_underflow ); + softfloat_exceptionFlags |= softfloat_flag_inexact; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) { + sig |= 1; + goto packReturn; + } +#endif + } + doIncrement = (UINT64_C( 0x8000000000000000 ) <= sigExtra); + if ( + ! roundNearEven + && (roundingMode != softfloat_round_near_maxMag) + ) { + doIncrement = + (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + && sigExtra; + } + if ( doIncrement ) { + ++sig; + sig &= + ~(uint_fast64_t) + (! (sigExtra & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + & roundNearEven); + exp = ((sig & UINT64_C( 0x8000000000000000 )) != 0); + } + goto packReturn; + } + if ( + (0x7FFE < exp) + || ((exp == 0x7FFE) && (sig == UINT64_C( 0xFFFFFFFFFFFFFFFF )) + && doIncrement) + ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + roundMask = 0; + overflow: + softfloat_raiseFlags( + softfloat_flag_overflow | softfloat_flag_inexact ); + if ( + roundNearEven + || (roundingMode == softfloat_round_near_maxMag) + || (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + ) { + exp = 0x7FFF; + sig = UINT64_C( 0x8000000000000000 ); + } else { + exp = 0x7FFE; + sig = ~roundMask; + } + goto packReturn; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( sigExtra ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) { + sig |= 1; + goto packReturn; + } +#endif + } + if ( doIncrement ) { + ++sig; + if ( ! sig ) { + ++exp; + sig = UINT64_C( 0x8000000000000000 ); + } else { + sig &= + ~(uint_fast64_t) + (! (sigExtra & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + & roundNearEven); + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + packReturn: + uZ.s.signExp = packToExtF80UI64( sign, exp ); + uZ.s.signif = sig; + return uZ.f; + +} + +/**** ended inlining ../../source/s_roundPackToExtF80.c ****/ +/**** start inlining ../../source/s_normRoundPackToExtF80.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +extFloat80_t + softfloat_normRoundPackToExtF80( + bool sign, + int_fast32_t exp, + uint_fast64_t sig, + uint_fast64_t sigExtra, + uint_fast8_t roundingPrecision + ) +{ + int_fast8_t shiftDist; + struct uint128 sig128; + + if ( ! sig ) { + exp -= 64; + sig = sigExtra; + sigExtra = 0; + } + shiftDist = softfloat_countLeadingZeros64( sig ); + exp -= shiftDist; + if ( shiftDist ) { + sig128 = softfloat_shortShiftLeft128( sig, sigExtra, shiftDist ); + sig = sig128.v64; + sigExtra = sig128.v0; + } + return + softfloat_roundPackToExtF80( + sign, exp, sig, sigExtra, roundingPrecision ); + +} + +/**** ended inlining ../../source/s_normRoundPackToExtF80.c ****/ +/**** start inlining ../../source/s_addMagsExtF80.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t + softfloat_addMagsExtF80( + uint_fast16_t uiA64, + uint_fast64_t uiA0, + uint_fast16_t uiB64, + uint_fast64_t uiB0, + bool signZ + ) +{ + int_fast32_t expA; + uint_fast64_t sigA; + int_fast32_t expB; + uint_fast64_t sigB; + int_fast32_t expDiff; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0, sigZ, sigZExtra; + struct exp32_sig64 normExpSig; + int_fast32_t expZ; + struct uint64_extra sig64Extra; + struct uint128 uiZ; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = expExtF80UI64( uiA64 ); + sigA = uiA0; + expB = expExtF80UI64( uiB64 ); + sigB = uiB0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( ! expDiff ) { + if ( expA == 0x7FFF ) { + if ( (sigA | sigB) & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + goto propagateNaN; + } + uiZ64 = uiA64; + uiZ0 = uiA0; + goto uiZ; + } + sigZ = sigA + sigB; + sigZExtra = 0; + if ( ! expA ) { + normExpSig = softfloat_normSubnormalExtF80Sig( sigZ ); + expZ = normExpSig.exp + 1; + sigZ = normExpSig.sig; + goto roundAndPack; + } + expZ = expA; + goto shiftRight1; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expDiff < 0 ) { + if ( expB == 0x7FFF ) { + if ( sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN; + uiZ64 = packToExtF80UI64( signZ, 0x7FFF ); + uiZ0 = uiB0; + goto uiZ; + } + expZ = expB; + if ( ! expA ) { + ++expDiff; + sigZExtra = 0; + if ( ! expDiff ) goto newlyAligned; + } + sig64Extra = softfloat_shiftRightJam64Extra( sigA, 0, -expDiff ); + sigA = sig64Extra.v; + sigZExtra = sig64Extra.extra; + } else { + if ( expA == 0x7FFF ) { + if ( sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN; + uiZ64 = uiA64; + uiZ0 = uiA0; + goto uiZ; + } + expZ = expA; + if ( ! expB ) { + --expDiff; + sigZExtra = 0; + if ( ! expDiff ) goto newlyAligned; + } + sig64Extra = softfloat_shiftRightJam64Extra( sigB, 0, expDiff ); + sigB = sig64Extra.v; + sigZExtra = sig64Extra.extra; + } + newlyAligned: + sigZ = sigA + sigB; + if ( sigZ & UINT64_C( 0x8000000000000000 ) ) goto roundAndPack; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftRight1: + sig64Extra = softfloat_shortShiftRightJam64Extra( sigZ, sigZExtra, 1 ); + sigZ = sig64Extra.v | UINT64_C( 0x8000000000000000 ); + sigZExtra = sig64Extra.extra; + ++expZ; + roundAndPack: + return + softfloat_roundPackToExtF80( + signZ, expZ, sigZ, sigZExtra, extF80_roundingPrecision ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNExtF80UI( uiA64, uiA0, uiB64, uiB0 ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/s_addMagsExtF80.c ****/ +/**** start inlining ../../source/s_subMagsExtF80.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t + softfloat_subMagsExtF80( + uint_fast16_t uiA64, + uint_fast64_t uiA0, + uint_fast16_t uiB64, + uint_fast64_t uiB0, + bool signZ + ) +{ + int_fast32_t expA; + uint_fast64_t sigA; + int_fast32_t expB; + uint_fast64_t sigB; + int_fast32_t expDiff; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0; + int_fast32_t expZ; + uint_fast64_t sigExtra; + struct uint128 sig128, uiZ; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = expExtF80UI64( uiA64 ); + sigA = uiA0; + expB = expExtF80UI64( uiB64 ); + sigB = uiB0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( 0 < expDiff ) goto expABigger; + if ( expDiff < 0 ) goto expBBigger; + if ( expA == 0x7FFF ) { + if ( (sigA | sigB) & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + goto propagateNaN; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ64 = defaultNaNExtF80UI64; + uiZ0 = defaultNaNExtF80UI0; + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA; + if ( ! expZ ) expZ = 1; + sigExtra = 0; + if ( sigB < sigA ) goto aBigger; + if ( sigA < sigB ) goto bBigger; + uiZ64 = + packToExtF80UI64( (softfloat_roundingMode == softfloat_round_min), 0 ); + uiZ0 = 0; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expBBigger: + if ( expB == 0x7FFF ) { + if ( sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN; + uiZ64 = packToExtF80UI64( signZ ^ 1, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + goto uiZ; + } + if ( ! expA ) { + ++expDiff; + sigExtra = 0; + if ( ! expDiff ) goto newlyAlignedBBigger; + } + sig128 = softfloat_shiftRightJam128( sigA, 0, -expDiff ); + sigA = sig128.v64; + sigExtra = sig128.v0; + newlyAlignedBBigger: + expZ = expB; + bBigger: + signZ = ! signZ; + sig128 = softfloat_sub128( sigB, 0, sigA, sigExtra ); + goto normRoundPack; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expABigger: + if ( expA == 0x7FFF ) { + if ( sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN; + uiZ64 = uiA64; + uiZ0 = uiA0; + goto uiZ; + } + if ( ! expB ) { + --expDiff; + sigExtra = 0; + if ( ! expDiff ) goto newlyAlignedABigger; + } + sig128 = softfloat_shiftRightJam128( sigB, 0, expDiff ); + sigB = sig128.v64; + sigExtra = sig128.v0; + newlyAlignedABigger: + expZ = expA; + aBigger: + sig128 = softfloat_sub128( sigA, 0, sigB, sigExtra ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + normRoundPack: + return + softfloat_normRoundPackToExtF80( + signZ, expZ, sig128.v64, sig128.v0, extF80_roundingPrecision ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNExtF80UI( uiA64, uiA0, uiB64, uiB0 ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/s_subMagsExtF80.c ****/ +/**** start inlining ../../source/s_normSubnormalF128Sig.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +struct exp32_sig128 + softfloat_normSubnormalF128Sig( uint_fast64_t sig64, uint_fast64_t sig0 ) +{ + int_fast8_t shiftDist; + struct exp32_sig128 z; + + if ( ! sig64 ) { + shiftDist = softfloat_countLeadingZeros64( sig0 ) - 15; + z.exp = -63 - shiftDist; + if ( shiftDist < 0 ) { + z.sig.v64 = sig0>>-shiftDist; + z.sig.v0 = sig0<<(shiftDist & 63); + } else { + z.sig.v64 = sig0< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t + softfloat_roundPackToF128( + bool sign, + int_fast32_t exp, + uint_fast64_t sig64, + uint_fast64_t sig0, + uint_fast64_t sigExtra + ) +{ + uint_fast8_t roundingMode; + bool roundNearEven, doIncrement, isTiny; + struct uint128_extra sig128Extra; + uint_fast64_t uiZ64, uiZ0; + struct uint128 sig128; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + roundingMode = softfloat_roundingMode; + roundNearEven = (roundingMode == softfloat_round_near_even); + doIncrement = (UINT64_C( 0x8000000000000000 ) <= sigExtra); + if ( ! roundNearEven && (roundingMode != softfloat_round_near_maxMag) ) { + doIncrement = + (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + && sigExtra; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x7FFD <= (uint32_t) exp ) { + if ( exp < 0 ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + isTiny = + (softfloat_detectTininess + == softfloat_tininess_beforeRounding) + || (exp < -1) + || ! doIncrement + || softfloat_lt128( + sig64, + sig0, + UINT64_C( 0x0001FFFFFFFFFFFF ), + UINT64_C( 0xFFFFFFFFFFFFFFFF ) + ); + sig128Extra = + softfloat_shiftRightJam128Extra( sig64, sig0, sigExtra, -exp ); + sig64 = sig128Extra.v.v64; + sig0 = sig128Extra.v.v0; + sigExtra = sig128Extra.extra; + exp = 0; + if ( isTiny && sigExtra ) { + softfloat_raiseFlags( softfloat_flag_underflow ); + } + doIncrement = (UINT64_C( 0x8000000000000000 ) <= sigExtra); + if ( + ! roundNearEven + && (roundingMode != softfloat_round_near_maxMag) + ) { + doIncrement = + (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + && sigExtra; + } + } else if ( + (0x7FFD < exp) + || ((exp == 0x7FFD) + && softfloat_eq128( + sig64, + sig0, + UINT64_C( 0x0001FFFFFFFFFFFF ), + UINT64_C( 0xFFFFFFFFFFFFFFFF ) + ) + && doIncrement) + ) { + /*---------------------------------------------------------------- + *----------------------------------------------------------------*/ + softfloat_raiseFlags( + softfloat_flag_overflow | softfloat_flag_inexact ); + if ( + roundNearEven + || (roundingMode == softfloat_round_near_maxMag) + || (roundingMode + == (sign ? softfloat_round_min : softfloat_round_max)) + ) { + uiZ64 = packToF128UI64( sign, 0x7FFF, 0 ); + uiZ0 = 0; + } else { + uiZ64 = + packToF128UI64( + sign, 0x7FFE, UINT64_C( 0x0000FFFFFFFFFFFF ) ); + uiZ0 = UINT64_C( 0xFFFFFFFFFFFFFFFF ); + } + goto uiZ; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( sigExtra ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) { + sig0 |= 1; + goto packReturn; + } +#endif + } + if ( doIncrement ) { + sig128 = softfloat_add128( sig64, sig0, 0, 1 ); + sig64 = sig128.v64; + sig0 = + sig128.v0 + & ~(uint64_t) + (! (sigExtra & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + & roundNearEven); + } else { + if ( ! (sig64 | sig0) ) exp = 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + packReturn: + uiZ64 = packToF128UI64( sign, exp, sig64 ); + uiZ0 = sig0; + uiZ: + uZ.ui.v64 = uiZ64; + uZ.ui.v0 = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/s_roundPackToF128.c ****/ +/**** start inlining ../../source/s_normRoundPackToF128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ + +float128_t + softfloat_normRoundPackToF128( + bool sign, int_fast32_t exp, uint_fast64_t sig64, uint_fast64_t sig0 ) +{ + int_fast8_t shiftDist; + struct uint128 sig128; + union ui128_f128 uZ; + uint_fast64_t sigExtra; + struct uint128_extra sig128Extra; + + if ( ! sig64 ) { + exp -= 64; + sig64 = sig0; + sig0 = 0; + } + shiftDist = softfloat_countLeadingZeros64( sig64 ) - 15; + exp -= shiftDist; + if ( 0 <= shiftDist ) { + if ( shiftDist ) { + sig128 = softfloat_shortShiftLeft128( sig64, sig0, shiftDist ); + sig64 = sig128.v64; + sig0 = sig128.v0; + } + if ( (uint32_t) exp < 0x7FFD ) { + uZ.ui.v64 = packToF128UI64( sign, sig64 | sig0 ? exp : 0, sig64 ); + uZ.ui.v0 = sig0; + return uZ.f; + } + sigExtra = 0; + } else { + sig128Extra = + softfloat_shortShiftRightJam128Extra( sig64, sig0, 0, -shiftDist ); + sig64 = sig128Extra.v.v64; + sig0 = sig128Extra.v.v0; + sigExtra = sig128Extra.extra; + } + return softfloat_roundPackToF128( sign, exp, sig64, sig0, sigExtra ); + +} + +/**** ended inlining ../../source/s_normRoundPackToF128.c ****/ +/**** start inlining ../../source/s_addMagsF128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ + +float128_t + softfloat_addMagsF128( + uint_fast64_t uiA64, + uint_fast64_t uiA0, + uint_fast64_t uiB64, + uint_fast64_t uiB0, + bool signZ + ) +{ + int_fast32_t expA; + struct uint128 sigA; + int_fast32_t expB; + struct uint128 sigB; + int_fast32_t expDiff; + struct uint128 uiZ, sigZ; + int_fast32_t expZ; + uint_fast64_t sigZExtra; + struct uint128_extra sig128Extra; + union ui128_f128 uZ; + + expA = expF128UI64( uiA64 ); + sigA.v64 = fracF128UI64( uiA64 ); + sigA.v0 = uiA0; + expB = expF128UI64( uiB64 ); + sigB.v64 = fracF128UI64( uiB64 ); + sigB.v0 = uiB0; + expDiff = expA - expB; + if ( ! expDiff ) { + if ( expA == 0x7FFF ) { + if ( sigA.v64 | sigA.v0 | sigB.v64 | sigB.v0 ) goto propagateNaN; + uiZ.v64 = uiA64; + uiZ.v0 = uiA0; + goto uiZ; + } + sigZ = softfloat_add128( sigA.v64, sigA.v0, sigB.v64, sigB.v0 ); + if ( ! expA ) { + uiZ.v64 = packToF128UI64( signZ, 0, sigZ.v64 ); + uiZ.v0 = sigZ.v0; + goto uiZ; + } + expZ = expA; + sigZ.v64 |= UINT64_C( 0x0002000000000000 ); + sigZExtra = 0; + goto shiftRight1; + } + if ( expDiff < 0 ) { + if ( expB == 0x7FFF ) { + if ( sigB.v64 | sigB.v0 ) goto propagateNaN; + uiZ.v64 = packToF128UI64( signZ, 0x7FFF, 0 ); + uiZ.v0 = 0; + goto uiZ; + } + expZ = expB; + if ( expA ) { + sigA.v64 |= UINT64_C( 0x0001000000000000 ); + } else { + ++expDiff; + sigZExtra = 0; + if ( ! expDiff ) goto newlyAligned; + } + sig128Extra = + softfloat_shiftRightJam128Extra( sigA.v64, sigA.v0, 0, -expDiff ); + sigA = sig128Extra.v; + sigZExtra = sig128Extra.extra; + } else { + if ( expA == 0x7FFF ) { + if ( sigA.v64 | sigA.v0 ) goto propagateNaN; + uiZ.v64 = uiA64; + uiZ.v0 = uiA0; + goto uiZ; + } + expZ = expA; + if ( expB ) { + sigB.v64 |= UINT64_C( 0x0001000000000000 ); + } else { + --expDiff; + sigZExtra = 0; + if ( ! expDiff ) goto newlyAligned; + } + sig128Extra = + softfloat_shiftRightJam128Extra( sigB.v64, sigB.v0, 0, expDiff ); + sigB = sig128Extra.v; + sigZExtra = sig128Extra.extra; + } + newlyAligned: + sigZ = + softfloat_add128( + sigA.v64 | UINT64_C( 0x0001000000000000 ), + sigA.v0, + sigB.v64, + sigB.v0 + ); + --expZ; + if ( sigZ.v64 < UINT64_C( 0x0002000000000000 ) ) goto roundAndPack; + ++expZ; + shiftRight1: + sig128Extra = + softfloat_shortShiftRightJam128Extra( + sigZ.v64, sigZ.v0, sigZExtra, 1 ); + sigZ = sig128Extra.v; + sigZExtra = sig128Extra.extra; + roundAndPack: + return + softfloat_roundPackToF128( signZ, expZ, sigZ.v64, sigZ.v0, sigZExtra ); + propagateNaN: + uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, uiB64, uiB0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_addMagsF128.c ****/ +/**** start inlining ../../source/s_subMagsF128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t + softfloat_subMagsF128( + uint_fast64_t uiA64, + uint_fast64_t uiA0, + uint_fast64_t uiB64, + uint_fast64_t uiB0, + bool signZ + ) +{ + int_fast32_t expA; + struct uint128 sigA; + int_fast32_t expB; + struct uint128 sigB, sigZ; + int_fast32_t expDiff, expZ; + struct uint128 uiZ; + union ui128_f128 uZ; + + expA = expF128UI64( uiA64 ); + sigA.v64 = fracF128UI64( uiA64 ); + sigA.v0 = uiA0; + expB = expF128UI64( uiB64 ); + sigB.v64 = fracF128UI64( uiB64 ); + sigB.v0 = uiB0; + sigA = softfloat_shortShiftLeft128( sigA.v64, sigA.v0, 4 ); + sigB = softfloat_shortShiftLeft128( sigB.v64, sigB.v0, 4 ); + expDiff = expA - expB; + if ( 0 < expDiff ) goto expABigger; + if ( expDiff < 0 ) goto expBBigger; + if ( expA == 0x7FFF ) { + if ( sigA.v64 | sigA.v0 | sigB.v64 | sigB.v0 ) goto propagateNaN; + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ.v64 = defaultNaNF128UI64; + uiZ.v0 = defaultNaNF128UI0; + goto uiZ; + } + expZ = expA; + if ( ! expZ ) expZ = 1; + if ( sigB.v64 < sigA.v64 ) goto aBigger; + if ( sigA.v64 < sigB.v64 ) goto bBigger; + if ( sigB.v0 < sigA.v0 ) goto aBigger; + if ( sigA.v0 < sigB.v0 ) goto bBigger; + uiZ.v64 = + packToF128UI64( + (softfloat_roundingMode == softfloat_round_min), 0, 0 ); + uiZ.v0 = 0; + goto uiZ; + expBBigger: + if ( expB == 0x7FFF ) { + if ( sigB.v64 | sigB.v0 ) goto propagateNaN; + uiZ.v64 = packToF128UI64( signZ ^ 1, 0x7FFF, 0 ); + uiZ.v0 = 0; + goto uiZ; + } + if ( expA ) { + sigA.v64 |= UINT64_C( 0x0010000000000000 ); + } else { + ++expDiff; + if ( ! expDiff ) goto newlyAlignedBBigger; + } + sigA = softfloat_shiftRightJam128( sigA.v64, sigA.v0, -expDiff ); + newlyAlignedBBigger: + expZ = expB; + sigB.v64 |= UINT64_C( 0x0010000000000000 ); + bBigger: + signZ = ! signZ; + sigZ = softfloat_sub128( sigB.v64, sigB.v0, sigA.v64, sigA.v0 ); + goto normRoundPack; + expABigger: + if ( expA == 0x7FFF ) { + if ( sigA.v64 | sigA.v0 ) goto propagateNaN; + uiZ.v64 = uiA64; + uiZ.v0 = uiA0; + goto uiZ; + } + if ( expB ) { + sigB.v64 |= UINT64_C( 0x0010000000000000 ); + } else { + --expDiff; + if ( ! expDiff ) goto newlyAlignedABigger; + } + sigB = softfloat_shiftRightJam128( sigB.v64, sigB.v0, expDiff ); + newlyAlignedABigger: + expZ = expA; + sigA.v64 |= UINT64_C( 0x0010000000000000 ); + aBigger: + sigZ = softfloat_sub128( sigA.v64, sigA.v0, sigB.v64, sigB.v0 ); + normRoundPack: + return softfloat_normRoundPackToF128( signZ, expZ - 5, sigZ.v64, sigZ.v0 ); + propagateNaN: + uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, uiB64, uiB0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_subMagsF128.c ****/ +/**** start inlining ../../source/s_mulAddF128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t + softfloat_mulAddF128( + uint_fast64_t uiA64, + uint_fast64_t uiA0, + uint_fast64_t uiB64, + uint_fast64_t uiB0, + uint_fast64_t uiC64, + uint_fast64_t uiC0, + uint_fast8_t op + ) +{ + bool signA; + int_fast32_t expA; + struct uint128 sigA; + bool signB; + int_fast32_t expB; + struct uint128 sigB; + bool signC; + int_fast32_t expC; + struct uint128 sigC; + bool signZ; + uint_fast64_t magBits; + struct uint128 uiZ; + struct exp32_sig128 normExpSig; + int_fast32_t expZ; + uint64_t sig256Z[4]; + struct uint128 sigZ; + int_fast32_t shiftDist, expDiff; + struct uint128 x128; + uint64_t sig256C[4]; + static uint64_t zero256[4] = INIT_UINTM4( 0, 0, 0, 0 ); + uint_fast64_t sigZExtra, sig256Z0; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + signA = signF128UI64( uiA64 ); + expA = expF128UI64( uiA64 ); + sigA.v64 = fracF128UI64( uiA64 ); + sigA.v0 = uiA0; + signB = signF128UI64( uiB64 ); + expB = expF128UI64( uiB64 ); + sigB.v64 = fracF128UI64( uiB64 ); + sigB.v0 = uiB0; + signC = signF128UI64( uiC64 ) ^ (op == softfloat_mulAdd_subC); + expC = expF128UI64( uiC64 ); + sigC.v64 = fracF128UI64( uiC64 ); + sigC.v0 = uiC0; + signZ = signA ^ signB ^ (op == softfloat_mulAdd_subProd); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( + (sigA.v64 | sigA.v0) || ((expB == 0x7FFF) && (sigB.v64 | sigB.v0)) + ) { + goto propagateNaN_ABC; + } + magBits = expB | sigB.v64 | sigB.v0; + goto infProdArg; + } + if ( expB == 0x7FFF ) { + if ( sigB.v64 | sigB.v0 ) goto propagateNaN_ABC; + magBits = expA | sigA.v64 | sigA.v0; + goto infProdArg; + } + if ( expC == 0x7FFF ) { + if ( sigC.v64 | sigC.v0 ) { + uiZ.v64 = 0; + uiZ.v0 = 0; + goto propagateNaN_ZC; + } + uiZ.v64 = uiC64; + uiZ.v0 = uiC0; + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! (sigA.v64 | sigA.v0) ) goto zeroProd; + normExpSig = softfloat_normSubnormalF128Sig( sigA.v64, sigA.v0 ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! (sigB.v64 | sigB.v0) ) goto zeroProd; + normExpSig = softfloat_normSubnormalF128Sig( sigB.v64, sigB.v0 ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x3FFE; + sigA.v64 |= UINT64_C( 0x0001000000000000 ); + sigB.v64 |= UINT64_C( 0x0001000000000000 ); + sigA = softfloat_shortShiftLeft128( sigA.v64, sigA.v0, 8 ); + sigB = softfloat_shortShiftLeft128( sigB.v64, sigB.v0, 15 ); + softfloat_mul128To256M( sigA.v64, sigA.v0, sigB.v64, sigB.v0, sig256Z ); + sigZ.v64 = sig256Z[indexWord( 4, 3 )]; + sigZ.v0 = sig256Z[indexWord( 4, 2 )]; + shiftDist = 0; + if ( ! (sigZ.v64 & UINT64_C( 0x0100000000000000 )) ) { + --expZ; + shiftDist = -1; + } + if ( ! expC ) { + if ( ! (sigC.v64 | sigC.v0) ) { + shiftDist += 8; + goto sigZ; + } + normExpSig = softfloat_normSubnormalF128Sig( sigC.v64, sigC.v0 ); + expC = normExpSig.exp; + sigC = normExpSig.sig; + } + sigC.v64 |= UINT64_C( 0x0001000000000000 ); + sigC = softfloat_shortShiftLeft128( sigC.v64, sigC.v0, 8 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expZ - expC; + if ( expDiff < 0 ) { + expZ = expC; + if ( (signZ == signC) || (expDiff < -1) ) { + shiftDist -= expDiff; + if ( shiftDist ) { + sigZ = + softfloat_shiftRightJam128( sigZ.v64, sigZ.v0, shiftDist ); + } + } else { + if ( ! shiftDist ) { + x128 = + softfloat_shortShiftRight128( + sig256Z[indexWord( 4, 1 )], sig256Z[indexWord( 4, 0 )], + 1 + ); + sig256Z[indexWord( 4, 1 )] = (sigZ.v0<<63) | x128.v64; + sig256Z[indexWord( 4, 0 )] = x128.v0; + sigZ = softfloat_shortShiftRight128( sigZ.v64, sigZ.v0, 1 ); + sig256Z[indexWord( 4, 3 )] = sigZ.v64; + sig256Z[indexWord( 4, 2 )] = sigZ.v0; + } + } + } else { + if ( shiftDist ) softfloat_add256M( sig256Z, sig256Z, sig256Z ); + if ( ! expDiff ) { + sigZ.v64 = sig256Z[indexWord( 4, 3 )]; + sigZ.v0 = sig256Z[indexWord( 4, 2 )]; + } else { + sig256C[indexWord( 4, 3 )] = sigC.v64; + sig256C[indexWord( 4, 2 )] = sigC.v0; + sig256C[indexWord( 4, 1 )] = 0; + sig256C[indexWord( 4, 0 )] = 0; + softfloat_shiftRightJam256M( sig256C, expDiff, sig256C ); + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 8; + if ( signZ == signC ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expDiff <= 0 ) { + sigZ = softfloat_add128( sigC.v64, sigC.v0, sigZ.v64, sigZ.v0 ); + } else { + softfloat_add256M( sig256Z, sig256C, sig256Z ); + sigZ.v64 = sig256Z[indexWord( 4, 3 )]; + sigZ.v0 = sig256Z[indexWord( 4, 2 )]; + } + if ( sigZ.v64 & UINT64_C( 0x0200000000000000 ) ) { + ++expZ; + shiftDist = 9; + } + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( expDiff < 0 ) { + signZ = signC; + if ( expDiff < -1 ) { + sigZ = + softfloat_sub128( sigC.v64, sigC.v0, sigZ.v64, sigZ.v0 ); + sigZExtra = + sig256Z[indexWord( 4, 1 )] | sig256Z[indexWord( 4, 0 )]; + if ( sigZExtra ) { + sigZ = softfloat_sub128( sigZ.v64, sigZ.v0, 0, 1 ); + } + if ( ! (sigZ.v64 & UINT64_C( 0x0100000000000000 )) ) { + --expZ; + shiftDist = 7; + } + goto shiftRightRoundPack; + } else { + sig256C[indexWord( 4, 3 )] = sigC.v64; + sig256C[indexWord( 4, 2 )] = sigC.v0; + sig256C[indexWord( 4, 1 )] = 0; + sig256C[indexWord( 4, 0 )] = 0; + softfloat_sub256M( sig256C, sig256Z, sig256Z ); + } + } else if ( ! expDiff ) { + sigZ = softfloat_sub128( sigZ.v64, sigZ.v0, sigC.v64, sigC.v0 ); + if ( + ! (sigZ.v64 | sigZ.v0) && ! sig256Z[indexWord( 4, 1 )] + && ! sig256Z[indexWord( 4, 0 )] + ) { + goto completeCancellation; + } + sig256Z[indexWord( 4, 3 )] = sigZ.v64; + sig256Z[indexWord( 4, 2 )] = sigZ.v0; + if ( sigZ.v64 & UINT64_C( 0x8000000000000000 ) ) { + signZ = ! signZ; + softfloat_sub256M( zero256, sig256Z, sig256Z ); + } + } else { + softfloat_sub256M( sig256Z, sig256C, sig256Z ); + if ( 1 < expDiff ) { + sigZ.v64 = sig256Z[indexWord( 4, 3 )]; + sigZ.v0 = sig256Z[indexWord( 4, 2 )]; + if ( ! (sigZ.v64 & UINT64_C( 0x0100000000000000 )) ) { + --expZ; + shiftDist = 7; + } + goto sigZ; + } + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sigZ.v64 = sig256Z[indexWord( 4, 3 )]; + sigZ.v0 = sig256Z[indexWord( 4, 2 )]; + sigZExtra = sig256Z[indexWord( 4, 1 )]; + sig256Z0 = sig256Z[indexWord( 4, 0 )]; + if ( sigZ.v64 ) { + if ( sig256Z0 ) sigZExtra |= 1; + } else { + expZ -= 64; + sigZ.v64 = sigZ.v0; + sigZ.v0 = sigZExtra; + sigZExtra = sig256Z0; + if ( ! sigZ.v64 ) { + expZ -= 64; + sigZ.v64 = sigZ.v0; + sigZ.v0 = sigZExtra; + sigZExtra = 0; + if ( ! sigZ.v64 ) { + expZ -= 64; + sigZ.v64 = sigZ.v0; + sigZ.v0 = 0; + } + } + } + shiftDist = softfloat_countLeadingZeros64( sigZ.v64 ); + expZ += 7 - shiftDist; + shiftDist = 15 - shiftDist; + if ( 0 < shiftDist ) goto shiftRightRoundPack; + if ( shiftDist ) { + shiftDist = -shiftDist; + sigZ = softfloat_shortShiftLeft128( sigZ.v64, sigZ.v0, shiftDist ); + x128 = softfloat_shortShiftLeft128( 0, sigZExtra, shiftDist ); + sigZ.v0 |= x128.v64; + sigZExtra = x128.v0; + } + goto roundPack; + } + sigZ: + sigZExtra = sig256Z[indexWord( 4, 1 )] | sig256Z[indexWord( 4, 0 )]; + shiftRightRoundPack: + sigZExtra = (uint64_t) (sigZ.v0<<(64 - shiftDist)) | (sigZExtra != 0); + sigZ = softfloat_shortShiftRight128( sigZ.v64, sigZ.v0, shiftDist ); + roundPack: + return + softfloat_roundPackToF128( + signZ, expZ - 1, sigZ.v64, sigZ.v0, sigZExtra ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN_ABC: + uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, uiB64, uiB0 ); + goto propagateNaN_ZC; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infProdArg: + if ( magBits ) { + uiZ.v64 = packToF128UI64( signZ, 0x7FFF, 0 ); + uiZ.v0 = 0; + if ( expC != 0x7FFF ) goto uiZ; + if ( sigC.v64 | sigC.v0 ) goto propagateNaN_ZC; + if ( signZ == signC ) goto uiZ; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ.v64 = defaultNaNF128UI64; + uiZ.v0 = defaultNaNF128UI0; + propagateNaN_ZC: + uiZ = softfloat_propagateNaNF128UI( uiZ.v64, uiZ.v0, uiC64, uiC0 ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zeroProd: + uiZ.v64 = uiC64; + uiZ.v0 = uiC0; + if ( ! (expC | sigC.v64 | sigC.v0) && (signZ != signC) ) { + completeCancellation: + uiZ.v64 = + packToF128UI64( + (softfloat_roundingMode == softfloat_round_min), 0, 0 ); + uiZ.v0 = 0; + } + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/s_mulAddF128.c ****/ +/**** start inlining ../../source/softfloat_state.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifndef THREAD_LOCAL +#define THREAD_LOCAL +#endif + +THREAD_LOCAL uint_fast8_t softfloat_roundingMode = softfloat_round_near_even; +THREAD_LOCAL uint_fast8_t softfloat_detectTininess = init_detectTininess; +THREAD_LOCAL uint_fast8_t softfloat_exceptionFlags = 0; + +THREAD_LOCAL uint_fast8_t extF80_roundingPrecision = 80; + +/**** ended inlining ../../source/softfloat_state.c ****/ +/**** start inlining ../../source/ui32_to_f16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t ui32_to_f16( uint32_t a ) +{ + int_fast8_t shiftDist; + union ui16_f16 u; + uint_fast16_t sig; + + shiftDist = softfloat_countLeadingZeros32( a ) - 21; + if ( 0 <= shiftDist ) { + u.ui = + a ? packToF16UI( + 0, 0x18 - shiftDist, (uint_fast16_t) a<>(-shiftDist) | ((uint32_t) (a<<(shiftDist & 31)) != 0) + : (uint_fast16_t) a< +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t ui32_to_f32( uint32_t a ) +{ + union ui32_f32 uZ; + + if ( ! a ) { + uZ.ui = 0; + return uZ.f; + } + if ( a & 0x80000000 ) { + return softfloat_roundPackToF32( 0, 0x9D, a>>1 | (a & 1) ); + } else { + return softfloat_normRoundPackToF32( 0, 0x9C, a ); + } + +} + +/**** ended inlining ../../source/ui32_to_f32.c ****/ +/**** start inlining ../../source/ui32_to_f64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t ui32_to_f64( uint32_t a ) +{ + uint_fast64_t uiZ; + int_fast8_t shiftDist; + union ui64_f64 uZ; + + if ( ! a ) { + uiZ = 0; + } else { + shiftDist = softfloat_countLeadingZeros32( a ) + 21; + uiZ = + packToF64UI( 0, 0x432 - shiftDist, (uint_fast64_t) a< +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t ui32_to_extF80( uint32_t a ) +{ + uint_fast16_t uiZ64; + int_fast8_t shiftDist; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + uiZ64 = 0; + if ( a ) { + shiftDist = softfloat_countLeadingZeros32( a ); + uiZ64 = 0x401E - shiftDist; + a <<= shiftDist; + } + uZ.s.signExp = uiZ64; + uZ.s.signif = (uint_fast64_t) a<<32; + return uZ.f; + +} + +/**** ended inlining ../../source/ui32_to_extF80.c ****/ +/**** start inlining ../../source/ui32_to_extF80M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void ui32_to_extF80M( uint32_t a, extFloat80_t *zPtr ) +{ + + *zPtr = ui32_to_extF80( a ); + +} + +#else + +void ui32_to_extF80M( uint32_t a, extFloat80_t *zPtr ) +{ + struct extFloat80M *zSPtr; + uint_fast16_t uiZ64; + uint64_t sigZ; + int_fast8_t shiftDist; + + zSPtr = (struct extFloat80M *) zPtr; + uiZ64 = 0; + sigZ = 0; + if ( a ) { + shiftDist = softfloat_countLeadingZeros32( a ); + uiZ64 = packToExtF80UI64( 0, 0x401E - shiftDist ); + sigZ = (uint64_t) (a<signExp = uiZ64; + zSPtr->signif = sigZ; + +} + +#endif + +/**** ended inlining ../../source/ui32_to_extF80M.c ****/ +/**** start inlining ../../source/ui32_to_f128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t ui32_to_f128( uint32_t a ) +{ + uint_fast64_t uiZ64; + int_fast8_t shiftDist; + union ui128_f128 uZ; + + uiZ64 = 0; + if ( a ) { + shiftDist = softfloat_countLeadingZeros32( a ) + 17; + uiZ64 = + packToF128UI64( + 0, 0x402E - shiftDist, (uint_fast64_t) a< +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void ui32_to_f128M( uint32_t a, float128_t *zPtr ) +{ + + *zPtr = ui32_to_f128( a ); + +} + +#else + +void ui32_to_f128M( uint32_t a, float128_t *zPtr ) +{ + uint32_t *zWPtr, uiZ96, uiZ64; + int_fast8_t shiftDist; + uint64_t normA; + + zWPtr = (uint32_t *) zPtr; + uiZ96 = 0; + uiZ64 = 0; + if ( a ) { + shiftDist = softfloat_countLeadingZeros32( a ) + 17; + normA = (uint64_t) a<>32 ); + uiZ64 = normA; + } + zWPtr[indexWord( 4, 3 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = uiZ64; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + +} + +#endif + +/**** ended inlining ../../source/ui32_to_f128M.c ****/ +/**** start inlining ../../source/ui64_to_f16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t ui64_to_f16( uint64_t a ) +{ + int_fast8_t shiftDist; + union ui16_f16 u; + uint_fast16_t sig; + + shiftDist = softfloat_countLeadingZeros64( a ) - 53; + if ( 0 <= shiftDist ) { + u.ui = + a ? packToF16UI( + 0, 0x18 - shiftDist, (uint_fast16_t) a< +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t ui64_to_f32( uint64_t a ) +{ + int_fast8_t shiftDist; + union ui32_f32 u; + uint_fast32_t sig; + + shiftDist = softfloat_countLeadingZeros64( a ) - 40; + if ( 0 <= shiftDist ) { + u.ui = + a ? packToF32UI( + 0, 0x95 - shiftDist, (uint_fast32_t) a< +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t ui64_to_f64( uint64_t a ) +{ + union ui64_f64 uZ; + + if ( ! a ) { + uZ.ui = 0; + return uZ.f; + } + if ( a & UINT64_C( 0x8000000000000000 ) ) { + return + softfloat_roundPackToF64( + 0, 0x43D, softfloat_shortShiftRightJam64( a, 1 ) ); + } else { + return softfloat_normRoundPackToF64( 0, 0x43C, a ); + } + +} + +/**** ended inlining ../../source/ui64_to_f64.c ****/ +/**** start inlining ../../source/ui64_to_extF80.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t ui64_to_extF80( uint64_t a ) +{ + uint_fast16_t uiZ64; + int_fast8_t shiftDist; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + uiZ64 = 0; + if ( a ) { + shiftDist = softfloat_countLeadingZeros64( a ); + uiZ64 = 0x403E - shiftDist; + a <<= shiftDist; + } + uZ.s.signExp = uiZ64; + uZ.s.signif = a; + return uZ.f; + +} + +/**** ended inlining ../../source/ui64_to_extF80.c ****/ +/**** start inlining ../../source/ui64_to_extF80M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void ui64_to_extF80M( uint64_t a, extFloat80_t *zPtr ) +{ + + *zPtr = ui64_to_extF80( a ); + +} + +#else + +void ui64_to_extF80M( uint64_t a, extFloat80_t *zPtr ) +{ + struct extFloat80M *zSPtr; + uint_fast16_t uiZ64; + uint64_t sigZ; + int_fast8_t shiftDist; + + zSPtr = (struct extFloat80M *) zPtr; + uiZ64 = 0; + sigZ = 0; + if ( a ) { + shiftDist = softfloat_countLeadingZeros64( a ); + uiZ64 = packToExtF80UI64( 0, 0x403E - shiftDist ); + sigZ = a<signExp = uiZ64; + zSPtr->signif = sigZ; + +} + +#endif + +/**** ended inlining ../../source/ui64_to_extF80M.c ****/ +/**** start inlining ../../source/ui64_to_f128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t ui64_to_f128( uint64_t a ) +{ + uint_fast64_t uiZ64, uiZ0; + int_fast8_t shiftDist; + struct uint128 zSig; + union ui128_f128 uZ; + + if ( ! a ) { + uiZ64 = 0; + uiZ0 = 0; + } else { + shiftDist = softfloat_countLeadingZeros64( a ) + 49; + if ( 64 <= shiftDist ) { + zSig.v64 = a<<(shiftDist - 64); + zSig.v0 = 0; + } else { + zSig = softfloat_shortShiftLeft128( 0, a, shiftDist ); + } + uiZ64 = packToF128UI64( 0, 0x406E - shiftDist, zSig.v64 ); + uiZ0 = zSig.v0; + } + uZ.ui.v64 = uiZ64; + uZ.ui.v0 = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/ui64_to_f128.c ****/ +/**** start inlining ../../source/ui64_to_f128M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void ui64_to_f128M( uint64_t a, float128_t *zPtr ) +{ + + *zPtr = ui64_to_f128( a ); + +} + +#else + +void ui64_to_f128M( uint64_t a, float128_t *zPtr ) +{ + uint32_t *zWPtr, uiZ96, uiZ64; + uint_fast8_t shiftDist; + uint32_t *ptr; + + zWPtr = (uint32_t *) zPtr; + uiZ96 = 0; + uiZ64 = 0; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + if ( a ) { + shiftDist = softfloat_countLeadingZeros64( a ) + 17; + if ( shiftDist < 32 ) { + ptr = zWPtr + indexMultiwordHi( 4, 3 ); + ptr[indexWord( 3, 2 )] = 0; + ptr[indexWord( 3, 1 )] = a>>32; + ptr[indexWord( 3, 0 )] = a; + softfloat_shortShiftLeft96M( ptr, shiftDist, ptr ); + ptr[indexWordHi( 3 )] = + packToF128UI96( 0, 0x404E - shiftDist, ptr[indexWordHi( 3 )] ); + return; + } + a <<= shiftDist - 32; + uiZ96 = packToF128UI96( 0, 0x404E - shiftDist, a>>32 ); + uiZ64 = a; + } + zWPtr[indexWord( 4, 3 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = uiZ64; + +} + +#endif + +/**** ended inlining ../../source/ui64_to_f128M.c ****/ +/**** start inlining ../../source/i32_to_f16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t i32_to_f16( int32_t a ) +{ + bool sign; + uint_fast32_t absA; + int_fast8_t shiftDist; + union ui16_f16 u; + uint_fast16_t sig; + + sign = (a < 0); + absA = sign ? -(uint_fast32_t) a : (uint_fast32_t) a; + shiftDist = softfloat_countLeadingZeros32( absA ) - 21; + if ( 0 <= shiftDist ) { + u.ui = + a ? packToF16UI( + sign, 0x18 - shiftDist, (uint_fast16_t) absA<>(-shiftDist) + | ((uint32_t) (absA<<(shiftDist & 31)) != 0) + : (uint_fast16_t) absA< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t i32_to_f32( int32_t a ) +{ + bool sign; + union ui32_f32 uZ; + uint_fast32_t absA; + + sign = (a < 0); + if ( ! (a & 0x7FFFFFFF) ) { + uZ.ui = sign ? packToF32UI( 1, 0x9E, 0 ) : 0; + return uZ.f; + } + absA = sign ? -(uint_fast32_t) a : (uint_fast32_t) a; + return softfloat_normRoundPackToF32( sign, 0x9C, absA ); + +} + +/**** ended inlining ../../source/i32_to_f32.c ****/ +/**** start inlining ../../source/i32_to_f64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t i32_to_f64( int32_t a ) +{ + uint_fast64_t uiZ; + bool sign; + uint_fast32_t absA; + int_fast8_t shiftDist; + union ui64_f64 uZ; + + if ( ! a ) { + uiZ = 0; + } else { + sign = (a < 0); + absA = sign ? -(uint_fast32_t) a : (uint_fast32_t) a; + shiftDist = softfloat_countLeadingZeros32( absA ) + 21; + uiZ = + packToF64UI( + sign, 0x432 - shiftDist, (uint_fast64_t) absA< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t i32_to_extF80( int32_t a ) +{ + uint_fast16_t uiZ64; + uint_fast32_t absA; + bool sign; + int_fast8_t shiftDist; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + uiZ64 = 0; + absA = 0; + if ( a ) { + sign = (a < 0); + absA = sign ? -(uint_fast32_t) a : (uint_fast32_t) a; + shiftDist = softfloat_countLeadingZeros32( absA ); + uiZ64 = packToExtF80UI64( sign, 0x401E - shiftDist ); + absA <<= shiftDist; + } + uZ.s.signExp = uiZ64; + uZ.s.signif = (uint_fast64_t) absA<<32; + return uZ.f; + +} + +/**** ended inlining ../../source/i32_to_extF80.c ****/ +/**** start inlining ../../source/i32_to_extF80M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void i32_to_extF80M( int32_t a, extFloat80_t *zPtr ) +{ + + *zPtr = i32_to_extF80( a ); + +} + +#else + +void i32_to_extF80M( int32_t a, extFloat80_t *zPtr ) +{ + struct extFloat80M *zSPtr; + uint_fast16_t uiZ64; + uint64_t sigZ; + bool sign; + uint32_t absA; + int_fast8_t shiftDist; + + zSPtr = (struct extFloat80M *) zPtr; + uiZ64 = 0; + sigZ = 0; + if ( a ) { + sign = (a < 0); + absA = sign ? -(uint32_t) a : (uint32_t) a; + shiftDist = softfloat_countLeadingZeros32( absA ); + uiZ64 = packToExtF80UI64( sign, 0x401E - shiftDist ); + sigZ = (uint64_t) (absA<signExp = uiZ64; + zSPtr->signif = sigZ; + +} + +#endif + +/**** ended inlining ../../source/i32_to_extF80M.c ****/ +/**** start inlining ../../source/i32_to_f128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t i32_to_f128( int32_t a ) +{ + uint_fast64_t uiZ64; + bool sign; + uint_fast32_t absA; + int_fast8_t shiftDist; + union ui128_f128 uZ; + + uiZ64 = 0; + if ( a ) { + sign = (a < 0); + absA = sign ? -(uint_fast32_t) a : (uint_fast32_t) a; + shiftDist = softfloat_countLeadingZeros32( absA ) + 17; + uiZ64 = + packToF128UI64( + sign, 0x402E - shiftDist, (uint_fast64_t) absA< +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void i32_to_f128M( int32_t a, float128_t *zPtr ) +{ + + *zPtr = i32_to_f128( a ); + +} + +#else + +void i32_to_f128M( int32_t a, float128_t *zPtr ) +{ + uint32_t *zWPtr; + uint32_t uiZ96, uiZ64; + bool sign; + uint32_t absA; + int_fast8_t shiftDist; + uint64_t normAbsA; + + zWPtr = (uint32_t *) zPtr; + uiZ96 = 0; + uiZ64 = 0; + if ( a ) { + sign = (a < 0); + absA = sign ? -(uint32_t) a : (uint32_t) a; + shiftDist = softfloat_countLeadingZeros32( absA ) + 17; + normAbsA = (uint64_t) absA<>32 ); + uiZ64 = normAbsA; + } + zWPtr[indexWord( 4, 3 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = uiZ64; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + +} + +#endif + +/**** ended inlining ../../source/i32_to_f128M.c ****/ +/**** start inlining ../../source/i64_to_f16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t i64_to_f16( int64_t a ) +{ + bool sign; + uint_fast64_t absA; + int_fast8_t shiftDist; + union ui16_f16 u; + uint_fast16_t sig; + + sign = (a < 0); + absA = sign ? -(uint_fast64_t) a : (uint_fast64_t) a; + shiftDist = softfloat_countLeadingZeros64( absA ) - 53; + if ( 0 <= shiftDist ) { + u.ui = + a ? packToF16UI( + sign, 0x18 - shiftDist, (uint_fast16_t) absA< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t i64_to_f32( int64_t a ) +{ + bool sign; + uint_fast64_t absA; + int_fast8_t shiftDist; + union ui32_f32 u; + uint_fast32_t sig; + + sign = (a < 0); + absA = sign ? -(uint_fast64_t) a : (uint_fast64_t) a; + shiftDist = softfloat_countLeadingZeros64( absA ) - 40; + if ( 0 <= shiftDist ) { + u.ui = + a ? packToF32UI( + sign, 0x95 - shiftDist, (uint_fast32_t) absA< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t i64_to_f64( int64_t a ) +{ + bool sign; + union ui64_f64 uZ; + uint_fast64_t absA; + + sign = (a < 0); + if ( ! (a & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ) { + uZ.ui = sign ? packToF64UI( 1, 0x43E, 0 ) : 0; + return uZ.f; + } + absA = sign ? -(uint_fast64_t) a : (uint_fast64_t) a; + return softfloat_normRoundPackToF64( sign, 0x43C, absA ); + +} + +/**** ended inlining ../../source/i64_to_f64.c ****/ +/**** start inlining ../../source/i64_to_extF80.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t i64_to_extF80( int64_t a ) +{ + uint_fast16_t uiZ64; + uint_fast64_t absA; + bool sign; + int_fast8_t shiftDist; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + uiZ64 = 0; + absA = 0; + if ( a ) { + sign = (a < 0); + absA = sign ? -(uint_fast64_t) a : (uint_fast64_t) a; + shiftDist = softfloat_countLeadingZeros64( absA ); + uiZ64 = packToExtF80UI64( sign, 0x403E - shiftDist ); + absA <<= shiftDist; + } + uZ.s.signExp = uiZ64; + uZ.s.signif = absA; + return uZ.f; + +} + +/**** ended inlining ../../source/i64_to_extF80.c ****/ +/**** start inlining ../../source/i64_to_extF80M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void i64_to_extF80M( int64_t a, extFloat80_t *zPtr ) +{ + + *zPtr = i64_to_extF80( a ); + +} + +#else + +void i64_to_extF80M( int64_t a, extFloat80_t *zPtr ) +{ + struct extFloat80M *zSPtr; + uint_fast16_t uiZ64; + uint64_t sigZ; + bool sign; + uint64_t absA; + int_fast8_t shiftDist; + + zSPtr = (struct extFloat80M *) zPtr; + uiZ64 = 0; + sigZ = 0; + if ( a ) { + sign = (a < 0); + absA = sign ? -(uint64_t) a : (uint64_t) a; + shiftDist = softfloat_countLeadingZeros64( absA ); + uiZ64 = packToExtF80UI64( sign, 0x403E - shiftDist ); + sigZ = absA<signExp = uiZ64; + zSPtr->signif = sigZ; + +} + +#endif + +/**** ended inlining ../../source/i64_to_extF80M.c ****/ +/**** start inlining ../../source/i64_to_f128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t i64_to_f128( int64_t a ) +{ + uint_fast64_t uiZ64, uiZ0; + bool sign; + uint_fast64_t absA; + int_fast8_t shiftDist; + struct uint128 zSig; + union ui128_f128 uZ; + + if ( ! a ) { + uiZ64 = 0; + uiZ0 = 0; + } else { + sign = (a < 0); + absA = sign ? -(uint_fast64_t) a : (uint_fast64_t) a; + shiftDist = softfloat_countLeadingZeros64( absA ) + 49; + if ( 64 <= shiftDist ) { + zSig.v64 = absA<<(shiftDist - 64); + zSig.v0 = 0; + } else { + zSig = softfloat_shortShiftLeft128( 0, absA, shiftDist ); + } + uiZ64 = packToF128UI64( sign, 0x406E - shiftDist, zSig.v64 ); + uiZ0 = zSig.v0; + } + uZ.ui.v64 = uiZ64; + uZ.ui.v0 = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/i64_to_f128.c ****/ +/**** start inlining ../../source/i64_to_f128M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void i64_to_f128M( int64_t a, float128_t *zPtr ) +{ + + *zPtr = i64_to_f128( a ); + +} + +#else + +void i64_to_f128M( int64_t a, float128_t *zPtr ) +{ + uint32_t *zWPtr; + uint32_t uiZ96, uiZ64; + bool sign; + uint64_t absA; + uint_fast8_t shiftDist; + uint32_t *ptr; + + zWPtr = (uint32_t *) zPtr; + uiZ96 = 0; + uiZ64 = 0; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + if ( a ) { + sign = (a < 0); + absA = sign ? -(uint64_t) a : (uint64_t) a; + shiftDist = softfloat_countLeadingZeros64( absA ) + 17; + if ( shiftDist < 32 ) { + ptr = zWPtr + indexMultiwordHi( 4, 3 ); + ptr[indexWord( 3, 2 )] = 0; + ptr[indexWord( 3, 1 )] = absA>>32; + ptr[indexWord( 3, 0 )] = absA; + softfloat_shortShiftLeft96M( ptr, shiftDist, ptr ); + ptr[indexWordHi( 3 )] = + packToF128UI96( + sign, 0x404E - shiftDist, ptr[indexWordHi( 3 )] ); + return; + } + absA <<= shiftDist - 32; + uiZ96 = packToF128UI96( sign, 0x404E - shiftDist, absA>>32 ); + uiZ64 = absA; + } + zWPtr[indexWord( 4, 3 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = uiZ64; + +} + +#endif + +/**** ended inlining ../../source/i64_to_f128M.c ****/ +/**** start inlining ../../source/f16_to_ui32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t f16_to_ui32( float16_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool sign; + int_fast8_t exp; + uint_fast16_t frac; + uint_fast32_t sig32; + int_fast8_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + frac ? ui32_fromNaN + : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig32 = frac; + if ( exp ) { + sig32 |= 0x0400; + shiftDist = exp - 0x19; + if ( (0 <= shiftDist) && ! sign ) { + return sig32< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t f16_to_ui64( float16_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool sign; + int_fast8_t exp; + uint_fast16_t frac; + uint_fast32_t sig32; + int_fast8_t shiftDist; +#ifndef SOFTFLOAT_FAST_INT64 + uint32_t extSig[3]; +#endif + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + frac ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig32 = frac; + if ( exp ) { + sig32 |= 0x0400; + shiftDist = exp - 0x19; + if ( (0 <= shiftDist) && ! sign ) { + return sig32<>12, (uint_fast64_t) sig32<<52, roundingMode, exact ); +#else + extSig[indexWord( 3, 2 )] = 0; + extSig[indexWord( 3, 1 )] = sig32>>12; + extSig[indexWord( 3, 0 )] = sig32<<20; + return softfloat_roundMToUI64( sign, extSig, roundingMode, exact ); +#endif + +} + +/**** ended inlining ../../source/f16_to_ui64.c ****/ +/**** start inlining ../../source/f16_to_i32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t f16_to_i32( float16_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool sign; + int_fast8_t exp; + uint_fast16_t frac; + int_fast32_t sig32; + int_fast8_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + frac ? i32_fromNaN + : sign ? i32_fromNegOverflow : i32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig32 = frac; + if ( exp ) { + sig32 |= 0x0400; + shiftDist = exp - 0x19; + if ( 0 <= shiftDist ) { + sig32 <<= shiftDist; + return sign ? -sig32 : sig32; + } + shiftDist = exp - 0x0D; + if ( 0 < shiftDist ) sig32 <<= shiftDist; + } + return + softfloat_roundToI32( + sign, (uint_fast32_t) sig32, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f16_to_i32.c ****/ +/**** start inlining ../../source/f16_to_i64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t f16_to_i64( float16_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool sign; + int_fast8_t exp; + uint_fast16_t frac; + int_fast32_t sig32; + int_fast8_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + frac ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig32 = frac; + if ( exp ) { + sig32 |= 0x0400; + shiftDist = exp - 0x19; + if ( 0 <= shiftDist ) { + sig32 <<= shiftDist; + return sign ? -sig32 : sig32; + } + shiftDist = exp - 0x0D; + if ( 0 < shiftDist ) sig32 <<= shiftDist; + } + return + softfloat_roundToI32( + sign, (uint_fast32_t) sig32, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f16_to_i64.c ****/ +/**** start inlining ../../source/f16_to_ui32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t f16_to_ui32_r_minMag( float16_t a, bool exact ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + int_fast8_t exp; + uint_fast16_t frac; + int_fast8_t shiftDist; + bool sign; + uint_fast32_t alignedSig; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = exp - 0x0F; + if ( shiftDist < 0 ) { + if ( exact && (exp | frac) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF16UI( uiA ); + if ( sign || (exp == 0x1F) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x1F) && frac ? ui32_fromNaN + : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + alignedSig = (uint_fast32_t) (frac | 0x0400)<>10; + +} + +/**** ended inlining ../../source/f16_to_ui32_r_minMag.c ****/ +/**** start inlining ../../source/f16_to_ui64_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t f16_to_ui64_r_minMag( float16_t a, bool exact ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + int_fast8_t exp; + uint_fast16_t frac; + int_fast8_t shiftDist; + bool sign; + uint_fast32_t alignedSig; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = exp - 0x0F; + if ( shiftDist < 0 ) { + if ( exact && (exp | frac) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF16UI( uiA ); + if ( sign || (exp == 0x1F) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x1F) && frac ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + alignedSig = (uint_fast32_t) (frac | 0x0400)<>10; + +} + +/**** ended inlining ../../source/f16_to_ui64_r_minMag.c ****/ +/**** start inlining ../../source/f16_to_i32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t f16_to_i32_r_minMag( float16_t a, bool exact ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + int_fast8_t exp; + uint_fast16_t frac; + int_fast8_t shiftDist; + bool sign; + int_fast32_t alignedSig; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = exp - 0x0F; + if ( shiftDist < 0 ) { + if ( exact && (exp | frac) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF16UI( uiA ); + if ( exp == 0x1F ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x1F) && frac ? i32_fromNaN + : sign ? i32_fromNegOverflow : i32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + alignedSig = (int_fast32_t) (frac | 0x0400)<>= 10; + return sign ? -alignedSig : alignedSig; + +} + +/**** ended inlining ../../source/f16_to_i32_r_minMag.c ****/ +/**** start inlining ../../source/f16_to_i64_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t f16_to_i64_r_minMag( float16_t a, bool exact ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + int_fast8_t exp; + uint_fast16_t frac; + int_fast8_t shiftDist; + bool sign; + int_fast32_t alignedSig; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = exp - 0x0F; + if ( shiftDist < 0 ) { + if ( exact && (exp | frac) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF16UI( uiA ); + if ( exp == 0x1F ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x1F) && frac ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + alignedSig = (int_fast32_t) (frac | 0x0400)<>= 10; + return sign ? -alignedSig : alignedSig; + +} + +/**** ended inlining ../../source/f16_to_i64_r_minMag.c ****/ +/**** start inlining ../../source/f16_to_f32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f16_to_f32( float16_t a ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool sign; + int_fast8_t exp; + uint_fast16_t frac; + struct commonNaN commonNaN; + uint_fast32_t uiZ; + struct exp8_sig16 normExpSig; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + if ( frac ) { + softfloat_f16UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF32UI( &commonNaN ); + } else { + uiZ = packToF32UI( sign, 0xFF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ = packToF32UI( sign, 0, 0 ); + goto uiZ; + } + normExpSig = softfloat_normSubnormalF16Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ = packToF32UI( sign, exp + 0x70, (uint_fast32_t) frac<<13 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f16_to_f32.c ****/ +/**** start inlining ../../source/f16_to_f64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f16_to_f64( float16_t a ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool sign; + int_fast8_t exp; + uint_fast16_t frac; + struct commonNaN commonNaN; + uint_fast64_t uiZ; + struct exp8_sig16 normExpSig; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + if ( frac ) { + softfloat_f16UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF64UI( &commonNaN ); + } else { + uiZ = packToF64UI( sign, 0x7FF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ = packToF64UI( sign, 0, 0 ); + goto uiZ; + } + normExpSig = softfloat_normSubnormalF16Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ = packToF64UI( sign, exp + 0x3F0, (uint_fast64_t) frac<<42 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f16_to_f64.c ****/ +/**** start inlining ../../source/f16_to_extF80.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t f16_to_extF80( float16_t a ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool sign; + int_fast8_t exp; + uint_fast16_t frac; + struct commonNaN commonNaN; + struct uint128 uiZ; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0; + struct exp8_sig16 normExpSig; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + if ( frac ) { + softfloat_f16UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToExtF80UI( &commonNaN ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + } else { + uiZ64 = packToExtF80UI64( sign, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ64 = packToExtF80UI64( sign, 0 ); + uiZ0 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF16Sig( frac ); + exp = normExpSig.exp; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ64 = packToExtF80UI64( sign, exp + 0x3FF0 ); + uiZ0 = (uint_fast64_t) (frac | 0x0400)<<53; + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/f16_to_extF80.c ****/ +/**** start inlining ../../source/f16_to_extF80M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void f16_to_extF80M( float16_t a, extFloat80_t *zPtr ) +{ + + *zPtr = f16_to_extF80( a ); + +} + +#else + +void f16_to_extF80M( float16_t a, extFloat80_t *zPtr ) +{ + struct extFloat80M *zSPtr; + union ui16_f16 uA; + uint16_t uiA; + bool sign; + int_fast8_t exp; + uint16_t frac; + struct commonNaN commonNaN; + uint_fast16_t uiZ64; + uint32_t uiZ32; + struct exp8_sig16 normExpSig; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zSPtr = (struct extFloat80M *) zPtr; + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + if ( frac ) { + softfloat_f16UIToCommonNaN( uiA, &commonNaN ); + softfloat_commonNaNToExtF80M( &commonNaN, zSPtr ); + return; + } + uiZ64 = packToExtF80UI64( sign, 0x7FFF ); + uiZ32 = 0x80000000; + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ64 = packToExtF80UI64( sign, 0 ); + uiZ32 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF16Sig( frac ); + exp = normExpSig.exp; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ64 = packToExtF80UI64( sign, exp + 0x3FF0 ); + uiZ32 = 0x80000000 | (uint32_t) frac<<21; + uiZ: + zSPtr->signExp = uiZ64; + zSPtr->signif = (uint64_t) uiZ32<<32; + +} + +#endif + +/**** ended inlining ../../source/f16_to_extF80M.c ****/ +/**** start inlining ../../source/f16_to_f128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f16_to_f128( float16_t a ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool sign; + int_fast8_t exp; + uint_fast16_t frac; + struct commonNaN commonNaN; + struct uint128 uiZ; + struct exp8_sig16 normExpSig; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + if ( frac ) { + softfloat_f16UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF128UI( &commonNaN ); + } else { + uiZ.v64 = packToF128UI64( sign, 0x7FFF, 0 ); + uiZ.v0 = 0; + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ.v64 = packToF128UI64( sign, 0, 0 ); + uiZ.v0 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF16Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ.v64 = packToF128UI64( sign, exp + 0x3FF0, (uint_fast64_t) frac<<38 ); + uiZ.v0 = 0; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f16_to_f128.c ****/ +/**** start inlining ../../source/f16_to_f128M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void f16_to_f128M( float16_t a, float128_t *zPtr ) +{ + + *zPtr = f16_to_f128( a ); + +} + +#else + +void f16_to_f128M( float16_t a, float128_t *zPtr ) +{ + uint32_t *zWPtr; + union ui16_f16 uA; + uint16_t uiA; + bool sign; + int_fast8_t exp; + uint16_t frac; + struct commonNaN commonNaN; + uint32_t uiZ96; + struct exp8_sig16 normExpSig; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zWPtr = (uint32_t *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + if ( frac ) { + softfloat_f16UIToCommonNaN( uiA, &commonNaN ); + softfloat_commonNaNToF128M( &commonNaN, zWPtr ); + return; + } + uiZ96 = packToF128UI96( sign, 0x7FFF, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ96 = packToF128UI96( sign, 0, 0 ); + goto uiZ; + } + normExpSig = softfloat_normSubnormalF16Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ96 = packToF128UI96( sign, exp + 0x3FF0, (uint32_t) frac<<6 ); + uiZ: + zWPtr[indexWord( 4, 3 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = 0; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + +} + +#endif + +/**** ended inlining ../../source/f16_to_f128M.c ****/ +/**** start inlining ../../source/f16_roundToInt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t f16_roundToInt( float16_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + int_fast8_t exp; + uint_fast16_t uiZ, lastBitMask, roundBitsMask; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp <= 0xE ) { + if ( !(uint16_t) (uiA<<1) ) return a; + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + uiZ = uiA & packToF16UI( 1, 0, 0 ); + switch ( roundingMode ) { + case softfloat_round_near_even: + if ( !fracF16UI( uiA ) ) break; + case softfloat_round_near_maxMag: + if ( exp == 0xE ) uiZ |= packToF16UI( 0, 0xF, 0 ); + break; + case softfloat_round_min: + if ( uiZ ) uiZ = packToF16UI( 1, 0xF, 0 ); + break; + case softfloat_round_max: + if ( !uiZ ) uiZ = packToF16UI( 0, 0xF, 0 ); + break; +#ifdef SOFTFLOAT_ROUND_ODD + case softfloat_round_odd: + uiZ |= packToF16UI( 0, 0xF, 0 ); + break; +#endif + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x19 <= exp ) { + if ( (exp == 0x1F) && fracF16UI( uiA ) ) { + uiZ = softfloat_propagateNaNF16UI( uiA, 0 ); + goto uiZ; + } + return a; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ = uiA; + lastBitMask = (uint_fast16_t) 1<<(0x19 - exp); + roundBitsMask = lastBitMask - 1; + if ( roundingMode == softfloat_round_near_maxMag ) { + uiZ += lastBitMask>>1; + } else if ( roundingMode == softfloat_round_near_even ) { + uiZ += lastBitMask>>1; + if ( !(uiZ & roundBitsMask) ) uiZ &= ~lastBitMask; + } else if ( + roundingMode + == (signF16UI( uiZ ) ? softfloat_round_min : softfloat_round_max) + ) { + uiZ += roundBitsMask; + } + uiZ &= ~roundBitsMask; + if ( uiZ != uiA ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) uiZ |= lastBitMask; +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f16_roundToInt.c ****/ +/**** start inlining ../../source/f16_add.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t f16_add( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + union ui16_f16 uB; + uint_fast16_t uiB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 1) + float16_t (*magsFuncPtr)( uint_fast16_t, uint_fast16_t ); +#endif + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; +#if defined INLINE_LEVEL && (1 <= INLINE_LEVEL) + if ( signF16UI( uiA ^ uiB ) ) { + return softfloat_subMagsF16( uiA, uiB ); + } else { + return softfloat_addMagsF16( uiA, uiB ); + } +#else + magsFuncPtr = + signF16UI( uiA ^ uiB ) ? softfloat_subMagsF16 : softfloat_addMagsF16; + return (*magsFuncPtr)( uiA, uiB ); +#endif + +} + +/**** ended inlining ../../source/f16_add.c ****/ +/**** start inlining ../../source/f16_sub.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t f16_sub( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + union ui16_f16 uB; + uint_fast16_t uiB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 1) + float16_t (*magsFuncPtr)( uint_fast16_t, uint_fast16_t ); +#endif + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; +#if defined INLINE_LEVEL && (1 <= INLINE_LEVEL) + if ( signF16UI( uiA ^ uiB ) ) { + return softfloat_addMagsF16( uiA, uiB ); + } else { + return softfloat_subMagsF16( uiA, uiB ); + } +#else + magsFuncPtr = + signF16UI( uiA ^ uiB ) ? softfloat_addMagsF16 : softfloat_subMagsF16; + return (*magsFuncPtr)( uiA, uiB ); +#endif + +} + +/**** ended inlining ../../source/f16_sub.c ****/ +/**** start inlining ../../source/f16_mul.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t f16_mul( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool signA; + int_fast8_t expA; + uint_fast16_t sigA; + union ui16_f16 uB; + uint_fast16_t uiB; + bool signB; + int_fast8_t expB; + uint_fast16_t sigB; + bool signZ; + uint_fast16_t magBits; + struct exp8_sig16 normExpSig; + int_fast8_t expZ; + uint_fast32_t sig32Z; + uint_fast16_t sigZ, uiZ; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF16UI( uiA ); + expA = expF16UI( uiA ); + sigA = fracF16UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF16UI( uiB ); + expB = expF16UI( uiB ); + sigB = fracF16UI( uiB ); + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x1F ) { + if ( sigA || ((expB == 0x1F) && sigB) ) goto propagateNaN; + magBits = expB | sigB; + goto infArg; + } + if ( expB == 0x1F ) { + if ( sigB ) goto propagateNaN; + magBits = expA | sigA; + goto infArg; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalF16Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! sigB ) goto zero; + normExpSig = softfloat_normSubnormalF16Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0xF; + sigA = (sigA | 0x0400)<<4; + sigB = (sigB | 0x0400)<<5; + sig32Z = (uint_fast32_t) sigA * sigB; + sigZ = sig32Z>>16; + if ( sig32Z & 0xFFFF ) sigZ |= 1; + if ( sigZ < 0x4000 ) { + --expZ; + sigZ <<= 1; + } + return softfloat_roundPackToF16( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF16UI( uiA, uiB ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infArg: + if ( ! magBits ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF16UI; + } else { + uiZ = packToF16UI( signZ, 0x1F, 0 ); + } + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ = packToF16UI( signZ, 0, 0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f16_mul.c ****/ +/**** start inlining ../../source/f16_mulAdd.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t f16_mulAdd( float16_t a, float16_t b, float16_t c ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + union ui16_f16 uB; + uint_fast16_t uiB; + union ui16_f16 uC; + uint_fast16_t uiC; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + uC.f = c; + uiC = uC.ui; + return softfloat_mulAddF16( uiA, uiB, uiC, 0 ); + +} + +/**** ended inlining ../../source/f16_mulAdd.c ****/ +/**** start inlining ../../source/f16_div.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extern const uint16_t softfloat_approxRecip_1k0s[]; +extern const uint16_t softfloat_approxRecip_1k1s[]; + +float16_t f16_div( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool signA; + int_fast8_t expA; + uint_fast16_t sigA; + union ui16_f16 uB; + uint_fast16_t uiB; + bool signB; + int_fast8_t expB; + uint_fast16_t sigB; + bool signZ; + struct exp8_sig16 normExpSig; + int_fast8_t expZ; +#ifdef SOFTFLOAT_FAST_DIV32TO16 + uint_fast32_t sig32A; + uint_fast16_t sigZ; +#else + int index; + uint16_t r0; + uint_fast16_t sigZ, rem; +#endif + uint_fast16_t uiZ; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF16UI( uiA ); + expA = expF16UI( uiA ); + sigA = fracF16UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF16UI( uiB ); + expB = expF16UI( uiB ); + sigB = fracF16UI( uiB ); + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x1F ) { + if ( sigA ) goto propagateNaN; + if ( expB == 0x1F ) { + if ( sigB ) goto propagateNaN; + goto invalid; + } + goto infinity; + } + if ( expB == 0x1F ) { + if ( sigB ) goto propagateNaN; + goto zero; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) { + if ( ! sigB ) { + if ( ! (expA | sigA) ) goto invalid; + softfloat_raiseFlags( softfloat_flag_infinite ); + goto infinity; + } + normExpSig = softfloat_normSubnormalF16Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalF16Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA - expB + 0xE; + sigA |= 0x0400; + sigB |= 0x0400; +#ifdef SOFTFLOAT_FAST_DIV32TO16 + if ( sigA < sigB ) { + --expZ; + sig32A = (uint_fast32_t) sigA<<15; + } else { + sig32A = (uint_fast32_t) sigA<<14; + } + sigZ = sig32A / sigB; + if ( ! (sigZ & 7) ) sigZ |= ((uint_fast32_t) sigB * sigZ != sig32A); +#else + if ( sigA < sigB ) { + --expZ; + sigA <<= 5; + } else { + sigA <<= 4; + } + index = sigB>>6 & 0xF; + r0 = softfloat_approxRecip_1k0s[index] + - (((uint_fast32_t) softfloat_approxRecip_1k1s[index] + * (sigB & 0x3F)) + >>10); + sigZ = ((uint_fast32_t) sigA * r0)>>16; + rem = (sigA<<10) - sigZ * sigB; + sigZ += (rem * (uint_fast32_t) r0)>>26; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + ++sigZ; + if ( ! (sigZ & 7) ) { + sigZ &= ~1; + rem = (sigA<<10) - sigZ * sigB; + if ( rem & 0x8000 ) { + sigZ -= 2; + } else { + if ( rem ) sigZ |= 1; + } + } +#endif + return softfloat_roundPackToF16( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF16UI( uiA, uiB ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF16UI; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infinity: + uiZ = packToF16UI( signZ, 0x1F, 0 ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ = packToF16UI( signZ, 0, 0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f16_div.c ****/ +/**** start inlining ../../source/f16_rem.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t f16_rem( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool signA; + int_fast8_t expA; + uint_fast16_t sigA; + union ui16_f16 uB; + uint_fast16_t uiB; + int_fast8_t expB; + uint_fast16_t sigB; + struct exp8_sig16 normExpSig; + uint16_t rem; + int_fast8_t expDiff; + uint_fast16_t q; + uint32_t recip32, q32; + uint16_t altRem, meanRem; + bool signRem; + uint_fast16_t uiZ; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF16UI( uiA ); + expA = expF16UI( uiA ); + sigA = fracF16UI( uiA ); + uB.f = b; + uiB = uB.ui; + expB = expF16UI( uiB ); + sigB = fracF16UI( uiB ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x1F ) { + if ( sigA || ((expB == 0x1F) && sigB) ) goto propagateNaN; + goto invalid; + } + if ( expB == 0x1F ) { + if ( sigB ) goto propagateNaN; + return a; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) { + if ( ! sigB ) goto invalid; + normExpSig = softfloat_normSubnormalF16Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) { + if ( ! sigA ) return a; + normExpSig = softfloat_normSubnormalF16Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + rem = sigA | 0x0400; + sigB |= 0x0400; + expDiff = expA - expB; + if ( expDiff < 1 ) { + if ( expDiff < -1 ) return a; + sigB <<= 3; + if ( expDiff ) { + rem <<= 2; + q = 0; + } else { + rem <<= 3; + q = (sigB <= rem); + if ( q ) rem -= sigB; + } + } else { + recip32 = softfloat_approxRecip32_1( (uint_fast32_t) sigB<<21 ); + /*-------------------------------------------------------------------- + | Changing the shift of `rem' here requires also changing the initial + | subtraction from `expDiff'. + *--------------------------------------------------------------------*/ + rem <<= 4; + expDiff -= 31; + /*-------------------------------------------------------------------- + | The scale of `sigB' affects how many bits are obtained during each + | cycle of the loop. Currently this is 29 bits per loop iteration, + | which is believed to be the maximum possible. + *--------------------------------------------------------------------*/ + sigB <<= 3; + for (;;) { + q32 = (rem * (uint_fast64_t) recip32)>>16; + if ( expDiff < 0 ) break; + rem = -((uint_fast16_t) q32 * sigB); + expDiff -= 29; + } + /*-------------------------------------------------------------------- + | (`expDiff' cannot be less than -30 here.) + *--------------------------------------------------------------------*/ + q32 >>= ~expDiff & 31; + q = q32; + rem = (rem<<(expDiff + 30)) - q * sigB; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + do { + altRem = rem; + ++q; + rem -= sigB; + } while ( ! (rem & 0x8000) ); + meanRem = rem + altRem; + if ( (meanRem & 0x8000) || (! meanRem && (q & 1)) ) rem = altRem; + signRem = signA; + if ( 0x8000 <= rem ) { + signRem = ! signRem; + rem = -rem; + } + return softfloat_normRoundPackToF16( signRem, expB, rem ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF16UI( uiA, uiB ); + goto uiZ; + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF16UI; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f16_rem.c ****/ +/**** start inlining ../../source/f16_sqrt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extern const uint16_t softfloat_approxRecipSqrt_1k0s[]; +extern const uint16_t softfloat_approxRecipSqrt_1k1s[]; + +float16_t f16_sqrt( float16_t a ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool signA; + int_fast8_t expA; + uint_fast16_t sigA, uiZ; + struct exp8_sig16 normExpSig; + int_fast8_t expZ; + int index; + uint_fast16_t r0; + uint_fast32_t ESqrR0; + uint16_t sigma0; + uint_fast16_t recipSqrt16, sigZ, shiftedSigZ; + uint16_t negRem; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF16UI( uiA ); + expA = expF16UI( uiA ); + sigA = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x1F ) { + if ( sigA ) { + uiZ = softfloat_propagateNaNF16UI( uiA, 0 ); + goto uiZ; + } + if ( ! signA ) return a; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( signA ) { + if ( ! (expA | sigA) ) return a; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) return a; + normExpSig = softfloat_normSubnormalF16Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = ((expA - 0xF)>>1) + 0xE; + expA &= 1; + sigA |= 0x0400; + index = (sigA>>6 & 0xE) + expA; + r0 = softfloat_approxRecipSqrt_1k0s[index] + - (((uint_fast32_t) softfloat_approxRecipSqrt_1k1s[index] + * (sigA & 0x7F)) + >>11); + ESqrR0 = ((uint_fast32_t) r0 * r0)>>1; + if ( expA ) ESqrR0 >>= 1; + sigma0 = ~(uint_fast16_t) ((ESqrR0 * sigA)>>16); + recipSqrt16 = r0 + (((uint_fast32_t) r0 * sigma0)>>25); + if ( ! (recipSqrt16 & 0x8000) ) recipSqrt16 = 0x8000; + sigZ = ((uint_fast32_t) (sigA<<5) * recipSqrt16)>>16; + if ( expA ) sigZ >>= 1; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + ++sigZ; + if ( ! (sigZ & 7) ) { + shiftedSigZ = sigZ>>1; + negRem = shiftedSigZ * shiftedSigZ; + sigZ &= ~1; + if ( negRem & 0x8000 ) { + sigZ |= 1; + } else { + if ( negRem ) --sigZ; + } + } + return softfloat_roundPackToF16( 0, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF16UI; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f16_sqrt.c ****/ +/**** start inlining ../../source/f16_eq.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f16_eq( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + union ui16_f16 uB; + uint_fast16_t uiB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF16UI( uiA ) || isNaNF16UI( uiB ) ) { + if ( + softfloat_isSigNaNF16UI( uiA ) || softfloat_isSigNaNF16UI( uiB ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + return (uiA == uiB) || ! (uint16_t) ((uiA | uiB)<<1); + +} + +/**** ended inlining ../../source/f16_eq.c ****/ +/**** start inlining ../../source/f16_le.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f16_le( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + union ui16_f16 uB; + uint_fast16_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF16UI( uiA ) || isNaNF16UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signF16UI( uiA ); + signB = signF16UI( uiB ); + return + (signA != signB) ? signA || ! (uint16_t) ((uiA | uiB)<<1) + : (uiA == uiB) || (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f16_le.c ****/ +/**** start inlining ../../source/f16_lt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f16_lt( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + union ui16_f16 uB; + uint_fast16_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF16UI( uiA ) || isNaNF16UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signF16UI( uiA ); + signB = signF16UI( uiB ); + return + (signA != signB) ? signA && ((uint16_t) ((uiA | uiB)<<1) != 0) + : (uiA != uiB) && (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f16_lt.c ****/ +/**** start inlining ../../source/f16_eq_signaling.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f16_eq_signaling( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + union ui16_f16 uB; + uint_fast16_t uiB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF16UI( uiA ) || isNaNF16UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + return (uiA == uiB) || ! (uint16_t) ((uiA | uiB)<<1); + +} + +/**** ended inlining ../../source/f16_eq_signaling.c ****/ +/**** start inlining ../../source/f16_le_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f16_le_quiet( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + union ui16_f16 uB; + uint_fast16_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF16UI( uiA ) || isNaNF16UI( uiB ) ) { + if ( + softfloat_isSigNaNF16UI( uiA ) || softfloat_isSigNaNF16UI( uiB ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signF16UI( uiA ); + signB = signF16UI( uiB ); + return + (signA != signB) ? signA || ! (uint16_t) ((uiA | uiB)<<1) + : (uiA == uiB) || (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f16_le_quiet.c ****/ +/**** start inlining ../../source/f16_lt_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f16_lt_quiet( float16_t a, float16_t b ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + union ui16_f16 uB; + uint_fast16_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF16UI( uiA ) || isNaNF16UI( uiB ) ) { + if ( + softfloat_isSigNaNF16UI( uiA ) || softfloat_isSigNaNF16UI( uiB ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signF16UI( uiA ); + signB = signF16UI( uiB ); + return + (signA != signB) ? signA && ((uint16_t) ((uiA | uiB)<<1) != 0) + : (uiA != uiB) && (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f16_lt_quiet.c ****/ +/**** start inlining ../../source/f16_isSignalingNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f16_isSignalingNaN( float16_t a ) +{ + union ui16_f16 uA; + + uA.f = a; + return softfloat_isSigNaNF16UI( uA.ui ); + +} + +/**** ended inlining ../../source/f16_isSignalingNaN.c ****/ +/**** start inlining ../../source/f32_to_ui32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t f32_to_ui32( float32_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool sign; + int_fast16_t exp; + uint_fast32_t sig; + uint_fast64_t sig64; + int_fast16_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + sig = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (ui32_fromNaN != ui32_fromPosOverflow) || (ui32_fromNaN != ui32_fromNegOverflow) + if ( (exp == 0xFF) && sig ) { +#if (ui32_fromNaN == ui32_fromPosOverflow) + sign = 0; +#elif (ui32_fromNaN == ui32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return ui32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig |= 0x00800000; + sig64 = (uint_fast64_t) sig<<32; + shiftDist = 0xAA - exp; + if ( 0 < shiftDist ) sig64 = softfloat_shiftRightJam64( sig64, shiftDist ); + return softfloat_roundToUI32( sign, sig64, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f32_to_ui32.c ****/ +/**** start inlining ../../source/f32_to_ui64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t f32_to_ui64( float32_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool sign; + int_fast16_t exp; + uint_fast32_t sig; + int_fast16_t shiftDist; +#ifdef SOFTFLOAT_FAST_INT64 + uint_fast64_t sig64, extra; + struct uint64_extra sig64Extra; +#else + uint32_t extSig[3]; +#endif + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + sig = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0xBE - exp; + if ( shiftDist < 0 ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0xFF) && sig ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig |= 0x00800000; +#ifdef SOFTFLOAT_FAST_INT64 + sig64 = (uint_fast64_t) sig<<40; + extra = 0; + if ( shiftDist ) { + sig64Extra = softfloat_shiftRightJam64Extra( sig64, 0, shiftDist ); + sig64 = sig64Extra.v; + extra = sig64Extra.extra; + } + return softfloat_roundToUI64( sign, sig64, extra, roundingMode, exact ); +#else + extSig[indexWord( 3, 2 )] = sig<<8; + extSig[indexWord( 3, 1 )] = 0; + extSig[indexWord( 3, 0 )] = 0; + if ( shiftDist ) softfloat_shiftRightJam96M( extSig, shiftDist, extSig ); + return softfloat_roundMToUI64( sign, extSig, roundingMode, exact ); +#endif + +} + +/**** ended inlining ../../source/f32_to_ui64.c ****/ +/**** start inlining ../../source/f32_to_i32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t f32_to_i32( float32_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool sign; + int_fast16_t exp; + uint_fast32_t sig; + uint_fast64_t sig64; + int_fast16_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + sig = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (i32_fromNaN != i32_fromPosOverflow) || (i32_fromNaN != i32_fromNegOverflow) + if ( (exp == 0xFF) && sig ) { +#if (i32_fromNaN == i32_fromPosOverflow) + sign = 0; +#elif (i32_fromNaN == i32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return i32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig |= 0x00800000; + sig64 = (uint_fast64_t) sig<<32; + shiftDist = 0xAA - exp; + if ( 0 < shiftDist ) sig64 = softfloat_shiftRightJam64( sig64, shiftDist ); + return softfloat_roundToI32( sign, sig64, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f32_to_i32.c ****/ +/**** start inlining ../../source/f32_to_i64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t f32_to_i64( float32_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool sign; + int_fast16_t exp; + uint_fast32_t sig; + int_fast16_t shiftDist; +#ifdef SOFTFLOAT_FAST_INT64 + uint_fast64_t sig64, extra; + struct uint64_extra sig64Extra; +#else + uint32_t extSig[3]; +#endif + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + sig = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0xBE - exp; + if ( shiftDist < 0 ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0xFF) && sig ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig |= 0x00800000; +#ifdef SOFTFLOAT_FAST_INT64 + sig64 = (uint_fast64_t) sig<<40; + extra = 0; + if ( shiftDist ) { + sig64Extra = softfloat_shiftRightJam64Extra( sig64, 0, shiftDist ); + sig64 = sig64Extra.v; + extra = sig64Extra.extra; + } + return softfloat_roundToI64( sign, sig64, extra, roundingMode, exact ); +#else + extSig[indexWord( 3, 2 )] = sig<<8; + extSig[indexWord( 3, 1 )] = 0; + extSig[indexWord( 3, 0 )] = 0; + if ( shiftDist ) softfloat_shiftRightJam96M( extSig, shiftDist, extSig ); + return softfloat_roundMToI64( sign, extSig, roundingMode, exact ); +#endif + +} + +/**** ended inlining ../../source/f32_to_i64.c ****/ +/**** start inlining ../../source/f32_to_ui32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t f32_to_ui32_r_minMag( float32_t a, bool exact ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + int_fast16_t exp; + uint_fast32_t sig; + int_fast16_t shiftDist; + bool sign; + uint_fast32_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF32UI( uiA ); + sig = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x9E - exp; + if ( 32 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF32UI( uiA ); + if ( sign || (shiftDist < 0) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0xFF) && sig ? ui32_fromNaN + : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig = (sig | 0x00800000)<<8; + z = sig>>shiftDist; + if ( exact && (z< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t f32_to_ui64_r_minMag( float32_t a, bool exact ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + int_fast16_t exp; + uint_fast32_t sig; + int_fast16_t shiftDist; + bool sign; + uint_fast64_t sig64, z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF32UI( uiA ); + sig = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0xBE - exp; + if ( 64 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF32UI( uiA ); + if ( sign || (shiftDist < 0) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0xFF) && sig ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig |= 0x00800000; + sig64 = (uint_fast64_t) sig<<40; + z = sig64>>shiftDist; + shiftDist = 40 - shiftDist; + if ( exact && (shiftDist < 0) && (uint32_t) (sig<<(shiftDist & 31)) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return z; + +} + +/**** ended inlining ../../source/f32_to_ui64_r_minMag.c ****/ +/**** start inlining ../../source/f32_to_i32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t f32_to_i32_r_minMag( float32_t a, bool exact ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + int_fast16_t exp; + uint_fast32_t sig; + int_fast16_t shiftDist; + bool sign; + int_fast32_t absZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF32UI( uiA ); + sig = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x9E - exp; + if ( 32 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF32UI( uiA ); + if ( shiftDist <= 0 ) { + if ( uiA == packToF32UI( 1, 0x9E, 0 ) ) return -0x7FFFFFFF - 1; + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0xFF) && sig ? i32_fromNaN + : sign ? i32_fromNegOverflow : i32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig = (sig | 0x00800000)<<8; + absZ = sig>>shiftDist; + if ( exact && ((uint_fast32_t) absZ< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t f32_to_i64_r_minMag( float32_t a, bool exact ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + int_fast16_t exp; + uint_fast32_t sig; + int_fast16_t shiftDist; + bool sign; + uint_fast64_t sig64; + int_fast64_t absZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF32UI( uiA ); + sig = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0xBE - exp; + if ( 64 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF32UI( uiA ); + if ( shiftDist <= 0 ) { + if ( uiA == packToF32UI( 1, 0xBE, 0 ) ) { + return -INT64_C( 0x7FFFFFFFFFFFFFFF ) - 1; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0xFF) && sig ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig |= 0x00800000; + sig64 = (uint_fast64_t) sig<<40; + absZ = sig64>>shiftDist; + shiftDist = 40 - shiftDist; + if ( exact && (shiftDist < 0) && (uint32_t) (sig<<(shiftDist & 31)) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return sign ? -absZ : absZ; + +} + +/**** ended inlining ../../source/f32_to_i64_r_minMag.c ****/ +/**** start inlining ../../source/f32_to_f16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t f32_to_f16( float32_t a ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool sign; + int_fast16_t exp; + uint_fast32_t frac; + struct commonNaN commonNaN; + uint_fast16_t uiZ, frac16; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + frac = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0xFF ) { + if ( frac ) { + softfloat_f32UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF16UI( &commonNaN ); + } else { + uiZ = packToF16UI( sign, 0x1F, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac16 = frac>>9 | ((frac & 0x1FF) != 0); + if ( ! (exp | frac16) ) { + uiZ = packToF16UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + return softfloat_roundPackToF16( sign, exp - 0x71, frac16 | 0x4000 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f32_to_f16.c ****/ +/**** start inlining ../../source/f32_to_f64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f32_to_f64( float32_t a ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool sign; + int_fast16_t exp; + uint_fast32_t frac; + struct commonNaN commonNaN; + uint_fast64_t uiZ; + struct exp16_sig32 normExpSig; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + frac = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0xFF ) { + if ( frac ) { + softfloat_f32UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF64UI( &commonNaN ); + } else { + uiZ = packToF64UI( sign, 0x7FF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ = packToF64UI( sign, 0, 0 ); + goto uiZ; + } + normExpSig = softfloat_normSubnormalF32Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ = packToF64UI( sign, exp + 0x380, (uint_fast64_t) frac<<29 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f32_to_f64.c ****/ +/**** start inlining ../../source/f32_to_extF80.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t f32_to_extF80( float32_t a ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool sign; + int_fast16_t exp; + uint_fast32_t frac; + struct commonNaN commonNaN; + struct uint128 uiZ; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0; + struct exp16_sig32 normExpSig; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + frac = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0xFF ) { + if ( frac ) { + softfloat_f32UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToExtF80UI( &commonNaN ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + } else { + uiZ64 = packToExtF80UI64( sign, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ64 = packToExtF80UI64( sign, 0 ); + uiZ0 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF32Sig( frac ); + exp = normExpSig.exp; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ64 = packToExtF80UI64( sign, exp + 0x3F80 ); + uiZ0 = (uint_fast64_t) (frac | 0x00800000)<<40; + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/f32_to_extF80.c ****/ +/**** start inlining ../../source/f32_to_extF80M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void f32_to_extF80M( float32_t a, extFloat80_t *zPtr ) +{ + + *zPtr = f32_to_extF80( a ); + +} + +#else + +void f32_to_extF80M( float32_t a, extFloat80_t *zPtr ) +{ + struct extFloat80M *zSPtr; + union ui32_f32 uA; + uint32_t uiA; + bool sign; + int_fast16_t exp; + uint32_t frac; + struct commonNaN commonNaN; + uint_fast16_t uiZ64; + uint32_t uiZ32; + struct exp16_sig32 normExpSig; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zSPtr = (struct extFloat80M *) zPtr; + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + frac = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0xFF ) { + if ( frac ) { + softfloat_f32UIToCommonNaN( uiA, &commonNaN ); + softfloat_commonNaNToExtF80M( &commonNaN, zSPtr ); + return; + } + uiZ64 = packToExtF80UI64( sign, 0x7FFF ); + uiZ32 = 0x80000000; + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ64 = packToExtF80UI64( sign, 0 ); + uiZ32 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF32Sig( frac ); + exp = normExpSig.exp; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ64 = packToExtF80UI64( sign, exp + 0x3F80 ); + uiZ32 = 0x80000000 | (uint32_t) frac<<8; + uiZ: + zSPtr->signExp = uiZ64; + zSPtr->signif = (uint64_t) uiZ32<<32; + +} + +#endif + +/**** ended inlining ../../source/f32_to_extF80M.c ****/ +/**** start inlining ../../source/f32_to_f128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f32_to_f128( float32_t a ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool sign; + int_fast16_t exp; + uint_fast32_t frac; + struct commonNaN commonNaN; + struct uint128 uiZ; + struct exp16_sig32 normExpSig; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + frac = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0xFF ) { + if ( frac ) { + softfloat_f32UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF128UI( &commonNaN ); + } else { + uiZ.v64 = packToF128UI64( sign, 0x7FFF, 0 ); + uiZ.v0 = 0; + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ.v64 = packToF128UI64( sign, 0, 0 ); + uiZ.v0 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF32Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ.v64 = packToF128UI64( sign, exp + 0x3F80, (uint_fast64_t) frac<<25 ); + uiZ.v0 = 0; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f32_to_f128.c ****/ +/**** start inlining ../../source/f32_to_f128M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void f32_to_f128M( float32_t a, float128_t *zPtr ) +{ + + *zPtr = f32_to_f128( a ); + +} + +#else + +void f32_to_f128M( float32_t a, float128_t *zPtr ) +{ + uint32_t *zWPtr; + union ui32_f32 uA; + uint32_t uiA; + bool sign; + int_fast16_t exp; + uint32_t frac, uiZ64; + struct commonNaN commonNaN; + uint32_t uiZ96; + struct exp16_sig32 normExpSig; + uint64_t frac64; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zWPtr = (uint32_t *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF32UI( uiA ); + exp = expF32UI( uiA ); + frac = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ64 = 0; + if ( exp == 0xFF ) { + if ( frac ) { + softfloat_f32UIToCommonNaN( uiA, &commonNaN ); + softfloat_commonNaNToF128M( &commonNaN, zWPtr ); + return; + } + uiZ96 = packToF128UI96( sign, 0x7FFF, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ96 = packToF128UI96( sign, 0, 0 ); + goto uiZ; + } + normExpSig = softfloat_normSubnormalF32Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac64 = (uint64_t) frac<<25; + uiZ96 = packToF128UI96( sign, exp + 0x3F80, frac64>>32 ); + uiZ64 = frac64; + uiZ: + zWPtr[indexWord( 4, 3 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = uiZ64; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + +} + +#endif + +/**** ended inlining ../../source/f32_to_f128M.c ****/ +/**** start inlining ../../source/f32_roundToInt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f32_roundToInt( float32_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + int_fast16_t exp; + uint_fast32_t uiZ, lastBitMask, roundBitsMask; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp <= 0x7E ) { + if ( !(uint32_t) (uiA<<1) ) return a; + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + uiZ = uiA & packToF32UI( 1, 0, 0 ); + switch ( roundingMode ) { + case softfloat_round_near_even: + if ( !fracF32UI( uiA ) ) break; + case softfloat_round_near_maxMag: + if ( exp == 0x7E ) uiZ |= packToF32UI( 0, 0x7F, 0 ); + break; + case softfloat_round_min: + if ( uiZ ) uiZ = packToF32UI( 1, 0x7F, 0 ); + break; + case softfloat_round_max: + if ( !uiZ ) uiZ = packToF32UI( 0, 0x7F, 0 ); + break; +#ifdef SOFTFLOAT_ROUND_ODD + case softfloat_round_odd: + uiZ |= packToF32UI( 0, 0x7F, 0 ); + break; +#endif + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x96 <= exp ) { + if ( (exp == 0xFF) && fracF32UI( uiA ) ) { + uiZ = softfloat_propagateNaNF32UI( uiA, 0 ); + goto uiZ; + } + return a; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ = uiA; + lastBitMask = (uint_fast32_t) 1<<(0x96 - exp); + roundBitsMask = lastBitMask - 1; + if ( roundingMode == softfloat_round_near_maxMag ) { + uiZ += lastBitMask>>1; + } else if ( roundingMode == softfloat_round_near_even ) { + uiZ += lastBitMask>>1; + if ( !(uiZ & roundBitsMask) ) uiZ &= ~lastBitMask; + } else if ( + roundingMode + == (signF32UI( uiZ ) ? softfloat_round_min : softfloat_round_max) + ) { + uiZ += roundBitsMask; + } + uiZ &= ~roundBitsMask; + if ( uiZ != uiA ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) uiZ |= lastBitMask; +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f32_roundToInt.c ****/ +/**** start inlining ../../source/f32_add.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f32_add( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + union ui32_f32 uB; + uint_fast32_t uiB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 1) + float32_t (*magsFuncPtr)( uint_fast32_t, uint_fast32_t ); +#endif + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; +#if defined INLINE_LEVEL && (1 <= INLINE_LEVEL) + if ( signF32UI( uiA ^ uiB ) ) { + return softfloat_subMagsF32( uiA, uiB ); + } else { + return softfloat_addMagsF32( uiA, uiB ); + } +#else + magsFuncPtr = + signF32UI( uiA ^ uiB ) ? softfloat_subMagsF32 : softfloat_addMagsF32; + return (*magsFuncPtr)( uiA, uiB ); +#endif + +} + +/**** ended inlining ../../source/f32_add.c ****/ +/**** start inlining ../../source/f32_sub.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f32_sub( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + union ui32_f32 uB; + uint_fast32_t uiB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 1) + float32_t (*magsFuncPtr)( uint_fast32_t, uint_fast32_t ); +#endif + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; +#if defined INLINE_LEVEL && (1 <= INLINE_LEVEL) + if ( signF32UI( uiA ^ uiB ) ) { + return softfloat_addMagsF32( uiA, uiB ); + } else { + return softfloat_subMagsF32( uiA, uiB ); + } +#else + magsFuncPtr = + signF32UI( uiA ^ uiB ) ? softfloat_addMagsF32 : softfloat_subMagsF32; + return (*magsFuncPtr)( uiA, uiB ); +#endif + +} + +/**** ended inlining ../../source/f32_sub.c ****/ +/**** start inlining ../../source/f32_mul.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f32_mul( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool signA; + int_fast16_t expA; + uint_fast32_t sigA; + union ui32_f32 uB; + uint_fast32_t uiB; + bool signB; + int_fast16_t expB; + uint_fast32_t sigB; + bool signZ; + uint_fast32_t magBits; + struct exp16_sig32 normExpSig; + int_fast16_t expZ; + uint_fast32_t sigZ, uiZ; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF32UI( uiA ); + expA = expF32UI( uiA ); + sigA = fracF32UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF32UI( uiB ); + expB = expF32UI( uiB ); + sigB = fracF32UI( uiB ); + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0xFF ) { + if ( sigA || ((expB == 0xFF) && sigB) ) goto propagateNaN; + magBits = expB | sigB; + goto infArg; + } + if ( expB == 0xFF ) { + if ( sigB ) goto propagateNaN; + magBits = expA | sigA; + goto infArg; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalF32Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! sigB ) goto zero; + normExpSig = softfloat_normSubnormalF32Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x7F; + sigA = (sigA | 0x00800000)<<7; + sigB = (sigB | 0x00800000)<<8; + sigZ = softfloat_shortShiftRightJam64( (uint_fast64_t) sigA * sigB, 32 ); + if ( sigZ < 0x40000000 ) { + --expZ; + sigZ <<= 1; + } + return softfloat_roundPackToF32( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF32UI( uiA, uiB ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infArg: + if ( ! magBits ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF32UI; + } else { + uiZ = packToF32UI( signZ, 0xFF, 0 ); + } + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ = packToF32UI( signZ, 0, 0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f32_mul.c ****/ +/**** start inlining ../../source/f32_mulAdd.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f32_mulAdd( float32_t a, float32_t b, float32_t c ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + union ui32_f32 uB; + uint_fast32_t uiB; + union ui32_f32 uC; + uint_fast32_t uiC; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + uC.f = c; + uiC = uC.ui; + return softfloat_mulAddF32( uiA, uiB, uiC, 0 ); + +} + +/**** ended inlining ../../source/f32_mulAdd.c ****/ +/**** start inlining ../../source/f32_div.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f32_div( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool signA; + int_fast16_t expA; + uint_fast32_t sigA; + union ui32_f32 uB; + uint_fast32_t uiB; + bool signB; + int_fast16_t expB; + uint_fast32_t sigB; + bool signZ; + struct exp16_sig32 normExpSig; + int_fast16_t expZ; +#ifdef SOFTFLOAT_FAST_DIV64TO32 + uint_fast64_t sig64A; + uint_fast32_t sigZ; +#else + uint_fast32_t sigZ; + uint_fast64_t rem; +#endif + uint_fast32_t uiZ; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF32UI( uiA ); + expA = expF32UI( uiA ); + sigA = fracF32UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF32UI( uiB ); + expB = expF32UI( uiB ); + sigB = fracF32UI( uiB ); + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0xFF ) { + if ( sigA ) goto propagateNaN; + if ( expB == 0xFF ) { + if ( sigB ) goto propagateNaN; + goto invalid; + } + goto infinity; + } + if ( expB == 0xFF ) { + if ( sigB ) goto propagateNaN; + goto zero; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) { + if ( ! sigB ) { + if ( ! (expA | sigA) ) goto invalid; + softfloat_raiseFlags( softfloat_flag_infinite ); + goto infinity; + } + normExpSig = softfloat_normSubnormalF32Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalF32Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA - expB + 0x7E; + sigA |= 0x00800000; + sigB |= 0x00800000; +#ifdef SOFTFLOAT_FAST_DIV64TO32 + if ( sigA < sigB ) { + --expZ; + sig64A = (uint_fast64_t) sigA<<31; + } else { + sig64A = (uint_fast64_t) sigA<<30; + } + sigZ = sig64A / sigB; + if ( ! (sigZ & 0x3F) ) sigZ |= ((uint_fast64_t) sigB * sigZ != sig64A); +#else + if ( sigA < sigB ) { + --expZ; + sigA <<= 8; + } else { + sigA <<= 7; + } + sigB <<= 8; + sigZ = ((uint_fast64_t) sigA * softfloat_approxRecip32_1( sigB ))>>32; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sigZ += 2; + if ( (sigZ & 0x3F) < 2 ) { + sigZ &= ~3; +#ifdef SOFTFLOAT_FAST_INT64 + rem = ((uint_fast64_t) sigA<<31) - (uint_fast64_t) sigZ * sigB; +#else + rem = ((uint_fast64_t) sigA<<32) - (uint_fast64_t) (sigZ<<1) * sigB; +#endif + if ( rem & UINT64_C( 0x8000000000000000 ) ) { + sigZ -= 4; + } else { + if ( rem ) sigZ |= 1; + } + } +#endif + return softfloat_roundPackToF32( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF32UI( uiA, uiB ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF32UI; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infinity: + uiZ = packToF32UI( signZ, 0xFF, 0 ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ = packToF32UI( signZ, 0, 0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f32_div.c ****/ +/**** start inlining ../../source/f32_rem.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f32_rem( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool signA; + int_fast16_t expA; + uint_fast32_t sigA; + union ui32_f32 uB; + uint_fast32_t uiB; + int_fast16_t expB; + uint_fast32_t sigB; + struct exp16_sig32 normExpSig; + uint32_t rem; + int_fast16_t expDiff; + uint32_t q, recip32, altRem, meanRem; + bool signRem; + uint_fast32_t uiZ; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF32UI( uiA ); + expA = expF32UI( uiA ); + sigA = fracF32UI( uiA ); + uB.f = b; + uiB = uB.ui; + expB = expF32UI( uiB ); + sigB = fracF32UI( uiB ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0xFF ) { + if ( sigA || ((expB == 0xFF) && sigB) ) goto propagateNaN; + goto invalid; + } + if ( expB == 0xFF ) { + if ( sigB ) goto propagateNaN; + return a; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) { + if ( ! sigB ) goto invalid; + normExpSig = softfloat_normSubnormalF32Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) { + if ( ! sigA ) return a; + normExpSig = softfloat_normSubnormalF32Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + rem = sigA | 0x00800000; + sigB |= 0x00800000; + expDiff = expA - expB; + if ( expDiff < 1 ) { + if ( expDiff < -1 ) return a; + sigB <<= 6; + if ( expDiff ) { + rem <<= 5; + q = 0; + } else { + rem <<= 6; + q = (sigB <= rem); + if ( q ) rem -= sigB; + } + } else { + recip32 = softfloat_approxRecip32_1( sigB<<8 ); + /*-------------------------------------------------------------------- + | Changing the shift of `rem' here requires also changing the initial + | subtraction from `expDiff'. + *--------------------------------------------------------------------*/ + rem <<= 7; + expDiff -= 31; + /*-------------------------------------------------------------------- + | The scale of `sigB' affects how many bits are obtained during each + | cycle of the loop. Currently this is 29 bits per loop iteration, + | which is believed to be the maximum possible. + *--------------------------------------------------------------------*/ + sigB <<= 6; + for (;;) { + q = (rem * (uint_fast64_t) recip32)>>32; + if ( expDiff < 0 ) break; + rem = -(q * (uint32_t) sigB); + expDiff -= 29; + } + /*-------------------------------------------------------------------- + | (`expDiff' cannot be less than -30 here.) + *--------------------------------------------------------------------*/ + q >>= ~expDiff & 31; + rem = (rem<<(expDiff + 30)) - q * (uint32_t) sigB; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + do { + altRem = rem; + ++q; + rem -= sigB; + } while ( ! (rem & 0x80000000) ); + meanRem = rem + altRem; + if ( (meanRem & 0x80000000) || (! meanRem && (q & 1)) ) rem = altRem; + signRem = signA; + if ( 0x80000000 <= rem ) { + signRem = ! signRem; + rem = -rem; + } + return softfloat_normRoundPackToF32( signRem, expB, rem ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF32UI( uiA, uiB ); + goto uiZ; + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF32UI; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f32_rem.c ****/ +/**** start inlining ../../source/f32_sqrt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f32_sqrt( float32_t a ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool signA; + int_fast16_t expA; + uint_fast32_t sigA, uiZ; + struct exp16_sig32 normExpSig; + int_fast16_t expZ; + uint_fast32_t sigZ, shiftedSigZ; + uint32_t negRem; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF32UI( uiA ); + expA = expF32UI( uiA ); + sigA = fracF32UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0xFF ) { + if ( sigA ) { + uiZ = softfloat_propagateNaNF32UI( uiA, 0 ); + goto uiZ; + } + if ( ! signA ) return a; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( signA ) { + if ( ! (expA | sigA) ) return a; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) return a; + normExpSig = softfloat_normSubnormalF32Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = ((expA - 0x7F)>>1) + 0x7E; + expA &= 1; + sigA = (sigA | 0x00800000)<<8; + sigZ = + ((uint_fast64_t) sigA * softfloat_approxRecipSqrt32_1( expA, sigA )) + >>32; + if ( expA ) sigZ >>= 1; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sigZ += 2; + if ( (sigZ & 0x3F) < 2 ) { + shiftedSigZ = sigZ>>2; + negRem = shiftedSigZ * shiftedSigZ; + sigZ &= ~3; + if ( negRem & 0x80000000 ) { + sigZ |= 1; + } else { + if ( negRem ) --sigZ; + } + } + return softfloat_roundPackToF32( 0, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF32UI; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f32_sqrt.c ****/ +/**** start inlining ../../source/f32_eq.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f32_eq( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + union ui32_f32 uB; + uint_fast32_t uiB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF32UI( uiA ) || isNaNF32UI( uiB ) ) { + if ( + softfloat_isSigNaNF32UI( uiA ) || softfloat_isSigNaNF32UI( uiB ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + return (uiA == uiB) || ! (uint32_t) ((uiA | uiB)<<1); + +} + +/**** ended inlining ../../source/f32_eq.c ****/ +/**** start inlining ../../source/f32_le.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f32_le( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + union ui32_f32 uB; + uint_fast32_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF32UI( uiA ) || isNaNF32UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signF32UI( uiA ); + signB = signF32UI( uiB ); + return + (signA != signB) ? signA || ! (uint32_t) ((uiA | uiB)<<1) + : (uiA == uiB) || (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f32_le.c ****/ +/**** start inlining ../../source/f32_lt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f32_lt( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + union ui32_f32 uB; + uint_fast32_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF32UI( uiA ) || isNaNF32UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signF32UI( uiA ); + signB = signF32UI( uiB ); + return + (signA != signB) ? signA && ((uint32_t) ((uiA | uiB)<<1) != 0) + : (uiA != uiB) && (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f32_lt.c ****/ +/**** start inlining ../../source/f32_eq_signaling.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f32_eq_signaling( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + union ui32_f32 uB; + uint_fast32_t uiB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF32UI( uiA ) || isNaNF32UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + return (uiA == uiB) || ! (uint32_t) ((uiA | uiB)<<1); + +} + +/**** ended inlining ../../source/f32_eq_signaling.c ****/ +/**** start inlining ../../source/f32_le_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f32_le_quiet( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + union ui32_f32 uB; + uint_fast32_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF32UI( uiA ) || isNaNF32UI( uiB ) ) { + if ( + softfloat_isSigNaNF32UI( uiA ) || softfloat_isSigNaNF32UI( uiB ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signF32UI( uiA ); + signB = signF32UI( uiB ); + return + (signA != signB) ? signA || ! (uint32_t) ((uiA | uiB)<<1) + : (uiA == uiB) || (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f32_le_quiet.c ****/ +/**** start inlining ../../source/f32_lt_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f32_lt_quiet( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + union ui32_f32 uB; + uint_fast32_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF32UI( uiA ) || isNaNF32UI( uiB ) ) { + if ( + softfloat_isSigNaNF32UI( uiA ) || softfloat_isSigNaNF32UI( uiB ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signF32UI( uiA ); + signB = signF32UI( uiB ); + return + (signA != signB) ? signA && ((uint32_t) ((uiA | uiB)<<1) != 0) + : (uiA != uiB) && (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f32_lt_quiet.c ****/ +/**** start inlining ../../source/f32_isSignalingNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f32_isSignalingNaN( float32_t a ) +{ + union ui32_f32 uA; + + uA.f = a; + return softfloat_isSigNaNF32UI( uA.ui ); + +} + +/**** ended inlining ../../source/f32_isSignalingNaN.c ****/ +/**** start inlining ../../source/f64_to_ui32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t f64_to_ui32( float64_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool sign; + int_fast16_t exp; + uint_fast64_t sig; + int_fast16_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + sig = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (ui32_fromNaN != ui32_fromPosOverflow) || (ui32_fromNaN != ui32_fromNegOverflow) + if ( (exp == 0x7FF) && sig ) { +#if (ui32_fromNaN == ui32_fromPosOverflow) + sign = 0; +#elif (ui32_fromNaN == ui32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return ui32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig |= UINT64_C( 0x0010000000000000 ); + shiftDist = 0x427 - exp; + if ( 0 < shiftDist ) sig = softfloat_shiftRightJam64( sig, shiftDist ); + return softfloat_roundToUI32( sign, sig, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f64_to_ui32.c ****/ +/**** start inlining ../../source/f64_to_ui64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t f64_to_ui64( float64_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool sign; + int_fast16_t exp; + uint_fast64_t sig; + int_fast16_t shiftDist; +#ifdef SOFTFLOAT_FAST_INT64 + struct uint64_extra sigExtra; +#else + uint32_t extSig[3]; +#endif + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + sig = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig |= UINT64_C( 0x0010000000000000 ); + shiftDist = 0x433 - exp; +#ifdef SOFTFLOAT_FAST_INT64 + if ( shiftDist <= 0 ) { + if ( shiftDist < -11 ) goto invalid; + sigExtra.v = sig<<-shiftDist; + sigExtra.extra = 0; + } else { + sigExtra = softfloat_shiftRightJam64Extra( sig, 0, shiftDist ); + } + return + softfloat_roundToUI64( + sign, sigExtra.v, sigExtra.extra, roundingMode, exact ); +#else + extSig[indexWord( 3, 0 )] = 0; + if ( shiftDist <= 0 ) { + if ( shiftDist < -11 ) goto invalid; + sig <<= -shiftDist; + extSig[indexWord( 3, 2 )] = sig>>32; + extSig[indexWord( 3, 1 )] = sig; + } else { + extSig[indexWord( 3, 2 )] = sig>>32; + extSig[indexWord( 3, 1 )] = sig; + softfloat_shiftRightJam96M( extSig, shiftDist, extSig ); + } + return softfloat_roundMToUI64( sign, extSig, roundingMode, exact ); +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FF) && fracF64UI( uiA ) ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + +} + +/**** ended inlining ../../source/f64_to_ui64.c ****/ +/**** start inlining ../../source/f64_to_i32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t f64_to_i32( float64_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool sign; + int_fast16_t exp; + uint_fast64_t sig; + int_fast16_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + sig = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (i32_fromNaN != i32_fromPosOverflow) || (i32_fromNaN != i32_fromNegOverflow) + if ( (exp == 0x7FF) && sig ) { +#if (i32_fromNaN == i32_fromPosOverflow) + sign = 0; +#elif (i32_fromNaN == i32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return i32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig |= UINT64_C( 0x0010000000000000 ); + shiftDist = 0x427 - exp; + if ( 0 < shiftDist ) sig = softfloat_shiftRightJam64( sig, shiftDist ); + return softfloat_roundToI32( sign, sig, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f64_to_i32.c ****/ +/**** start inlining ../../source/f64_to_i64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t f64_to_i64( float64_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool sign; + int_fast16_t exp; + uint_fast64_t sig; + int_fast16_t shiftDist; +#ifdef SOFTFLOAT_FAST_INT64 + struct uint64_extra sigExtra; +#else + uint32_t extSig[3]; +#endif + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + sig = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig |= UINT64_C( 0x0010000000000000 ); + shiftDist = 0x433 - exp; +#ifdef SOFTFLOAT_FAST_INT64 + if ( shiftDist <= 0 ) { + if ( shiftDist < -11 ) goto invalid; + sigExtra.v = sig<<-shiftDist; + sigExtra.extra = 0; + } else { + sigExtra = softfloat_shiftRightJam64Extra( sig, 0, shiftDist ); + } + return + softfloat_roundToI64( + sign, sigExtra.v, sigExtra.extra, roundingMode, exact ); +#else + extSig[indexWord( 3, 0 )] = 0; + if ( shiftDist <= 0 ) { + if ( shiftDist < -11 ) goto invalid; + sig <<= -shiftDist; + extSig[indexWord( 3, 2 )] = sig>>32; + extSig[indexWord( 3, 1 )] = sig; + } else { + extSig[indexWord( 3, 2 )] = sig>>32; + extSig[indexWord( 3, 1 )] = sig; + softfloat_shiftRightJam96M( extSig, shiftDist, extSig ); + } + return softfloat_roundMToI64( sign, extSig, roundingMode, exact ); +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FF) && fracF64UI( uiA ) ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + +} + +/**** ended inlining ../../source/f64_to_i64.c ****/ +/**** start inlining ../../source/f64_to_ui32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t f64_to_ui32_r_minMag( float64_t a, bool exact ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + int_fast16_t exp; + uint_fast64_t sig; + int_fast16_t shiftDist; + bool sign; + uint_fast32_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF64UI( uiA ); + sig = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x433 - exp; + if ( 53 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF64UI( uiA ); + if ( sign || (shiftDist < 21) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FF) && sig ? ui32_fromNaN + : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig |= UINT64_C( 0x0010000000000000 ); + z = sig>>shiftDist; + if ( exact && ((uint_fast64_t) z< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t f64_to_ui64_r_minMag( float64_t a, bool exact ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + int_fast16_t exp; + uint_fast64_t sig; + int_fast16_t shiftDist; + bool sign; + uint_fast64_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF64UI( uiA ); + sig = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x433 - exp; + if ( 53 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF64UI( uiA ); + if ( sign ) goto invalid; + if ( shiftDist <= 0 ) { + if ( shiftDist < -11 ) goto invalid; + z = (sig | UINT64_C( 0x0010000000000000 ))<<-shiftDist; + } else { + sig |= UINT64_C( 0x0010000000000000 ); + z = sig>>shiftDist; + if ( exact && (uint64_t) (sig<<(-shiftDist & 63)) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + } + return z; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FF) && sig ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + +} + +/**** ended inlining ../../source/f64_to_ui64_r_minMag.c ****/ +/**** start inlining ../../source/f64_to_i32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t f64_to_i32_r_minMag( float64_t a, bool exact ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + int_fast16_t exp; + uint_fast64_t sig; + int_fast16_t shiftDist; + bool sign; + int_fast32_t absZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF64UI( uiA ); + sig = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x433 - exp; + if ( 53 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF64UI( uiA ); + if ( shiftDist < 22 ) { + if ( + sign && (exp == 0x41E) && (sig < UINT64_C( 0x0000000000200000 )) + ) { + if ( exact && sig ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return -0x7FFFFFFF - 1; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FF) && sig ? i32_fromNaN + : sign ? i32_fromNegOverflow : i32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig |= UINT64_C( 0x0010000000000000 ); + absZ = sig>>shiftDist; + if ( exact && ((uint_fast64_t) (uint_fast32_t) absZ< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t f64_to_i64_r_minMag( float64_t a, bool exact ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool sign; + int_fast16_t exp; + uint_fast64_t sig; + int_fast16_t shiftDist; + int_fast64_t absZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + sig = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x433 - exp; + if ( shiftDist <= 0 ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( shiftDist < -10 ) { + if ( uiA == packToF64UI( 1, 0x43E, 0 ) ) { + return -INT64_C( 0x7FFFFFFFFFFFFFFF ) - 1; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FF) && sig ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sig |= UINT64_C( 0x0010000000000000 ); + absZ = sig<<-shiftDist; + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( 53 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sig |= UINT64_C( 0x0010000000000000 ); + absZ = sig>>shiftDist; + if ( exact && (absZ< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t f64_to_f16( float64_t a ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool sign; + int_fast16_t exp; + uint_fast64_t frac; + struct commonNaN commonNaN; + uint_fast16_t uiZ, frac16; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + frac = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FF ) { + if ( frac ) { + softfloat_f64UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF16UI( &commonNaN ); + } else { + uiZ = packToF16UI( sign, 0x1F, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac16 = softfloat_shortShiftRightJam64( frac, 38 ); + if ( ! (exp | frac16) ) { + uiZ = packToF16UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + return softfloat_roundPackToF16( sign, exp - 0x3F1, frac16 | 0x4000 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f64_to_f16.c ****/ +/**** start inlining ../../source/f64_to_f32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f64_to_f32( float64_t a ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool sign; + int_fast16_t exp; + uint_fast64_t frac; + struct commonNaN commonNaN; + uint_fast32_t uiZ, frac32; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + frac = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FF ) { + if ( frac ) { + softfloat_f64UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF32UI( &commonNaN ); + } else { + uiZ = packToF32UI( sign, 0xFF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac32 = softfloat_shortShiftRightJam64( frac, 22 ); + if ( ! (exp | frac32) ) { + uiZ = packToF32UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + return softfloat_roundPackToF32( sign, exp - 0x381, frac32 | 0x40000000 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f64_to_f32.c ****/ +/**** start inlining ../../source/f64_to_extF80.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t f64_to_extF80( float64_t a ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool sign; + int_fast16_t exp; + uint_fast64_t frac; + struct commonNaN commonNaN; + struct uint128 uiZ; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0; + struct exp16_sig64 normExpSig; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + frac = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FF ) { + if ( frac ) { + softfloat_f64UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToExtF80UI( &commonNaN ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + } else { + uiZ64 = packToExtF80UI64( sign, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ64 = packToExtF80UI64( sign, 0 ); + uiZ0 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF64Sig( frac ); + exp = normExpSig.exp; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ64 = packToExtF80UI64( sign, exp + 0x3C00 ); + uiZ0 = (frac | UINT64_C( 0x0010000000000000 ))<<11; + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/f64_to_extF80.c ****/ +/**** start inlining ../../source/f64_to_extF80M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void f64_to_extF80M( float64_t a, extFloat80_t *zPtr ) +{ + + *zPtr = f64_to_extF80( a ); + +} + +#else + +void f64_to_extF80M( float64_t a, extFloat80_t *zPtr ) +{ + struct extFloat80M *zSPtr; + union ui64_f64 uA; + uint64_t uiA; + bool sign; + int_fast16_t exp; + uint64_t frac; + struct commonNaN commonNaN; + uint_fast16_t uiZ64; + uint64_t uiZ0; + struct exp16_sig64 normExpSig; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zSPtr = (struct extFloat80M *) zPtr; + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + frac = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FF ) { + if ( frac ) { + softfloat_f64UIToCommonNaN( uiA, &commonNaN ); + softfloat_commonNaNToExtF80M( &commonNaN, zSPtr ); + return; + } + uiZ64 = packToExtF80UI64( sign, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ64 = packToExtF80UI64( sign, 0 ); + uiZ0 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF64Sig( frac ); + exp = normExpSig.exp; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ64 = packToExtF80UI64( sign, exp + 0x3C00 ); + uiZ0 = UINT64_C( 0x8000000000000000 ) | frac<<11; + uiZ: + zSPtr->signExp = uiZ64; + zSPtr->signif = uiZ0; + +} + +#endif + +/**** ended inlining ../../source/f64_to_extF80M.c ****/ +/**** start inlining ../../source/f64_to_f128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f64_to_f128( float64_t a ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool sign; + int_fast16_t exp; + uint_fast64_t frac; + struct commonNaN commonNaN; + struct uint128 uiZ; + struct exp16_sig64 normExpSig; + struct uint128 frac128; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + frac = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FF ) { + if ( frac ) { + softfloat_f64UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF128UI( &commonNaN ); + } else { + uiZ.v64 = packToF128UI64( sign, 0x7FFF, 0 ); + uiZ.v0 = 0; + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ.v64 = packToF128UI64( sign, 0, 0 ); + uiZ.v0 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF64Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac128 = softfloat_shortShiftLeft128( 0, frac, 60 ); + uiZ.v64 = packToF128UI64( sign, exp + 0x3C00, frac128.v64 ); + uiZ.v0 = frac128.v0; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f64_to_f128.c ****/ +/**** start inlining ../../source/f64_to_f128M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void f64_to_f128M( float64_t a, float128_t *zPtr ) +{ + + *zPtr = f64_to_f128( a ); + +} + +#else + +void f64_to_f128M( float64_t a, float128_t *zPtr ) +{ + uint32_t *zWPtr; + union ui64_f64 uA; + uint64_t uiA; + bool sign; + int_fast16_t exp; + uint64_t frac; + struct commonNaN commonNaN; + uint32_t uiZ96; + struct exp16_sig64 normExpSig; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zWPtr = (uint32_t *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF64UI( uiA ); + exp = expF64UI( uiA ); + frac = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zWPtr[indexWord( 4, 0 )] = 0; + if ( exp == 0x7FF ) { + if ( frac ) { + softfloat_f64UIToCommonNaN( uiA, &commonNaN ); + softfloat_commonNaNToF128M( &commonNaN, zWPtr ); + return; + } + uiZ96 = packToF128UI96( sign, 0x7FFF, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ96 = packToF128UI96( sign, 0, 0 ); + goto uiZ; + } + normExpSig = softfloat_normSubnormalF64Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zWPtr[indexWord( 4, 1 )] = (uint32_t) frac<<28; + frac >>= 4; + zWPtr[indexWordHi( 4 )] = packToF128UI96( sign, exp + 0x3C00, frac>>32 ); + zWPtr[indexWord( 4, 2 )] = frac; + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + zWPtr[indexWord( 4, 3 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = 0; + zWPtr[indexWord( 4, 1 )] = 0; + +} + +#endif + +/**** ended inlining ../../source/f64_to_f128M.c ****/ +/**** start inlining ../../source/f64_roundToInt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f64_roundToInt( float64_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + int_fast16_t exp; + uint_fast64_t uiZ, lastBitMask, roundBitsMask; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + exp = expF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp <= 0x3FE ) { + if ( !(uiA & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ) return a; + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + uiZ = uiA & packToF64UI( 1, 0, 0 ); + switch ( roundingMode ) { + case softfloat_round_near_even: + if ( !fracF64UI( uiA ) ) break; + case softfloat_round_near_maxMag: + if ( exp == 0x3FE ) uiZ |= packToF64UI( 0, 0x3FF, 0 ); + break; + case softfloat_round_min: + if ( uiZ ) uiZ = packToF64UI( 1, 0x3FF, 0 ); + break; + case softfloat_round_max: + if ( !uiZ ) uiZ = packToF64UI( 0, 0x3FF, 0 ); + break; +#ifdef SOFTFLOAT_ROUND_ODD + case softfloat_round_odd: + uiZ |= packToF64UI( 0, 0x3FF, 0 ); + break; +#endif + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x433 <= exp ) { + if ( (exp == 0x7FF) && fracF64UI( uiA ) ) { + uiZ = softfloat_propagateNaNF64UI( uiA, 0 ); + goto uiZ; + } + return a; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ = uiA; + lastBitMask = (uint_fast64_t) 1<<(0x433 - exp); + roundBitsMask = lastBitMask - 1; + if ( roundingMode == softfloat_round_near_maxMag ) { + uiZ += lastBitMask>>1; + } else if ( roundingMode == softfloat_round_near_even ) { + uiZ += lastBitMask>>1; + if ( !(uiZ & roundBitsMask) ) uiZ &= ~lastBitMask; + } else if ( + roundingMode + == (signF64UI( uiZ ) ? softfloat_round_min : softfloat_round_max) + ) { + uiZ += roundBitsMask; + } + uiZ &= ~roundBitsMask; + if ( uiZ != uiA ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) uiZ |= lastBitMask; +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f64_roundToInt.c ****/ +/**** start inlining ../../source/f64_add.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f64_add( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool signA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + float64_t (*magsFuncPtr)( uint_fast64_t, uint_fast64_t, bool ); +#endif + + uA.f = a; + uiA = uA.ui; + signA = signF64UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF64UI( uiB ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + return softfloat_addMagsF64( uiA, uiB, signA ); + } else { + return softfloat_subMagsF64( uiA, uiB, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_addMagsF64 : softfloat_subMagsF64; + return (*magsFuncPtr)( uiA, uiB, signA ); +#endif + +} + +/**** ended inlining ../../source/f64_add.c ****/ +/**** start inlining ../../source/f64_sub.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f64_sub( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool signA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + float64_t (*magsFuncPtr)( uint_fast64_t, uint_fast64_t, bool ); +#endif + + uA.f = a; + uiA = uA.ui; + signA = signF64UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF64UI( uiB ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + return softfloat_subMagsF64( uiA, uiB, signA ); + } else { + return softfloat_addMagsF64( uiA, uiB, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_subMagsF64 : softfloat_addMagsF64; + return (*magsFuncPtr)( uiA, uiB, signA ); +#endif + +} + +/**** ended inlining ../../source/f64_sub.c ****/ +/**** start inlining ../../source/f64_mul.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f64_mul( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool signA; + int_fast16_t expA; + uint_fast64_t sigA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signB; + int_fast16_t expB; + uint_fast64_t sigB; + bool signZ; + uint_fast64_t magBits; + struct exp16_sig64 normExpSig; + int_fast16_t expZ; +#ifdef SOFTFLOAT_FAST_INT64 + struct uint128 sig128Z; +#else + uint32_t sig128Z[4]; +#endif + uint_fast64_t sigZ, uiZ; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF64UI( uiA ); + expA = expF64UI( uiA ); + sigA = fracF64UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF64UI( uiB ); + expB = expF64UI( uiB ); + sigB = fracF64UI( uiB ); + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FF ) { + if ( sigA || ((expB == 0x7FF) && sigB) ) goto propagateNaN; + magBits = expB | sigB; + goto infArg; + } + if ( expB == 0x7FF ) { + if ( sigB ) goto propagateNaN; + magBits = expA | sigA; + goto infArg; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalF64Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! sigB ) goto zero; + normExpSig = softfloat_normSubnormalF64Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x3FF; + sigA = (sigA | UINT64_C( 0x0010000000000000 ))<<10; + sigB = (sigB | UINT64_C( 0x0010000000000000 ))<<11; +#ifdef SOFTFLOAT_FAST_INT64 + sig128Z = softfloat_mul64To128( sigA, sigB ); + sigZ = sig128Z.v64 | (sig128Z.v0 != 0); +#else + softfloat_mul64To128M( sigA, sigB, sig128Z ); + sigZ = + (uint64_t) sig128Z[indexWord( 4, 3 )]<<32 | sig128Z[indexWord( 4, 2 )]; + if ( sig128Z[indexWord( 4, 1 )] || sig128Z[indexWord( 4, 0 )] ) sigZ |= 1; +#endif + if ( sigZ < UINT64_C( 0x4000000000000000 ) ) { + --expZ; + sigZ <<= 1; + } + return softfloat_roundPackToF64( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF64UI( uiA, uiB ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infArg: + if ( ! magBits ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF64UI; + } else { + uiZ = packToF64UI( signZ, 0x7FF, 0 ); + } + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ = packToF64UI( signZ, 0, 0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f64_mul.c ****/ +/**** start inlining ../../source/f64_mulAdd.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f64_mulAdd( float64_t a, float64_t b, float64_t c ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + union ui64_f64 uB; + uint_fast64_t uiB; + union ui64_f64 uC; + uint_fast64_t uiC; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + uC.f = c; + uiC = uC.ui; + return softfloat_mulAddF64( uiA, uiB, uiC, 0 ); + +} + +/**** ended inlining ../../source/f64_mulAdd.c ****/ +/**** start inlining ../../source/f64_div.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f64_div( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool signA; + int_fast16_t expA; + uint_fast64_t sigA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signB; + int_fast16_t expB; + uint_fast64_t sigB; + bool signZ; + struct exp16_sig64 normExpSig; + int_fast16_t expZ; + uint32_t recip32, sig32Z, doubleTerm; + uint_fast64_t rem; + uint32_t q; + uint_fast64_t sigZ; + uint_fast64_t uiZ; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF64UI( uiA ); + expA = expF64UI( uiA ); + sigA = fracF64UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF64UI( uiB ); + expB = expF64UI( uiB ); + sigB = fracF64UI( uiB ); + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FF ) { + if ( sigA ) goto propagateNaN; + if ( expB == 0x7FF ) { + if ( sigB ) goto propagateNaN; + goto invalid; + } + goto infinity; + } + if ( expB == 0x7FF ) { + if ( sigB ) goto propagateNaN; + goto zero; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) { + if ( ! sigB ) { + if ( ! (expA | sigA) ) goto invalid; + softfloat_raiseFlags( softfloat_flag_infinite ); + goto infinity; + } + normExpSig = softfloat_normSubnormalF64Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalF64Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA - expB + 0x3FE; + sigA |= UINT64_C( 0x0010000000000000 ); + sigB |= UINT64_C( 0x0010000000000000 ); + if ( sigA < sigB ) { + --expZ; + sigA <<= 11; + } else { + sigA <<= 10; + } + sigB <<= 11; + recip32 = softfloat_approxRecip32_1( sigB>>32 ) - 2; + sig32Z = ((uint32_t) (sigA>>32) * (uint_fast64_t) recip32)>>32; + doubleTerm = sig32Z<<1; + rem = + ((sigA - (uint_fast64_t) doubleTerm * (uint32_t) (sigB>>32))<<28) + - (uint_fast64_t) doubleTerm * ((uint32_t) sigB>>4); + q = (((uint32_t) (rem>>32) * (uint_fast64_t) recip32)>>32) + 4; + sigZ = ((uint_fast64_t) sig32Z<<32) + ((uint_fast64_t) q<<4); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (sigZ & 0x1FF) < 4<<4 ) { + q &= ~7; + sigZ &= ~(uint_fast64_t) 0x7F; + doubleTerm = q<<1; + rem = + ((rem - (uint_fast64_t) doubleTerm * (uint32_t) (sigB>>32))<<28) + - (uint_fast64_t) doubleTerm * ((uint32_t) sigB>>4); + if ( rem & UINT64_C( 0x8000000000000000 ) ) { + sigZ -= 1<<7; + } else { + if ( rem ) sigZ |= 1; + } + } + return softfloat_roundPackToF64( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF64UI( uiA, uiB ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF64UI; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infinity: + uiZ = packToF64UI( signZ, 0x7FF, 0 ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ = packToF64UI( signZ, 0, 0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f64_div.c ****/ +/**** start inlining ../../source/f64_rem.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f64_rem( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool signA; + int_fast16_t expA; + uint_fast64_t sigA; + union ui64_f64 uB; + uint_fast64_t uiB; + int_fast16_t expB; + uint_fast64_t sigB; + struct exp16_sig64 normExpSig; + uint64_t rem; + int_fast16_t expDiff; + uint32_t q, recip32; + uint_fast64_t q64; + uint64_t altRem, meanRem; + bool signRem; + uint_fast64_t uiZ; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF64UI( uiA ); + expA = expF64UI( uiA ); + sigA = fracF64UI( uiA ); + uB.f = b; + uiB = uB.ui; + expB = expF64UI( uiB ); + sigB = fracF64UI( uiB ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FF ) { + if ( sigA || ((expB == 0x7FF) && sigB) ) goto propagateNaN; + goto invalid; + } + if ( expB == 0x7FF ) { + if ( sigB ) goto propagateNaN; + return a; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA < expB - 1 ) return a; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) { + if ( ! sigB ) goto invalid; + normExpSig = softfloat_normSubnormalF64Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) { + if ( ! sigA ) return a; + normExpSig = softfloat_normSubnormalF64Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + rem = sigA | UINT64_C( 0x0010000000000000 ); + sigB |= UINT64_C( 0x0010000000000000 ); + expDiff = expA - expB; + if ( expDiff < 1 ) { + if ( expDiff < -1 ) return a; + sigB <<= 9; + if ( expDiff ) { + rem <<= 8; + q = 0; + } else { + rem <<= 9; + q = (sigB <= rem); + if ( q ) rem -= sigB; + } + } else { + recip32 = softfloat_approxRecip32_1( sigB>>21 ); + /*-------------------------------------------------------------------- + | Changing the shift of `rem' here requires also changing the initial + | subtraction from `expDiff'. + *--------------------------------------------------------------------*/ + rem <<= 9; + expDiff -= 30; + /*-------------------------------------------------------------------- + | The scale of `sigB' affects how many bits are obtained during each + | cycle of the loop. Currently this is 29 bits per loop iteration, + | the maximum possible. + *--------------------------------------------------------------------*/ + sigB <<= 9; + for (;;) { + q64 = (uint32_t) (rem>>32) * (uint_fast64_t) recip32; + if ( expDiff < 0 ) break; + q = (q64 + 0x80000000)>>32; +#ifdef SOFTFLOAT_FAST_INT64 + rem <<= 29; +#else + rem = (uint_fast64_t) (uint32_t) (rem>>3)<<32; +#endif + rem -= q * (uint64_t) sigB; + if ( rem & UINT64_C( 0x8000000000000000 ) ) rem += sigB; + expDiff -= 29; + } + /*-------------------------------------------------------------------- + | (`expDiff' cannot be less than -29 here.) + *--------------------------------------------------------------------*/ + q = (uint32_t) (q64>>32)>>(~expDiff & 31); + rem = (rem<<(expDiff + 30)) - q * (uint64_t) sigB; + if ( rem & UINT64_C( 0x8000000000000000 ) ) { + altRem = rem + sigB; + goto selectRem; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + do { + altRem = rem; + ++q; + rem -= sigB; + } while ( ! (rem & UINT64_C( 0x8000000000000000 )) ); + selectRem: + meanRem = rem + altRem; + if ( + (meanRem & UINT64_C( 0x8000000000000000 )) || (! meanRem && (q & 1)) + ) { + rem = altRem; + } + signRem = signA; + if ( rem & UINT64_C( 0x8000000000000000 ) ) { + signRem = ! signRem; + rem = -rem; + } + return softfloat_normRoundPackToF64( signRem, expB, rem ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF64UI( uiA, uiB ); + goto uiZ; + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF64UI; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f64_rem.c ****/ +/**** start inlining ../../source/f64_sqrt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f64_sqrt( float64_t a ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool signA; + int_fast16_t expA; + uint_fast64_t sigA, uiZ; + struct exp16_sig64 normExpSig; + int_fast16_t expZ; + uint32_t sig32A, recipSqrt32, sig32Z; + uint_fast64_t rem; + uint32_t q; + uint_fast64_t sigZ, shiftedSigZ; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF64UI( uiA ); + expA = expF64UI( uiA ); + sigA = fracF64UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FF ) { + if ( sigA ) { + uiZ = softfloat_propagateNaNF64UI( uiA, 0 ); + goto uiZ; + } + if ( ! signA ) return a; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( signA ) { + if ( ! (expA | sigA) ) return a; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) return a; + normExpSig = softfloat_normSubnormalF64Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + | (`sig32Z' is guaranteed to be a lower bound on the square root of + | `sig32A', which makes `sig32Z' also a lower bound on the square root of + | `sigA'.) + *------------------------------------------------------------------------*/ + expZ = ((expA - 0x3FF)>>1) + 0x3FE; + expA &= 1; + sigA |= UINT64_C( 0x0010000000000000 ); + sig32A = sigA>>21; + recipSqrt32 = softfloat_approxRecipSqrt32_1( expA, sig32A ); + sig32Z = ((uint_fast64_t) sig32A * recipSqrt32)>>32; + if ( expA ) { + sigA <<= 8; + sig32Z >>= 1; + } else { + sigA <<= 9; + } + rem = sigA - (uint_fast64_t) sig32Z * sig32Z; + q = ((uint32_t) (rem>>2) * (uint_fast64_t) recipSqrt32)>>32; + sigZ = ((uint_fast64_t) sig32Z<<32 | 1<<5) + ((uint_fast64_t) q<<3); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (sigZ & 0x1FF) < 0x22 ) { + sigZ &= ~(uint_fast64_t) 0x3F; + shiftedSigZ = sigZ>>6; + rem = (sigA<<52) - shiftedSigZ * shiftedSigZ; + if ( rem & UINT64_C( 0x8000000000000000 ) ) { + --sigZ; + } else { + if ( rem ) sigZ |= 1; + } + } + return softfloat_roundPackToF64( 0, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF64UI; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f64_sqrt.c ****/ +/**** start inlining ../../source/f64_eq.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f64_eq( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + union ui64_f64 uB; + uint_fast64_t uiB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF64UI( uiA ) || isNaNF64UI( uiB ) ) { + if ( + softfloat_isSigNaNF64UI( uiA ) || softfloat_isSigNaNF64UI( uiB ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + return (uiA == uiB) || ! ((uiA | uiB) & UINT64_C( 0x7FFFFFFFFFFFFFFF )); + +} + +/**** ended inlining ../../source/f64_eq.c ****/ +/**** start inlining ../../source/f64_le.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f64_le( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF64UI( uiA ) || isNaNF64UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signF64UI( uiA ); + signB = signF64UI( uiB ); + return + (signA != signB) + ? signA || ! ((uiA | uiB) & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + : (uiA == uiB) || (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f64_le.c ****/ +/**** start inlining ../../source/f64_lt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f64_lt( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF64UI( uiA ) || isNaNF64UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signF64UI( uiA ); + signB = signF64UI( uiB ); + return + (signA != signB) + ? signA && ((uiA | uiB) & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + : (uiA != uiB) && (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f64_lt.c ****/ +/**** start inlining ../../source/f64_eq_signaling.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f64_eq_signaling( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + union ui64_f64 uB; + uint_fast64_t uiB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF64UI( uiA ) || isNaNF64UI( uiB ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + return (uiA == uiB) || ! ((uiA | uiB) & UINT64_C( 0x7FFFFFFFFFFFFFFF )); + +} + +/**** ended inlining ../../source/f64_eq_signaling.c ****/ +/**** start inlining ../../source/f64_le_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f64_le_quiet( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF64UI( uiA ) || isNaNF64UI( uiB ) ) { + if ( + softfloat_isSigNaNF64UI( uiA ) || softfloat_isSigNaNF64UI( uiB ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signF64UI( uiA ); + signB = signF64UI( uiB ); + return + (signA != signB) + ? signA || ! ((uiA | uiB) & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + : (uiA == uiB) || (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f64_le_quiet.c ****/ +/**** start inlining ../../source/f64_lt_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f64_lt_quiet( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signA, signB; + + uA.f = a; + uiA = uA.ui; + uB.f = b; + uiB = uB.ui; + if ( isNaNF64UI( uiA ) || isNaNF64UI( uiB ) ) { + if ( + softfloat_isSigNaNF64UI( uiA ) || softfloat_isSigNaNF64UI( uiB ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signF64UI( uiA ); + signB = signF64UI( uiB ); + return + (signA != signB) + ? signA && ((uiA | uiB) & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + : (uiA != uiB) && (signA ^ (uiA < uiB)); + +} + +/**** ended inlining ../../source/f64_lt_quiet.c ****/ +/**** start inlining ../../source/f64_isSignalingNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f64_isSignalingNaN( float64_t a ) +{ + union ui64_f64 uA; + + uA.f = a; + return softfloat_isSigNaNF64UI( uA.ui ); + +} + +/**** ended inlining ../../source/f64_isSignalingNaN.c ****/ +/**** start inlining ../../source/extF80_to_ui32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t + extF80_to_ui32( extFloat80_t a, uint_fast8_t roundingMode, bool exact ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + bool sign; + int_fast32_t exp; + uint_fast64_t sig; + int_fast32_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = uA.s.signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (ui32_fromNaN != ui32_fromPosOverflow) || (ui32_fromNaN != ui32_fromNegOverflow) + if ( (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ) { +#if (ui32_fromNaN == ui32_fromPosOverflow) + sign = 0; +#elif (ui32_fromNaN == ui32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return ui32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x4032 - exp; + if ( shiftDist <= 0 ) shiftDist = 1; + sig = softfloat_shiftRightJam64( sig, shiftDist ); + return softfloat_roundToUI32( sign, sig, roundingMode, exact ); + +} + +/**** ended inlining ../../source/extF80_to_ui32.c ****/ +/**** start inlining ../../source/extF80_to_ui64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t + extF80_to_ui64( extFloat80_t a, uint_fast8_t roundingMode, bool exact ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + bool sign; + int_fast32_t exp; + uint_fast64_t sig; + int_fast32_t shiftDist; + uint_fast64_t sigExtra; + struct uint64_extra sig64Extra; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = uA.s.signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( shiftDist < 0 ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sigExtra = 0; + if ( shiftDist ) { + sig64Extra = softfloat_shiftRightJam64Extra( sig, 0, shiftDist ); + sig = sig64Extra.v; + sigExtra = sig64Extra.extra; + } + return softfloat_roundToUI64( sign, sig, sigExtra, roundingMode, exact ); + +} + +/**** ended inlining ../../source/extF80_to_ui64.c ****/ +/**** start inlining ../../source/extF80_to_i32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t + extF80_to_i32( extFloat80_t a, uint_fast8_t roundingMode, bool exact ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + bool sign; + int_fast32_t exp; + uint_fast64_t sig; + int_fast32_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = uA.s.signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (i32_fromNaN != i32_fromPosOverflow) || (i32_fromNaN != i32_fromNegOverflow) + if ( (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ) { +#if (i32_fromNaN == i32_fromPosOverflow) + sign = 0; +#elif (i32_fromNaN == i32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return i32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x4032 - exp; + if ( shiftDist <= 0 ) shiftDist = 1; + sig = softfloat_shiftRightJam64( sig, shiftDist ); + return softfloat_roundToI32( sign, sig, roundingMode, exact ); + +} + +/**** ended inlining ../../source/extF80_to_i32.c ****/ +/**** start inlining ../../source/extF80_to_i64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t + extF80_to_i64( extFloat80_t a, uint_fast8_t roundingMode, bool exact ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + bool sign; + int_fast32_t exp; + uint_fast64_t sig; + int_fast32_t shiftDist; + uint_fast64_t sigExtra; + struct uint64_extra sig64Extra; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = uA.s.signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( shiftDist <= 0 ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( shiftDist ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sigExtra = 0; + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sig64Extra = softfloat_shiftRightJam64Extra( sig, 0, shiftDist ); + sig = sig64Extra.v; + sigExtra = sig64Extra.extra; + } + return softfloat_roundToI64( sign, sig, sigExtra, roundingMode, exact ); + +} + +/**** ended inlining ../../source/extF80_to_i64.c ****/ +/**** start inlining ../../source/extF80_to_ui32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t extF80_to_ui32_r_minMag( extFloat80_t a, bool exact ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + int_fast32_t exp; + uint_fast64_t sig; + int_fast32_t shiftDist; + bool sign; + uint_fast32_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + exp = expExtF80UI64( uiA64 ); + sig = uA.s.signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( 64 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signExtF80UI64( uiA64 ); + if ( sign || (shiftDist < 32) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + ? ui32_fromNaN + : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + z = sig>>shiftDist; + if ( exact && ((uint_fast64_t) z< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t extF80_to_ui64_r_minMag( extFloat80_t a, bool exact ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + int_fast32_t exp; + uint_fast64_t sig; + int_fast32_t shiftDist; + bool sign; + uint_fast64_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + exp = expExtF80UI64( uiA64 ); + sig = uA.s.signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( 64 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signExtF80UI64( uiA64 ); + if ( sign || (shiftDist < 0) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + z = sig>>shiftDist; + if ( exact && (z< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t extF80_to_i32_r_minMag( extFloat80_t a, bool exact ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + int_fast32_t exp; + uint_fast64_t sig; + int_fast32_t shiftDist; + bool sign; + int_fast32_t absZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + exp = expExtF80UI64( uiA64 ); + sig = uA.s.signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( 64 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signExtF80UI64( uiA64 ); + if ( shiftDist < 33 ) { + if ( + (uiA64 == packToExtF80UI64( 1, 0x401E )) + && (sig < UINT64_C( 0x8000000100000000 )) + ) { + if ( exact && (sig & UINT64_C( 0x00000000FFFFFFFF )) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return -0x7FFFFFFF - 1; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + ? i32_fromNaN + : sign ? i32_fromNegOverflow : i32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + absZ = sig>>shiftDist; + if ( exact && ((uint_fast64_t) (uint_fast32_t) absZ< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t extF80_to_i64_r_minMag( extFloat80_t a, bool exact ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + int_fast32_t exp; + uint_fast64_t sig; + int_fast32_t shiftDist; + bool sign; + int_fast64_t absZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + exp = expExtF80UI64( uiA64 ); + sig = uA.s.signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( 64 <= shiftDist ) { + if ( exact && (exp | sig) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signExtF80UI64( uiA64 ); + if ( shiftDist <= 0 ) { + if ( + (uiA64 == packToExtF80UI64( 1, 0x403E )) + && (sig == UINT64_C( 0x8000000000000000 )) + ) { + return -INT64_C( 0x7FFFFFFFFFFFFFFF ) - 1; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + absZ = sig>>shiftDist; + if ( exact && (uint64_t) (sig<<(-shiftDist & 63)) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return sign ? -absZ : absZ; + +} + +/**** ended inlining ../../source/extF80_to_i64_r_minMag.c ****/ +/**** start inlining ../../source/extF80_to_f16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t extF80_to_f16( extFloat80_t a ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig; + struct commonNaN commonNaN; + uint_fast16_t uiZ, sig16; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_extF80UIToCommonNaN( uiA64, uiA0, &commonNaN ); + uiZ = softfloat_commonNaNToF16UI( &commonNaN ); + } else { + uiZ = packToF16UI( sign, 0x1F, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig16 = softfloat_shortShiftRightJam64( sig, 49 ); + if ( ! (exp | sig16) ) { + uiZ = packToF16UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp -= 0x3FF1; + if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) { + if ( exp < -0x40 ) exp = -0x40; + } + return softfloat_roundPackToF16( sign, exp, sig16 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/extF80_to_f16.c ****/ +/**** start inlining ../../source/extF80_to_f32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t extF80_to_f32( extFloat80_t a ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig; + struct commonNaN commonNaN; + uint_fast32_t uiZ, sig32; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_extF80UIToCommonNaN( uiA64, uiA0, &commonNaN ); + uiZ = softfloat_commonNaNToF32UI( &commonNaN ); + } else { + uiZ = packToF32UI( sign, 0xFF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig32 = softfloat_shortShiftRightJam64( sig, 33 ); + if ( ! (exp | sig32) ) { + uiZ = packToF32UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp -= 0x3F81; + if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) { + if ( exp < -0x1000 ) exp = -0x1000; + } + return softfloat_roundPackToF32( sign, exp, sig32 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/extF80_to_f32.c ****/ +/**** start inlining ../../source/extF80_to_f64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t extF80_to_f64( extFloat80_t a ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig; + struct commonNaN commonNaN; + uint_fast64_t uiZ; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! (exp | sig) ) { + uiZ = packToF64UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_extF80UIToCommonNaN( uiA64, uiA0, &commonNaN ); + uiZ = softfloat_commonNaNToF64UI( &commonNaN ); + } else { + uiZ = packToF64UI( sign, 0x7FF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig = softfloat_shortShiftRightJam64( sig, 1 ); + exp -= 0x3C01; + if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) { + if ( exp < -0x1000 ) exp = -0x1000; + } + return softfloat_roundPackToF64( sign, exp, sig ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/extF80_to_f64.c ****/ +/**** start inlining ../../source/extF80_to_f128.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t extF80_to_f128( extFloat80_t a ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + uint_fast16_t exp; + uint_fast64_t frac; + struct commonNaN commonNaN; + struct uint128 uiZ; + bool sign; + struct uint128 frac128; + union ui128_f128 uZ; + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + exp = expExtF80UI64( uiA64 ); + frac = uiA0 & UINT64_C( 0x7FFFFFFFFFFFFFFF ); + if ( (exp == 0x7FFF) && frac ) { + softfloat_extF80UIToCommonNaN( uiA64, uiA0, &commonNaN ); + uiZ = softfloat_commonNaNToF128UI( &commonNaN ); + } else { + sign = signExtF80UI64( uiA64 ); + frac128 = softfloat_shortShiftLeft128( 0, frac, 49 ); + uiZ.v64 = packToF128UI64( sign, exp, frac128.v64 ); + uiZ.v0 = frac128.v0; + } + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/extF80_to_f128.c ****/ +/**** start inlining ../../source/extF80_roundToInt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t + extF80_roundToInt( extFloat80_t a, uint_fast8_t roundingMode, bool exact ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64, signUI64; + int_fast32_t exp; + uint_fast64_t sigA; + uint_fast16_t uiZ64; + uint_fast64_t sigZ; + struct exp32_sig64 normExpSig; + struct uint128 uiZ; + uint_fast64_t lastBitMask, roundBitsMask; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + signUI64 = uiA64 & packToExtF80UI64( 1, 0 ); + exp = expExtF80UI64( uiA64 ); + sigA = uA.s.signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( !(sigA & UINT64_C( 0x8000000000000000 )) && (exp != 0x7FFF) ) { + if ( !sigA ) { + uiZ64 = signUI64; + sigZ = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalExtF80Sig( sigA ); + exp += normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x403E <= exp ) { + if ( exp == 0x7FFF ) { + if ( sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + uiZ = softfloat_propagateNaNExtF80UI( uiA64, sigA, 0, 0 ); + uiZ64 = uiZ.v64; + sigZ = uiZ.v0; + goto uiZ; + } + sigZ = UINT64_C( 0x8000000000000000 ); + } else { + sigZ = sigA; + } + uiZ64 = signUI64 | exp; + goto uiZ; + } + if ( exp <= 0x3FFE ) { + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + switch ( roundingMode ) { + case softfloat_round_near_even: + if ( !(sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ) break; + case softfloat_round_near_maxMag: + if ( exp == 0x3FFE ) goto mag1; + break; + case softfloat_round_min: + if ( signUI64 ) goto mag1; + break; + case softfloat_round_max: + if ( !signUI64 ) goto mag1; + break; +#ifdef SOFTFLOAT_ROUND_ODD + case softfloat_round_odd: + goto mag1; +#endif + } + uiZ64 = signUI64; + sigZ = 0; + goto uiZ; + mag1: + uiZ64 = signUI64 | 0x3FFF; + sigZ = UINT64_C( 0x8000000000000000 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ64 = signUI64 | exp; + lastBitMask = (uint_fast64_t) 1<<(0x403E - exp); + roundBitsMask = lastBitMask - 1; + sigZ = sigA; + if ( roundingMode == softfloat_round_near_maxMag ) { + sigZ += lastBitMask>>1; + } else if ( roundingMode == softfloat_round_near_even ) { + sigZ += lastBitMask>>1; + if ( !(sigZ & roundBitsMask) ) sigZ &= ~lastBitMask; + } else if ( + roundingMode == (signUI64 ? softfloat_round_min : softfloat_round_max) + ) { + sigZ += roundBitsMask; + } + sigZ &= ~roundBitsMask; + if ( !sigZ ) { + ++uiZ64; + sigZ = UINT64_C( 0x8000000000000000 ); + } + if ( sigZ != sigA ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) sigZ |= lastBitMask; +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = sigZ; + return uZ.f; + +} + +/**** ended inlining ../../source/extF80_roundToInt.c ****/ +/**** start inlining ../../source/extF80_add.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t extF80_add( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool signA; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + extFloat80_t + (*magsFuncPtr)( + uint_fast16_t, uint_fast64_t, uint_fast16_t, uint_fast64_t, bool ); +#endif + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + signA = signExtF80UI64( uiA64 ); + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + signB = signExtF80UI64( uiB64 ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + return softfloat_addMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA ); + } else { + return softfloat_subMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_addMagsExtF80 : softfloat_subMagsExtF80; + return (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA ); +#endif + +} + +/**** ended inlining ../../source/extF80_add.c ****/ +/**** start inlining ../../source/extF80_sub.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t extF80_sub( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool signA; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + extFloat80_t + (*magsFuncPtr)( + uint_fast16_t, uint_fast64_t, uint_fast16_t, uint_fast64_t, bool ); +#endif + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + signA = signExtF80UI64( uiA64 ); + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + signB = signExtF80UI64( uiB64 ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + return softfloat_subMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA ); + } else { + return softfloat_addMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_subMagsExtF80 : softfloat_addMagsExtF80; + return (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA ); +#endif + +} + +/**** ended inlining ../../source/extF80_sub.c ****/ +/**** start inlining ../../source/extF80_mul.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t extF80_mul( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool signA; + int_fast32_t expA; + uint_fast64_t sigA; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signB; + int_fast32_t expB; + uint_fast64_t sigB; + bool signZ; + uint_fast64_t magBits; + struct exp32_sig64 normExpSig; + int_fast32_t expZ; + struct uint128 sig128Z, uiZ; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + signA = signExtF80UI64( uiA64 ); + expA = expExtF80UI64( uiA64 ); + sigA = uiA0; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + signB = signExtF80UI64( uiB64 ); + expB = expExtF80UI64( uiB64 ); + sigB = uiB0; + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( + (sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + || ((expB == 0x7FFF) && (sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ))) + ) { + goto propagateNaN; + } + magBits = expB | sigB; + goto infArg; + } + if ( expB == 0x7FFF ) { + if ( sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN; + magBits = expA | sigA; + goto infArg; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) expA = 1; + if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalExtF80Sig( sigA ); + expA += normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) expB = 1; + if ( ! (sigB & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigB ) goto zero; + normExpSig = softfloat_normSubnormalExtF80Sig( sigB ); + expB += normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x3FFE; + sig128Z = softfloat_mul64To128( sigA, sigB ); + if ( sig128Z.v64 < UINT64_C( 0x8000000000000000 ) ) { + --expZ; + sig128Z = + softfloat_add128( + sig128Z.v64, sig128Z.v0, sig128Z.v64, sig128Z.v0 ); + } + return + softfloat_roundPackToExtF80( + signZ, expZ, sig128Z.v64, sig128Z.v0, extF80_roundingPrecision ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNExtF80UI( uiA64, uiA0, uiB64, uiB0 ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infArg: + if ( ! magBits ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ64 = defaultNaNExtF80UI64; + uiZ0 = defaultNaNExtF80UI0; + } else { + uiZ64 = packToExtF80UI64( signZ, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + } + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ64 = packToExtF80UI64( signZ, 0 ); + uiZ0 = 0; + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/extF80_mul.c ****/ +/**** start inlining ../../source/extF80_div.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t extF80_div( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool signA; + int_fast32_t expA; + uint_fast64_t sigA; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signB; + int_fast32_t expB; + uint_fast64_t sigB; + bool signZ; + struct exp32_sig64 normExpSig; + int_fast32_t expZ; + struct uint128 rem; + uint_fast32_t recip32; + uint_fast64_t sigZ; + int ix; + uint_fast64_t q64; + uint_fast32_t q; + struct uint128 term; + uint_fast64_t sigZExtra; + struct uint128 uiZ; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + signA = signExtF80UI64( uiA64 ); + expA = expExtF80UI64( uiA64 ); + sigA = uiA0; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + signB = signExtF80UI64( uiB64 ); + expB = expExtF80UI64( uiB64 ); + sigB = uiB0; + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN; + if ( expB == 0x7FFF ) { + if ( sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN; + goto invalid; + } + goto infinity; + } + if ( expB == 0x7FFF ) { + if ( sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN; + goto zero; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) expB = 1; + if ( ! (sigB & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigB ) { + if ( ! sigA ) goto invalid; + softfloat_raiseFlags( softfloat_flag_infinite ); + goto infinity; + } + normExpSig = softfloat_normSubnormalExtF80Sig( sigB ); + expB += normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) expA = 1; + if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalExtF80Sig( sigA ); + expA += normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA - expB + 0x3FFF; + if ( sigA < sigB ) { + --expZ; + rem = softfloat_shortShiftLeft128( 0, sigA, 32 ); + } else { + rem = softfloat_shortShiftLeft128( 0, sigA, 31 ); + } + recip32 = softfloat_approxRecip32_1( sigB>>32 ); + sigZ = 0; + ix = 2; + for (;;) { + q64 = (uint_fast64_t) (uint32_t) (rem.v64>>2) * recip32; + q = (q64 + 0x80000000)>>32; + --ix; + if ( ix < 0 ) break; + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 ); + term = softfloat_mul64ByShifted32To128( sigB, q ); + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + --q; + rem = softfloat_add128( rem.v64, rem.v0, sigB>>32, sigB<<32 ); + } + sigZ = (sigZ<<29) + q; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ((q + 1) & 0x3FFFFF) < 2 ) { + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 ); + term = softfloat_mul64ByShifted32To128( sigB, q ); + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + term = softfloat_shortShiftLeft128( 0, sigB, 32 ); + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + --q; + rem = softfloat_add128( rem.v64, rem.v0, term.v64, term.v0 ); + } else if ( softfloat_le128( term.v64, term.v0, rem.v64, rem.v0 ) ) { + ++q; + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + } + if ( rem.v64 | rem.v0 ) q |= 1; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sigZ = (sigZ<<6) + (q>>23); + sigZExtra = (uint64_t) ((uint_fast64_t) q<<41); + return + softfloat_roundPackToExtF80( + signZ, expZ, sigZ, sigZExtra, extF80_roundingPrecision ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNExtF80UI( uiA64, uiA0, uiB64, uiB0 ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ64 = defaultNaNExtF80UI64; + uiZ0 = defaultNaNExtF80UI0; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infinity: + uiZ64 = packToExtF80UI64( signZ, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ64 = packToExtF80UI64( signZ, 0 ); + uiZ0 = 0; + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/extF80_div.c ****/ +/**** start inlining ../../source/extF80_rem.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t extF80_rem( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool signA; + int_fast32_t expA; + uint_fast64_t sigA; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + int_fast32_t expB; + uint_fast64_t sigB; + struct exp32_sig64 normExpSig; + int_fast32_t expDiff; + struct uint128 rem, shiftedSigB; + uint_fast32_t q, recip32; + uint_fast64_t q64; + struct uint128 term, altRem, meanRem; + bool signRem; + struct uint128 uiZ; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + signA = signExtF80UI64( uiA64 ); + expA = expExtF80UI64( uiA64 ); + sigA = uiA0; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + expB = expExtF80UI64( uiB64 ); + sigB = uiB0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( + (sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + || ((expB == 0x7FFF) && (sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ))) + ) { + goto propagateNaN; + } + goto invalid; + } + if ( expB == 0x7FFF ) { + if ( sigB & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) goto propagateNaN; + /*-------------------------------------------------------------------- + | Argument b is an infinity. Doubling `expB' is an easy way to ensure + | that `expDiff' later is less than -1, which will result in returning + | a canonicalized version of argument a. + *--------------------------------------------------------------------*/ + expB += expB; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) expB = 1; + if ( ! (sigB & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigB ) goto invalid; + normExpSig = softfloat_normSubnormalExtF80Sig( sigB ); + expB += normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) expA = 1; + if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigA ) { + expA = 0; + goto copyA; + } + normExpSig = softfloat_normSubnormalExtF80Sig( sigA ); + expA += normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( expDiff < -1 ) goto copyA; + rem = softfloat_shortShiftLeft128( 0, sigA, 32 ); + shiftedSigB = softfloat_shortShiftLeft128( 0, sigB, 32 ); + if ( expDiff < 1 ) { + if ( expDiff ) { + --expB; + shiftedSigB = softfloat_shortShiftLeft128( 0, sigB, 33 ); + q = 0; + } else { + q = (sigB <= sigA); + if ( q ) { + rem = + softfloat_sub128( + rem.v64, rem.v0, shiftedSigB.v64, shiftedSigB.v0 ); + } + } + } else { + recip32 = softfloat_approxRecip32_1( sigB>>32 ); + expDiff -= 30; + for (;;) { + q64 = (uint_fast64_t) (uint32_t) (rem.v64>>2) * recip32; + if ( expDiff < 0 ) break; + q = (q64 + 0x80000000)>>32; + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 ); + term = softfloat_mul64ByShifted32To128( sigB, q ); + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + rem = + softfloat_add128( + rem.v64, rem.v0, shiftedSigB.v64, shiftedSigB.v0 ); + } + expDiff -= 29; + } + /*-------------------------------------------------------------------- + | (`expDiff' cannot be less than -29 here.) + *--------------------------------------------------------------------*/ + q = (uint32_t) (q64>>32)>>(~expDiff & 31); + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, expDiff + 30 ); + term = softfloat_mul64ByShifted32To128( sigB, q ); + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + altRem = + softfloat_add128( + rem.v64, rem.v0, shiftedSigB.v64, shiftedSigB.v0 ); + goto selectRem; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + do { + altRem = rem; + ++q; + rem = + softfloat_sub128( + rem.v64, rem.v0, shiftedSigB.v64, shiftedSigB.v0 ); + } while ( ! (rem.v64 & UINT64_C( 0x8000000000000000 )) ); + selectRem: + meanRem = softfloat_add128( rem.v64, rem.v0, altRem.v64, altRem.v0 ); + if ( + (meanRem.v64 & UINT64_C( 0x8000000000000000 )) + || (! (meanRem.v64 | meanRem.v0) && (q & 1)) + ) { + rem = altRem; + } + signRem = signA; + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + signRem = ! signRem; + rem = softfloat_sub128( 0, 0, rem.v64, rem.v0 ); + } + return + softfloat_normRoundPackToExtF80( + signRem, rem.v64 | rem.v0 ? expB + 32 : 0, rem.v64, rem.v0, 80 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNExtF80UI( uiA64, uiA0, uiB64, uiB0 ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ64 = defaultNaNExtF80UI64; + uiZ0 = defaultNaNExtF80UI0; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + copyA: + if ( expA < 1 ) { + sigA >>= 1 - expA; + expA = 0; + } + uiZ64 = packToExtF80UI64( signA, expA ); + uiZ0 = sigA; + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/extF80_rem.c ****/ +/**** start inlining ../../source/extF80_sqrt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t extF80_sqrt( extFloat80_t a ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool signA; + int_fast32_t expA; + uint_fast64_t sigA; + struct uint128 uiZ; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0; + struct exp32_sig64 normExpSig; + int_fast32_t expZ; + uint_fast32_t sig32A, recipSqrt32, sig32Z; + struct uint128 rem; + uint_fast64_t q, x64, sigZ; + struct uint128 y, term; + uint_fast64_t sigZExtra; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + signA = signExtF80UI64( uiA64 ); + expA = expExtF80UI64( uiA64 ); + sigA = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + uiZ = softfloat_propagateNaNExtF80UI( uiA64, uiA0, 0, 0 ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + goto uiZ; + } + if ( ! signA ) return a; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( signA ) { + if ( ! sigA ) goto zero; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) expA = 1; + if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalExtF80Sig( sigA ); + expA += normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + | (`sig32Z' is guaranteed to be a lower bound on the square root of + | `sig32A', which makes `sig32Z' also a lower bound on the square root of + | `sigA'.) + *------------------------------------------------------------------------*/ + expZ = ((expA - 0x3FFF)>>1) + 0x3FFF; + expA &= 1; + sig32A = sigA>>32; + recipSqrt32 = softfloat_approxRecipSqrt32_1( expA, sig32A ); + sig32Z = ((uint_fast64_t) sig32A * recipSqrt32)>>32; + if ( expA ) { + sig32Z >>= 1; + rem = softfloat_shortShiftLeft128( 0, sigA, 61 ); + } else { + rem = softfloat_shortShiftLeft128( 0, sigA, 62 ); + } + rem.v64 -= (uint_fast64_t) sig32Z * sig32Z; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = ((uint32_t) (rem.v64>>2) * (uint_fast64_t) recipSqrt32)>>32; + x64 = (uint_fast64_t) sig32Z<<32; + sigZ = x64 + (q<<3); + y = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 ); + /*------------------------------------------------------------------------ + | (Repeating this loop is a rare occurrence.) + *------------------------------------------------------------------------*/ + for (;;) { + term = softfloat_mul64ByShifted32To128( x64 + sigZ, q ); + rem = softfloat_sub128( y.v64, y.v0, term.v64, term.v0 ); + if ( ! (rem.v64 & UINT64_C( 0x8000000000000000 )) ) break; + --q; + sigZ -= 1<<3; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = (((rem.v64>>2) * recipSqrt32)>>32) + 2; + x64 = sigZ; + sigZ = (sigZ<<1) + (q>>25); + sigZExtra = (uint64_t) (q<<39); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (q & 0xFFFFFF) <= 2 ) { + q &= ~(uint_fast64_t) 0xFFFF; + sigZExtra = (uint64_t) (q<<39); + term = softfloat_mul64ByShifted32To128( x64 + (q>>27), q ); + x64 = (uint32_t) (q<<5) * (uint_fast64_t) (uint32_t) q; + term = softfloat_add128( term.v64, term.v0, 0, x64 ); + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 28 ); + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + if ( ! sigZExtra ) --sigZ; + --sigZExtra; + } else { + if ( rem.v64 | rem.v0 ) sigZExtra |= 1; + } + } + return + softfloat_roundPackToExtF80( + 0, expZ, sigZ, sigZExtra, extF80_roundingPrecision ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ64 = defaultNaNExtF80UI64; + uiZ0 = defaultNaNExtF80UI0; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ64 = packToExtF80UI64( signA, 0 ); + uiZ0 = 0; + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/extF80_sqrt.c ****/ +/**** start inlining ../../source/extF80_eq.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool extF80_eq( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNExtF80UI( uiA64, uiA0 ) + || softfloat_isSigNaNExtF80UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + return + (uiA0 == uiB0) + && ((uiA64 == uiB64) || (! uiA0 && ! ((uiA64 | uiB64) & 0x7FFF))); + +} + +/**** ended inlining ../../source/extF80_eq.c ****/ +/**** start inlining ../../source/extF80_le.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool extF80_le( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signA, signB; + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signExtF80UI64( uiA64 ); + signB = signExtF80UI64( uiB64 ); + return + (signA != signB) + ? signA || ! (((uiA64 | uiB64) & 0x7FFF) | uiA0 | uiB0) + : ((uiA64 == uiB64) && (uiA0 == uiB0)) + || (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 )); + +} + +/**** ended inlining ../../source/extF80_le.c ****/ +/**** start inlining ../../source/extF80_lt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool extF80_lt( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signA, signB; + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signExtF80UI64( uiA64 ); + signB = signExtF80UI64( uiB64 ); + return + (signA != signB) + ? signA && (((uiA64 | uiB64) & 0x7FFF) | uiA0 | uiB0) + : ((uiA64 != uiB64) || (uiA0 != uiB0)) + && (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 )); + +} + +/**** ended inlining ../../source/extF80_lt.c ****/ +/**** start inlining ../../source/extF80_eq_signaling.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool extF80_eq_signaling( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + return + (uiA0 == uiB0) + && ((uiA64 == uiB64) || (! uiA0 && ! ((uiA64 | uiB64) & 0x7FFF))); + +} + +/**** ended inlining ../../source/extF80_eq_signaling.c ****/ +/**** start inlining ../../source/extF80_le_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool extF80_le_quiet( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signA, signB; + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNExtF80UI( uiA64, uiA0 ) + || softfloat_isSigNaNExtF80UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signExtF80UI64( uiA64 ); + signB = signExtF80UI64( uiB64 ); + return + (signA != signB) + ? signA || ! (((uiA64 | uiB64) & 0x7FFF) | uiA0 | uiB0) + : ((uiA64 == uiB64) && (uiA0 == uiB0)) + || (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 )); + +} + +/**** ended inlining ../../source/extF80_le_quiet.c ****/ +/**** start inlining ../../source/extF80_lt_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool extF80_lt_quiet( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signA, signB; + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNExtF80UI( uiA64, uiA0 ) + || softfloat_isSigNaNExtF80UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signExtF80UI64( uiA64 ); + signB = signExtF80UI64( uiB64 ); + return + (signA != signB) + ? signA && (((uiA64 | uiB64) & 0x7FFF) | uiA0 | uiB0) + : ((uiA64 != uiB64) || (uiA0 != uiB0)) + && (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 )); + +} + +/**** ended inlining ../../source/extF80_lt_quiet.c ****/ +/**** start inlining ../../source/extF80_isSignalingNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool extF80_isSignalingNaN( extFloat80_t a ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + + uA.f = a; + return softfloat_isSigNaNExtF80UI( uA.s.signExp, uA.s.signif ); + +} + +/**** ended inlining ../../source/extF80_isSignalingNaN.c ****/ +/**** start inlining ../../source/extF80M_to_ui32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +uint_fast32_t + extF80M_to_ui32( + const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + + return extF80_to_ui32( *aPtr, roundingMode, exact ); + +} + +#else + +uint_fast32_t + extF80M_to_ui32( + const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + bool sign; + int32_t exp; + uint64_t sig; + int32_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + uiA64 = aSPtr->signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x4032 - exp; + if ( shiftDist <= 0 ) { + if ( sig>>32 ) goto invalid; + if ( -32 < shiftDist ) { + sig <<= -shiftDist; + } else { + if ( (uint32_t) sig ) goto invalid; + } + } else { + sig = softfloat_shiftRightJam64( sig, shiftDist ); + } + return softfloat_roundToUI32( sign, sig, roundingMode, exact ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + ? ui32_fromNaN + : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow; + +} + +#endif + +/**** ended inlining ../../source/extF80M_to_ui32.c ****/ +/**** start inlining ../../source/extF80M_to_ui64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +uint_fast64_t + extF80M_to_ui64( + const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + + return extF80_to_ui64( *aPtr, roundingMode, exact ); + +} + +#else + +uint_fast64_t + extF80M_to_ui64( + const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + bool sign; + int32_t exp; + uint64_t sig; + int32_t shiftDist; + uint32_t extSig[3]; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + uiA64 = aSPtr->signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( shiftDist < 0 ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + extSig[indexWord( 3, 2 )] = sig>>32; + extSig[indexWord( 3, 1 )] = sig; + extSig[indexWord( 3, 0 )] = 0; + if ( shiftDist ) softfloat_shiftRightJam96M( extSig, shiftDist, extSig ); + return softfloat_roundMToUI64( sign, extSig, roundingMode, exact ); + +} + +#endif + +/**** ended inlining ../../source/extF80M_to_ui64.c ****/ +/**** start inlining ../../source/extF80M_to_i32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +int_fast32_t + extF80M_to_i32( + const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + + return extF80_to_i32( *aPtr, roundingMode, exact ); + +} + +#else + +int_fast32_t + extF80M_to_i32( + const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + bool sign; + int32_t exp; + uint64_t sig; + int32_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + uiA64 = aSPtr->signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x4032 - exp; + if ( shiftDist <= 0 ) { + if ( sig>>32 ) goto invalid; + if ( -32 < shiftDist ) { + sig <<= -shiftDist; + } else { + if ( (uint32_t) sig ) goto invalid; + } + } else { + sig = softfloat_shiftRightJam64( sig, shiftDist ); + } + return softfloat_roundToI32( sign, sig, roundingMode, exact ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ? i32_fromNaN + : sign ? i32_fromNegOverflow : i32_fromPosOverflow; + +} + +#endif + +/**** ended inlining ../../source/extF80M_to_i32.c ****/ +/**** start inlining ../../source/extF80M_to_i64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +int_fast64_t + extF80M_to_i64( + const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + + return extF80_to_i64( *aPtr, roundingMode, exact ); + +} + +#else + +int_fast64_t + extF80M_to_i64( + const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + bool sign; + int32_t exp; + uint64_t sig; + int32_t shiftDist; + uint32_t extSig[3]; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + uiA64 = aSPtr->signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( shiftDist < 0 ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + extSig[indexWord( 3, 2 )] = sig>>32; + extSig[indexWord( 3, 1 )] = sig; + extSig[indexWord( 3, 0 )] = 0; + if ( shiftDist ) softfloat_shiftRightJam96M( extSig, shiftDist, extSig ); + return softfloat_roundMToI64( sign, extSig, roundingMode, exact ); + +} + +#endif + +/**** ended inlining ../../source/extF80M_to_i64.c ****/ +/**** start inlining ../../source/extF80M_to_ui32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +uint_fast32_t extF80M_to_ui32_r_minMag( const extFloat80_t *aPtr, bool exact ) +{ + + return extF80_to_ui32_r_minMag( *aPtr, exact ); + +} + +#else + +uint_fast32_t extF80M_to_ui32_r_minMag( const extFloat80_t *aPtr, bool exact ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + int32_t exp; + uint64_t sig; + int32_t shiftDist; + bool sign; + uint64_t shiftedSig; + uint32_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + uiA64 = aSPtr->signExp; + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! sig && (exp != 0x7FFF) ) return 0; + shiftDist = 0x403E - exp; + if ( 64 <= shiftDist ) { + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signExtF80UI64( uiA64 ); + if ( shiftDist < 0 ) { + if ( sign || sig>>32 || (shiftDist <= -31) ) goto invalid; + shiftedSig = (uint64_t) (uint32_t) sig<<-shiftDist; + if ( shiftedSig>>32 ) goto invalid; + z = shiftedSig; + } else { + shiftedSig = sig; + if ( shiftDist ) shiftedSig >>= shiftDist; + if ( shiftedSig>>32 ) goto invalid; + z = shiftedSig; + if ( sign && z ) goto invalid; + if ( exact && shiftDist && ((uint64_t) z< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +uint_fast64_t extF80M_to_ui64_r_minMag( const extFloat80_t *aPtr, bool exact ) +{ + + return extF80_to_ui64_r_minMag( *aPtr, exact ); + +} + +#else + +uint_fast64_t extF80M_to_ui64_r_minMag( const extFloat80_t *aPtr, bool exact ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + int32_t exp; + uint64_t sig; + int32_t shiftDist; + bool sign; + uint64_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + uiA64 = aSPtr->signExp; + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! sig && (exp != 0x7FFF) ) return 0; + shiftDist = 0x403E - exp; + if ( 64 <= shiftDist ) { + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signExtF80UI64( uiA64 ); + if ( shiftDist < 0 ) { + if ( sign || (shiftDist <= -63) ) goto invalid; + shiftDist = -shiftDist; + z = sig<>shiftDist != sig ) goto invalid; + } else { + z = sig; + if ( shiftDist ) z >>= shiftDist; + if ( sign && z ) goto invalid; + if ( exact && shiftDist && (z< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +int_fast32_t extF80M_to_i32_r_minMag( const extFloat80_t *aPtr, bool exact ) +{ + + return extF80_to_i32_r_minMag( *aPtr, exact ); + +} + +#else + +int_fast32_t extF80M_to_i32_r_minMag( const extFloat80_t *aPtr, bool exact ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + int32_t exp; + uint64_t sig; + int32_t shiftDist; + bool sign, raiseInexact; + int32_t z; + uint64_t shiftedSig; + uint32_t absZ; + union { uint32_t ui; int32_t i; } u; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + uiA64 = aSPtr->signExp; + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! sig && (exp != 0x7FFF) ) return 0; + shiftDist = 0x403E - exp; + if ( 64 <= shiftDist ) { + raiseInexact = exact; + z = 0; + } else { + sign = signExtF80UI64( uiA64 ); + raiseInexact = false; + if ( shiftDist < 0 ) { + if ( sig>>32 || (shiftDist <= -31) ) goto invalid; + shiftedSig = (uint64_t) (uint32_t) sig<<-shiftDist; + if ( shiftedSig>>32 ) goto invalid; + absZ = shiftedSig; + } else { + shiftedSig = sig; + if ( shiftDist ) shiftedSig >>= shiftDist; + if ( shiftedSig>>32 ) goto invalid; + absZ = shiftedSig; + if ( exact && shiftDist ) { + raiseInexact = ((uint64_t) absZ< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +int_fast64_t extF80M_to_i64_r_minMag( const extFloat80_t *aPtr, bool exact ) +{ + + return extF80_to_i64_r_minMag( *aPtr, exact ); + +} + +#else + +int_fast64_t extF80M_to_i64_r_minMag( const extFloat80_t *aPtr, bool exact ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + int32_t exp; + uint64_t sig; + int32_t shiftDist; + bool sign, raiseInexact; + int64_t z; + uint64_t absZ; + union { uint64_t ui; int64_t i; } u; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + uiA64 = aSPtr->signExp; + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! sig && (exp != 0x7FFF) ) return 0; + shiftDist = 0x403E - exp; + if ( 64 <= shiftDist ) { + raiseInexact = exact; + z = 0; + } else { + sign = signExtF80UI64( uiA64 ); + raiseInexact = false; + if ( shiftDist < 0 ) { + if ( shiftDist <= -63 ) goto invalid; + shiftDist = -shiftDist; + absZ = sig<>shiftDist != sig ) goto invalid; + } else { + absZ = sig; + if ( shiftDist ) absZ >>= shiftDist; + if ( exact && shiftDist ) raiseInexact = (absZ< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +float16_t extF80M_to_f16( const extFloat80_t *aPtr ) +{ + + return extF80_to_f16( *aPtr ); + +} + +#else + +float16_t extF80M_to_f16( const extFloat80_t *aPtr ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + bool sign; + int32_t exp; + uint64_t sig; + struct commonNaN commonNaN; + uint16_t uiZ, sig16; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_extF80MToCommonNaN( aSPtr, &commonNaN ); + uiZ = softfloat_commonNaNToF16UI( &commonNaN ); + } else { + uiZ = packToF16UI( sign, 0x1F, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! (sig & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sig ) { + uiZ = packToF16UI( sign, 0, 0 ); + goto uiZ; + } + exp += softfloat_normExtF80SigM( &sig ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig16 = softfloat_shortShiftRightJam64( sig, 49 ); + exp -= 0x3FF1; + if ( sizeof (int_fast16_t) < sizeof (int32_t) ) { + if ( exp < -0x40 ) exp = -0x40; + } + return softfloat_roundPackToF16( sign, exp, sig16 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +#endif + +/**** ended inlining ../../source/extF80M_to_f16.c ****/ +/**** start inlining ../../source/extF80M_to_f32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +float32_t extF80M_to_f32( const extFloat80_t *aPtr ) +{ + + return extF80_to_f32( *aPtr ); + +} + +#else + +float32_t extF80M_to_f32( const extFloat80_t *aPtr ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + bool sign; + int32_t exp; + uint64_t sig; + struct commonNaN commonNaN; + uint32_t uiZ, sig32; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_extF80MToCommonNaN( aSPtr, &commonNaN ); + uiZ = softfloat_commonNaNToF32UI( &commonNaN ); + } else { + uiZ = packToF32UI( sign, 0xFF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! (sig & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sig ) { + uiZ = packToF32UI( sign, 0, 0 ); + goto uiZ; + } + exp += softfloat_normExtF80SigM( &sig ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig32 = softfloat_shortShiftRightJam64( sig, 33 ); + exp -= 0x3F81; + if ( sizeof (int_fast16_t) < sizeof (int32_t) ) { + if ( exp < -0x1000 ) exp = -0x1000; + } + return softfloat_roundPackToF32( sign, exp, sig32 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +#endif + +/**** ended inlining ../../source/extF80M_to_f32.c ****/ +/**** start inlining ../../source/extF80M_to_f64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +float64_t extF80M_to_f64( const extFloat80_t *aPtr ) +{ + + return extF80_to_f64( *aPtr ); + +} + +#else + +float64_t extF80M_to_f64( const extFloat80_t *aPtr ) +{ + const struct extFloat80M *aSPtr; + uint_fast16_t uiA64; + bool sign; + int32_t exp; + uint64_t sig; + struct commonNaN commonNaN; + uint64_t uiZ; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_extF80MToCommonNaN( aSPtr, &commonNaN ); + uiZ = softfloat_commonNaNToF64UI( &commonNaN ); + } else { + uiZ = packToF64UI( sign, 0x7FF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! (sig & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sig ) { + uiZ = packToF64UI( sign, 0, 0 ); + goto uiZ; + } + exp += softfloat_normExtF80SigM( &sig ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig = softfloat_shortShiftRightJam64( sig, 1 ); + exp -= 0x3C01; + if ( sizeof (int_fast16_t) < sizeof (int32_t) ) { + if ( exp < -0x1000 ) exp = -0x1000; + } + return softfloat_roundPackToF64( sign, exp, sig ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +#endif + +/**** ended inlining ../../source/extF80M_to_f64.c ****/ +/**** start inlining ../../source/extF80M_to_f128M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void extF80M_to_f128M( const extFloat80_t *aPtr, float128_t *zPtr ) +{ + + *zPtr = extF80_to_f128( *aPtr ); + +} + +#else + +void extF80M_to_f128M( const extFloat80_t *aPtr, float128_t *zPtr ) +{ + const struct extFloat80M *aSPtr; + uint32_t *zWPtr; + uint_fast16_t uiA64; + bool sign; + int32_t exp; + uint64_t sig; + struct commonNaN commonNaN; + uint32_t uiZ96; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + zWPtr = (uint32_t *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zWPtr[indexWord( 4, 0 )] = 0; + if ( exp == 0x7FFF ) { + if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_extF80MToCommonNaN( aSPtr, &commonNaN ); + softfloat_commonNaNToF128M( &commonNaN, zWPtr ); + return; + } + uiZ96 = packToF128UI96( sign, 0x7FFF, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) --exp; + if ( ! (sig & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sig ) { + uiZ96 = packToF128UI96( sign, 0, 0 ); + goto uiZ; + } + exp += softfloat_normExtF80SigM( &sig ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zWPtr[indexWord( 4, 1 )] = (uint32_t) sig<<17; + sig >>= 15; + zWPtr[indexWord( 4, 2 )] = sig; + if ( exp < 0 ) { + zWPtr[indexWordHi( 4 )] = sig>>32; + softfloat_shiftRight96M( + &zWPtr[indexMultiwordHi( 4, 3 )], + -exp, + &zWPtr[indexMultiwordHi( 4, 3 )] + ); + exp = 0; + sig = (uint64_t) zWPtr[indexWordHi( 4 )]<<32; + } + zWPtr[indexWordHi( 4 )] = packToF128UI96( sign, exp, sig>>32 ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + zWPtr[indexWord( 4, 3 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = 0; + zWPtr[indexWord( 4, 1 )] = 0; + +} + +#endif + +/**** ended inlining ../../source/extF80M_to_f128M.c ****/ +/**** start inlining ../../source/extF80M_roundToInt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + extF80M_roundToInt( + const extFloat80_t *aPtr, + uint_fast8_t roundingMode, + bool exact, + extFloat80_t *zPtr + ) +{ + + *zPtr = extF80_roundToInt( *aPtr, roundingMode, exact ); + +} + +#else + +void + extF80M_roundToInt( + const extFloat80_t *aPtr, + uint_fast8_t roundingMode, + bool exact, + extFloat80_t *zPtr + ) +{ + const struct extFloat80M *aSPtr; + struct extFloat80M *zSPtr; + uint_fast16_t uiA64, signUI64; + int32_t exp; + uint64_t sigA; + uint_fast16_t uiZ64; + uint64_t sigZ, lastBitMask, roundBitsMask; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + zSPtr = (struct extFloat80M *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + signUI64 = uiA64 & packToExtF80UI64( 1, 0 ); + exp = expExtF80UI64( uiA64 ); + sigA = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( !(sigA & UINT64_C( 0x8000000000000000 )) && (exp != 0x7FFF) ) { + if ( !sigA ) { + uiZ64 = signUI64; + sigZ = 0; + goto uiZ; + } + exp += softfloat_normExtF80SigM( &sigA ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp <= 0x3FFE ) { + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + switch ( roundingMode ) { + case softfloat_round_near_even: + if ( !(sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ) break; + case softfloat_round_near_maxMag: + if ( exp == 0x3FFE ) goto mag1; + break; + case softfloat_round_min: + if ( signUI64 ) goto mag1; + break; + case softfloat_round_max: + if ( !signUI64 ) goto mag1; + break; +#ifdef SOFTFLOAT_ROUND_ODD + case softfloat_round_odd: + goto mag1; +#endif + } + uiZ64 = signUI64; + sigZ = 0; + goto uiZ; + mag1: + uiZ64 = signUI64 | 0x3FFF; + sigZ = UINT64_C( 0x8000000000000000 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x403E <= exp ) { + if ( exp == 0x7FFF ) { + if ( sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_propagateNaNExtF80M( aSPtr, 0, zSPtr ); + return; + } + sigZ = UINT64_C( 0x8000000000000000 ); + } else { + sigZ = sigA; + } + uiZ64 = signUI64 | exp; + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ64 = signUI64 | exp; + lastBitMask = (uint64_t) 1<<(0x403E - exp); + roundBitsMask = lastBitMask - 1; + sigZ = sigA; + if ( roundingMode == softfloat_round_near_maxMag ) { + sigZ += lastBitMask>>1; + } else if ( roundingMode == softfloat_round_near_even ) { + sigZ += lastBitMask>>1; + if ( !(sigZ & roundBitsMask) ) sigZ &= ~lastBitMask; + } else if ( + roundingMode == (signUI64 ? softfloat_round_min : softfloat_round_max) + ) { + sigZ += roundBitsMask; + } + sigZ &= ~roundBitsMask; + if ( !sigZ ) { + ++uiZ64; + sigZ = UINT64_C( 0x8000000000000000 ); + } + if ( sigZ != sigA ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) sigZ |= lastBitMask; +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + uiZ: + zSPtr->signExp = uiZ64; + zSPtr->signif = sigZ; + return; + +} + +#endif + +/**** ended inlining ../../source/extF80M_roundToInt.c ****/ +/**** start inlining ../../source/extF80M_add.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + extF80M_add( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool signA; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + extFloat80_t + (*magsFuncPtr)( + uint_fast16_t, uint_fast64_t, uint_fast16_t, uint_fast64_t, bool ); +#endif + + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + uiA64 = aSPtr->signExp; + uiA0 = aSPtr->signif; + signA = signExtF80UI64( uiA64 ); + uiB64 = bSPtr->signExp; + uiB0 = bSPtr->signif; + signB = signExtF80UI64( uiB64 ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + *zPtr = softfloat_addMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA ); + } else { + *zPtr = softfloat_subMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_addMagsExtF80 : softfloat_subMagsExtF80; + *zPtr = (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA ); +#endif + +} + +#else + +void + extF80M_add( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + + softfloat_addExtF80M( + (const struct extFloat80M *) aPtr, + (const struct extFloat80M *) bPtr, + (struct extFloat80M *) zPtr, + false + ); + +} + +#endif + +/**** ended inlining ../../source/extF80M_add.c ****/ +/**** start inlining ../../source/extF80M_sub.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + extF80M_sub( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool signA; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + extFloat80_t + (*magsFuncPtr)( + uint_fast16_t, uint_fast64_t, uint_fast16_t, uint_fast64_t, bool ); +#endif + + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + uiA64 = aSPtr->signExp; + uiA0 = aSPtr->signif; + signA = signExtF80UI64( uiA64 ); + uiB64 = bSPtr->signExp; + uiB0 = bSPtr->signif; + signB = signExtF80UI64( uiB64 ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + *zPtr = softfloat_subMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA ); + } else { + *zPtr = softfloat_addMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_subMagsExtF80 : softfloat_addMagsExtF80; + *zPtr = (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA ); +#endif + +} + +#else + +void + extF80M_sub( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + + softfloat_addExtF80M( + (const struct extFloat80M *) aPtr, + (const struct extFloat80M *) bPtr, + (struct extFloat80M *) zPtr, + true + ); + +} + +#endif + +/**** ended inlining ../../source/extF80M_sub.c ****/ +/**** start inlining ../../source/extF80M_mul.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + extF80M_mul( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + + *zPtr = extF80_mul( *aPtr, *bPtr ); + +} + +#else + +void + extF80M_mul( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + struct extFloat80M *zSPtr; + uint_fast16_t uiA64; + int32_t expA; + uint_fast16_t uiB64; + int32_t expB; + bool signZ; + uint_fast16_t exp, uiZ64; + uint64_t uiZ0, sigA, sigB; + int32_t expZ; + uint32_t sigProd[4], *extSigZPtr; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + zSPtr = (struct extFloat80M *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + expA = expExtF80UI64( uiA64 ); + uiB64 = bSPtr->signExp; + expB = expExtF80UI64( uiB64 ); + signZ = signExtF80UI64( uiA64 ) ^ signExtF80UI64( uiB64 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) { + if ( softfloat_tryPropagateNaNExtF80M( aSPtr, bSPtr, zSPtr ) ) return; + if ( + (! aSPtr->signif && (expA != 0x7FFF)) + || (! bSPtr->signif && (expB != 0x7FFF)) + ) { + softfloat_invalidExtF80M( zSPtr ); + return; + } + uiZ64 = packToExtF80UI64( signZ, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) expA = 1; + sigA = aSPtr->signif; + if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigA ) goto zero; + expA += softfloat_normExtF80SigM( &sigA ); + } + if ( ! expB ) expB = 1; + sigB = bSPtr->signif; + if ( ! (sigB & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigB ) goto zero; + expB += softfloat_normExtF80SigM( &sigB ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x3FFE; + softfloat_mul64To128M( sigA, sigB, sigProd ); + if ( sigProd[indexWordLo( 4 )] ) sigProd[indexWord( 4, 1 )] |= 1; + extSigZPtr = &sigProd[indexMultiwordHi( 4, 3 )]; + if ( sigProd[indexWordHi( 4 )] < 0x80000000 ) { + --expZ; + softfloat_add96M( extSigZPtr, extSigZPtr, extSigZPtr ); + } + softfloat_roundPackMToExtF80M( + signZ, expZ, extSigZPtr, extF80_roundingPrecision, zSPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ64 = packToExtF80UI64( signZ, 0 ); + uiZ0 = 0; + uiZ: + zSPtr->signExp = uiZ64; + zSPtr->signif = uiZ0; + +} + +#endif + +/**** ended inlining ../../source/extF80M_mul.c ****/ +/**** start inlining ../../source/extF80M_div.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + extF80M_div( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + + *zPtr = extF80_div( *aPtr, *bPtr ); + +} + +#else + +void + extF80M_div( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + struct extFloat80M *zSPtr; + uint_fast16_t uiA64; + int32_t expA; + uint_fast16_t uiB64; + int32_t expB; + bool signZ; + uint64_t sigA, x64; + int32_t expZ; + int shiftDist; + uint32_t y[3], recip32, sigB[3]; + int ix; + uint32_t q, qs[2]; + uint_fast16_t uiZ64; + uint64_t uiZ0; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + zSPtr = (struct extFloat80M *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + expA = expExtF80UI64( uiA64 ); + uiB64 = bSPtr->signExp; + expB = expExtF80UI64( uiB64 ); + signZ = signExtF80UI64( uiA64 ) ^ signExtF80UI64( uiB64 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) { + if ( softfloat_tryPropagateNaNExtF80M( aSPtr, bSPtr, zSPtr ) ) return; + if ( expA == 0x7FFF ) { + if ( expB == 0x7FFF ) goto invalid; + goto infinity; + } + goto zero; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sigA = aSPtr->signif; + x64 = bSPtr->signif; + if ( ! expB ) expB = 1; + if ( ! (x64 & UINT64_C( 0x8000000000000000 )) ) { + if ( ! x64 ) { + if ( ! sigA ) goto invalid; + softfloat_raiseFlags( softfloat_flag_infinite ); + goto infinity; + } + expB += softfloat_normExtF80SigM( &x64 ); + } + if ( ! expA ) expA = 1; + if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigA ) goto zero; + expA += softfloat_normExtF80SigM( &sigA ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA - expB + 0x3FFF; + shiftDist = 29; + if ( sigA < x64 ) { + --expZ; + shiftDist = 30; + } + softfloat_shortShiftLeft64To96M( sigA, shiftDist, y ); + recip32 = softfloat_approxRecip32_1( x64>>32 ); + sigB[indexWord( 3, 0 )] = (uint32_t) x64<<30; + x64 >>= 2; + sigB[indexWord( 3, 2 )] = x64>>32; + sigB[indexWord( 3, 1 )] = x64; + ix = 2; + for (;;) { + x64 = (uint64_t) y[indexWordHi( 3 )] * recip32; + q = (x64 + 0x80000000)>>32; + --ix; + if ( ix < 0 ) break; + softfloat_remStep96MBy32( y, 29, sigB, q, y ); + if ( y[indexWordHi( 3 )] & 0x80000000 ) { + --q; + softfloat_add96M( y, sigB, y ); + } + qs[ix] = q; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ((q + 1) & 0x3FFFFF) < 2 ) { + softfloat_remStep96MBy32( y, 29, sigB, q, y ); + if ( y[indexWordHi( 3 )] & 0x80000000 ) { + --q; + softfloat_add96M( y, sigB, y ); + } else if ( softfloat_compare96M( sigB, y ) <= 0 ) { + ++q; + softfloat_sub96M( y, sigB, y ); + } + if ( + y[indexWordLo( 3 )] || y[indexWord( 3, 1 )] || y[indexWord( 3, 2 )] + ) { + q |= 1; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + x64 = (uint64_t) q<<9; + y[indexWord( 3, 0 )] = x64; + x64 = ((uint64_t) qs[0]<<6) + (x64>>32); + y[indexWord( 3, 1 )] = x64; + y[indexWord( 3, 2 )] = (qs[1]<<3) + (x64>>32); + softfloat_roundPackMToExtF80M( + signZ, expZ, y, extF80_roundingPrecision, zSPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_invalidExtF80M( zSPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infinity: + uiZ64 = packToExtF80UI64( signZ, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ64 = packToExtF80UI64( signZ, 0 ); + uiZ0 = 0; + uiZ: + zSPtr->signExp = uiZ64; + zSPtr->signif = uiZ0; + +} + +#endif + +/**** ended inlining ../../source/extF80M_div.c ****/ +/**** start inlining ../../source/extF80M_rem.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + extF80M_rem( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + + *zPtr = extF80_rem( *aPtr, *bPtr ); + +} + +#else + +void + extF80M_rem( + const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + struct extFloat80M *zSPtr; + uint_fast16_t uiA64; + int32_t expA, expB; + uint64_t x64; + bool signRem; + uint64_t sigA; + int32_t expDiff; + uint32_t rem[3], x[3], sig32B, q, recip32, rem2[3], *remPtr, *altRemPtr; + uint32_t *newRemPtr, wordMeanRem; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + zSPtr = (struct extFloat80M *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + expA = expExtF80UI64( uiA64 ); + expB = expExtF80UI64( bSPtr->signExp ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) { + if ( softfloat_tryPropagateNaNExtF80M( aSPtr, bSPtr, zSPtr ) ) return; + if ( expA == 0x7FFF ) goto invalid; + /*-------------------------------------------------------------------- + | If we get here, then argument b is an infinity and `expB' is 0x7FFF; + | Doubling `expB' is an easy way to ensure that `expDiff' later is + | less than -1, which will result in returning a canonicalized version + | of argument a. + *--------------------------------------------------------------------*/ + expB += expB; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) expB = 1; + x64 = bSPtr->signif; + if ( ! (x64 & UINT64_C( 0x8000000000000000 )) ) { + if ( ! x64 ) goto invalid; + expB += softfloat_normExtF80SigM( &x64 ); + } + signRem = signExtF80UI64( uiA64 ); + if ( ! expA ) expA = 1; + sigA = aSPtr->signif; + if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) { + if ( ! sigA ) { + expA = 0; + goto copyA; + } + expA += softfloat_normExtF80SigM( &sigA ); + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( expDiff < -1 ) goto copyA; + rem[indexWord( 3, 2 )] = sigA>>34; + rem[indexWord( 3, 1 )] = sigA>>2; + rem[indexWord( 3, 0 )] = (uint32_t) sigA<<30; + x[indexWord( 3, 0 )] = (uint32_t) x64<<30; + sig32B = x64>>32; + x64 >>= 2; + x[indexWord( 3, 2 )] = x64>>32; + x[indexWord( 3, 1 )] = x64; + if ( expDiff < 1 ) { + if ( expDiff ) { + --expB; + softfloat_add96M( x, x, x ); + q = 0; + } else { + q = (softfloat_compare96M( x, rem ) <= 0); + if ( q ) softfloat_sub96M( rem, x, rem ); + } + } else { + recip32 = softfloat_approxRecip32_1( sig32B ); + expDiff -= 30; + for (;;) { + x64 = (uint64_t) rem[indexWordHi( 3 )] * recip32; + if ( expDiff < 0 ) break; + q = (x64 + 0x80000000)>>32; + softfloat_remStep96MBy32( rem, 29, x, q, rem ); + if ( rem[indexWordHi( 3 )] & 0x80000000 ) { + softfloat_add96M( rem, x, rem ); + } + expDiff -= 29; + } + /*-------------------------------------------------------------------- + | (`expDiff' cannot be less than -29 here.) + *--------------------------------------------------------------------*/ + q = (uint32_t) (x64>>32)>>(~expDiff & 31); + softfloat_remStep96MBy32( rem, expDiff + 30, x, q, rem ); + if ( rem[indexWordHi( 3 )] & 0x80000000 ) { + remPtr = rem; + altRemPtr = rem2; + softfloat_add96M( remPtr, x, altRemPtr ); + goto selectRem; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + remPtr = rem; + altRemPtr = rem2; + do { + ++q; + newRemPtr = altRemPtr; + softfloat_sub96M( remPtr, x, newRemPtr ); + altRemPtr = remPtr; + remPtr = newRemPtr; + } while ( ! (remPtr[indexWordHi( 3 )] & 0x80000000) ); + selectRem: + softfloat_add96M( remPtr, altRemPtr, x ); + wordMeanRem = x[indexWordHi( 3 )]; + if ( + (wordMeanRem & 0x80000000) + || (! wordMeanRem && (q & 1) && ! x[indexWord( 3, 0 )] + && ! x[indexWord( 3, 1 )]) + ) { + remPtr = altRemPtr; + } + if ( remPtr[indexWordHi( 3 )] & 0x80000000 ) { + signRem = ! signRem; + softfloat_negX96M( remPtr ); + } + softfloat_normRoundPackMToExtF80M( signRem, expB + 2, remPtr, 80, zSPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_invalidExtF80M( zSPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + copyA: + if ( expA < 1 ) { + sigA >>= 1 - expA; + expA = 0; + } + zSPtr->signExp = packToExtF80UI64( signRem, expA ); + zSPtr->signif = sigA; + +} + +#endif + +/**** ended inlining ../../source/extF80M_rem.c ****/ +/**** start inlining ../../source/extF80M_sqrt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void extF80M_sqrt( const extFloat80_t *aPtr, extFloat80_t *zPtr ) +{ + + *zPtr = extF80_sqrt( *aPtr ); + +} + +#else + +void extF80M_sqrt( const extFloat80_t *aPtr, extFloat80_t *zPtr ) +{ + const struct extFloat80M *aSPtr; + struct extFloat80M *zSPtr; + uint_fast16_t uiA64, signUI64; + int32_t expA; + uint64_t rem64; + int32_t expZ; + uint32_t rem96[3], sig32A, recipSqrt32, sig32Z, q; + uint64_t sig64Z, x64; + uint32_t rem32, term[4], rem[4], extSigZ[3]; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + zSPtr = (struct extFloat80M *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + signUI64 = uiA64 & packToExtF80UI64( 1, 0 ); + expA = expExtF80UI64( uiA64 ); + rem64 = aSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( rem64 & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_propagateNaNExtF80M( aSPtr, 0, zSPtr ); + return; + } + if ( signUI64 ) goto invalid; + rem64 = UINT64_C( 0x8000000000000000 ); + goto copyA; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) expA = 1; + if ( ! (rem64 & UINT64_C( 0x8000000000000000 )) ) { + if ( ! rem64 ) { + uiA64 = signUI64; + goto copyA; + } + expA += softfloat_normExtF80SigM( &rem64 ); + } + if ( signUI64 ) goto invalid; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = ((expA - 0x3FFF)>>1) + 0x3FFF; + expA &= 1; + softfloat_shortShiftLeft64To96M( rem64, 30 - expA, rem96 ); + sig32A = rem64>>32; + recipSqrt32 = softfloat_approxRecipSqrt32_1( expA, sig32A ); + sig32Z = ((uint64_t) sig32A * recipSqrt32)>>32; + if ( expA ) sig32Z >>= 1; + rem64 = + ((uint64_t) rem96[indexWord( 3, 2 )]<<32 | rem96[indexWord( 3, 1 )]) + - (uint64_t) sig32Z * sig32Z; + rem96[indexWord( 3, 2 )] = rem64>>32; + rem96[indexWord( 3, 1 )] = rem64; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = ((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32; + sig64Z = ((uint64_t) sig32Z<<32) + ((uint64_t) q<<3); + term[indexWord( 3, 2 )] = 0; + /*------------------------------------------------------------------------ + | (Repeating this loop is a rare occurrence.) + *------------------------------------------------------------------------*/ + for (;;) { + x64 = ((uint64_t) sig32Z<<32) + sig64Z; + term[indexWord( 3, 1 )] = x64>>32; + term[indexWord( 3, 0 )] = x64; + softfloat_remStep96MBy32( + rem96, 29, term, q, &rem[indexMultiwordHi( 4, 3 )] ); + rem32 = rem[indexWord( 4, 3 )]; + if ( ! (rem32 & 0x80000000) ) break; + --q; + sig64Z -= 1<<3; + } + rem64 = (uint64_t) rem32<<32 | rem[indexWord( 4, 2 )]; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = (((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32) + 2; + if ( rem64>>34 ) q += recipSqrt32; + x64 = (uint64_t) q<<7; + extSigZ[indexWord( 3, 0 )] = x64; + x64 = (sig64Z<<1) + (x64>>32); + extSigZ[indexWord( 3, 2 )] = x64>>32; + extSigZ[indexWord( 3, 1 )] = x64; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (q & 0xFFFFFF) <= 2 ) { + q &= ~(uint32_t) 0xFFFF; + extSigZ[indexWordLo( 3 )] = q<<7; + x64 = sig64Z + (q>>27); + term[indexWord( 4, 3 )] = 0; + term[indexWord( 4, 2 )] = x64>>32; + term[indexWord( 4, 1 )] = x64; + term[indexWord( 4, 0 )] = q<<5; + rem[indexWord( 4, 0 )] = 0; + softfloat_remStep128MBy32( rem, 28, term, q, rem ); + q = rem[indexWordHi( 4 )]; + if ( q & 0x80000000 ) { + softfloat_sub1X96M( extSigZ ); + } else { + if ( q || rem[indexWord( 4, 1 )] || rem[indexWord( 4, 2 )] ) { + extSigZ[indexWordLo( 3 )] |= 1; + } + } + } + softfloat_roundPackMToExtF80M( + 0, expZ, extSigZ, extF80_roundingPrecision, zSPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_invalidExtF80M( zSPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + copyA: + zSPtr->signExp = uiA64; + zSPtr->signif = rem64; + +} + +#endif + +/**** ended inlining ../../source/extF80M_sqrt.c ****/ +/**** start inlining ../../source/extF80M_eq.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool extF80M_eq( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + + return extF80_eq( *aPtr, *bPtr ); + +} + +#else + +bool extF80M_eq( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + uint_fast16_t uiA64; + uint64_t uiA0; + uint_fast16_t uiB64; + uint64_t uiB0; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + uiA0 = aSPtr->signif; + uiB64 = bSPtr->signExp; + uiB0 = bSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNExtF80UI( uiA64, uiA0 ) + || softfloat_isSigNaNExtF80UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( uiA0 == uiB0 ) { + return (uiA64 == uiB64) || ! uiA0; + } else { + if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) { + return ! softfloat_compareNonnormExtF80M( aSPtr, bSPtr ); + } + return false; + } + +} + +#endif + +/**** ended inlining ../../source/extF80M_eq.c ****/ +/**** start inlining ../../source/extF80M_le.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool extF80M_le( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + + return extF80_le( *aPtr, *bPtr ); + +} + +#else + +bool extF80M_le( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + uint_fast16_t uiA64; + uint64_t uiA0; + uint_fast16_t uiB64; + uint64_t uiB0; + bool signA, ltMags; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + uiA0 = aSPtr->signif; + uiB64 = bSPtr->signExp; + uiB0 = bSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + signA = signExtF80UI64( uiA64 ); + if ( (uiA64 ^ uiB64) & 0x8000 ) { + /*-------------------------------------------------------------------- + | Signs are different. + *--------------------------------------------------------------------*/ + return signA || ! (uiA0 | uiB0); + } else { + /*-------------------------------------------------------------------- + | Signs are the same. + *--------------------------------------------------------------------*/ + if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) { + return (softfloat_compareNonnormExtF80M( aSPtr, bSPtr ) <= 0); + } + if ( uiA64 == uiB64 ) { + if ( uiA0 == uiB0 ) return true; + ltMags = (uiA0 < uiB0); + } else { + ltMags = (uiA64 < uiB64); + } + return signA ^ ltMags; + } + +} + +#endif + +/**** ended inlining ../../source/extF80M_le.c ****/ +/**** start inlining ../../source/extF80M_lt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool extF80M_lt( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + + return extF80_lt( *aPtr, *bPtr ); + +} + +#else + +bool extF80M_lt( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + uint_fast16_t uiA64; + uint64_t uiA0; + uint_fast16_t uiB64; + uint64_t uiB0; + bool signA, ltMags; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + uiA0 = aSPtr->signif; + uiB64 = bSPtr->signExp; + uiB0 = bSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + signA = signExtF80UI64( uiA64 ); + if ( (uiA64 ^ uiB64) & 0x8000 ) { + /*-------------------------------------------------------------------- + | Signs are different. + *--------------------------------------------------------------------*/ + return signA && ((uiA0 | uiB0) != 0); + } else { + /*-------------------------------------------------------------------- + | Signs are the same. + *--------------------------------------------------------------------*/ + if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) { + return (softfloat_compareNonnormExtF80M( aSPtr, bSPtr ) < 0); + } + if ( uiA64 == uiB64 ) { + if ( uiA0 == uiB0 ) return false; + ltMags = (uiA0 < uiB0); + } else { + ltMags = (uiA64 < uiB64); + } + return signA ^ ltMags; + } + +} + +#endif + +/**** ended inlining ../../source/extF80M_lt.c ****/ +/**** start inlining ../../source/extF80M_eq_signaling.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool extF80M_eq_signaling( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + + return extF80_eq_signaling( *aPtr, *bPtr ); + +} + +#else + +bool extF80M_eq_signaling( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + uint_fast16_t uiA64; + uint64_t uiA0; + uint_fast16_t uiB64; + uint64_t uiB0; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + uiA0 = aSPtr->signif; + uiB64 = bSPtr->signExp; + uiB0 = bSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( uiA0 == uiB0 ) { + return (uiA64 == uiB64) || ! uiA0; + } else { + if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) { + return ! softfloat_compareNonnormExtF80M( aSPtr, bSPtr ); + } + return false; + } + +} + +#endif + +/**** ended inlining ../../source/extF80M_eq_signaling.c ****/ +/**** start inlining ../../source/extF80M_le_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool extF80M_le_quiet( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + + return extF80_le_quiet( *aPtr, *bPtr ); + +} + +#else + +bool extF80M_le_quiet( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + uint_fast16_t uiA64; + uint64_t uiA0; + uint_fast16_t uiB64; + uint64_t uiB0; + bool signA, ltMags; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + uiA0 = aSPtr->signif; + uiB64 = bSPtr->signExp; + uiB0 = bSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNExtF80UI( uiA64, uiA0 ) + || softfloat_isSigNaNExtF80UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + signA = signExtF80UI64( uiA64 ); + if ( (uiA64 ^ uiB64) & 0x8000 ) { + /*-------------------------------------------------------------------- + | Signs are different. + *--------------------------------------------------------------------*/ + return signA || ! (uiA0 | uiB0); + } else { + /*-------------------------------------------------------------------- + | Signs are the same. + *--------------------------------------------------------------------*/ + if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) { + return (softfloat_compareNonnormExtF80M( aSPtr, bSPtr ) <= 0); + } + if ( uiA64 == uiB64 ) { + if ( uiA0 == uiB0 ) return true; + ltMags = (uiA0 < uiB0); + } else { + ltMags = (uiA64 < uiB64); + } + return signA ^ ltMags; + } + +} + +#endif + +/**** ended inlining ../../source/extF80M_le_quiet.c ****/ +/**** start inlining ../../source/extF80M_lt_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool extF80M_lt_quiet( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + + return extF80_lt_quiet( *aPtr, *bPtr ); + +} + +#else + +bool extF80M_lt_quiet( const extFloat80_t *aPtr, const extFloat80_t *bPtr ) +{ + const struct extFloat80M *aSPtr, *bSPtr; + uint_fast16_t uiA64; + uint64_t uiA0; + uint_fast16_t uiB64; + uint64_t uiB0; + bool signA, ltMags; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aSPtr = (const struct extFloat80M *) aPtr; + bSPtr = (const struct extFloat80M *) bPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA64 = aSPtr->signExp; + uiA0 = aSPtr->signif; + uiB64 = bSPtr->signExp; + uiB0 = bSPtr->signif; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNExtF80UI( uiA64, uiA0 ) + || softfloat_isSigNaNExtF80UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + signA = signExtF80UI64( uiA64 ); + if ( (uiA64 ^ uiB64) & 0x8000 ) { + /*-------------------------------------------------------------------- + | Signs are different. + *--------------------------------------------------------------------*/ + return signA && ((uiA0 | uiB0) != 0); + } else { + /*-------------------------------------------------------------------- + | Signs are the same. + *--------------------------------------------------------------------*/ + if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) { + return (softfloat_compareNonnormExtF80M( aSPtr, bSPtr ) < 0); + } + if ( uiA64 == uiB64 ) { + if ( uiA0 == uiB0 ) return false; + ltMags = (uiA0 < uiB0); + } else { + ltMags = (uiA64 < uiB64); + } + return signA ^ ltMags; + } + +} + +#endif + +/**** ended inlining ../../source/extF80M_lt_quiet.c ****/ +/**** start inlining ../../source/f128_to_ui32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t + f128_to_ui32( float128_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig64; + int_fast32_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + sig64 = fracF128UI64( uiA64 ) | (uiA0 != 0); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (ui32_fromNaN != ui32_fromPosOverflow) || (ui32_fromNaN != ui32_fromNegOverflow) + if ( (exp == 0x7FFF) && sig64 ) { +#if (ui32_fromNaN == ui32_fromPosOverflow) + sign = 0; +#elif (ui32_fromNaN == ui32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return ui32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 ); + shiftDist = 0x4023 - exp; + if ( 0 < shiftDist ) { + sig64 = softfloat_shiftRightJam64( sig64, shiftDist ); + } + return softfloat_roundToUI32( sign, sig64, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f128_to_ui32.c ****/ +/**** start inlining ../../source/f128_to_ui64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t + f128_to_ui64( float128_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig64, sig0; + int_fast32_t shiftDist; + struct uint128 sig128; + struct uint64_extra sigExtra; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + sig64 = fracF128UI64( uiA64 ); + sig0 = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x402F - exp; + if ( shiftDist <= 0 ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( shiftDist < -15 ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig64 | sig0) ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sig64 |= UINT64_C( 0x0001000000000000 ); + if ( shiftDist ) { + sig128 = softfloat_shortShiftLeft128( sig64, sig0, -shiftDist ); + sig64 = sig128.v64; + sig0 = sig128.v0; + } + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 ); + sigExtra = softfloat_shiftRightJam64Extra( sig64, sig0, shiftDist ); + sig64 = sigExtra.v; + sig0 = sigExtra.extra; + } + return softfloat_roundToUI64( sign, sig64, sig0, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f128_to_ui64.c ****/ +/**** start inlining ../../source/f128_to_i32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t f128_to_i32( float128_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig64, sig0; + int_fast32_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + sig64 = fracF128UI64( uiA64 ); + sig0 = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (i32_fromNaN != i32_fromPosOverflow) || (i32_fromNaN != i32_fromNegOverflow) + if ( (exp == 0x7FFF) && (sig64 | sig0) ) { +#if (i32_fromNaN == i32_fromPosOverflow) + sign = 0; +#elif (i32_fromNaN == i32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return i32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 ); + sig64 |= (sig0 != 0); + shiftDist = 0x4023 - exp; + if ( 0 < shiftDist ) sig64 = softfloat_shiftRightJam64( sig64, shiftDist ); + return softfloat_roundToI32( sign, sig64, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f128_to_i32.c ****/ +/**** start inlining ../../source/f128_to_i64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t f128_to_i64( float128_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig64, sig0; + int_fast32_t shiftDist; + struct uint128 sig128; + struct uint64_extra sigExtra; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + sig64 = fracF128UI64( uiA64 ); + sig0 = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x402F - exp; + if ( shiftDist <= 0 ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( shiftDist < -15 ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig64 | sig0) ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sig64 |= UINT64_C( 0x0001000000000000 ); + if ( shiftDist ) { + sig128 = softfloat_shortShiftLeft128( sig64, sig0, -shiftDist ); + sig64 = sig128.v64; + sig0 = sig128.v0; + } + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 ); + sigExtra = softfloat_shiftRightJam64Extra( sig64, sig0, shiftDist ); + sig64 = sigExtra.v; + sig0 = sigExtra.extra; + } + return softfloat_roundToI64( sign, sig64, sig0, roundingMode, exact ); + +} + +/**** ended inlining ../../source/f128_to_i64.c ****/ +/**** start inlining ../../source/f128_to_ui32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast32_t f128_to_ui32_r_minMag( float128_t a, bool exact ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + int_fast32_t exp; + uint_fast64_t sig64; + int_fast32_t shiftDist; + bool sign; + uint_fast32_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + exp = expF128UI64( uiA64 ); + sig64 = fracF128UI64( uiA64 ) | (uiA0 != 0); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x402F - exp; + if ( 49 <= shiftDist ) { + if ( exact && (exp | sig64) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF128UI64( uiA64 ); + if ( sign || (shiftDist < 17) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && sig64 ? ui32_fromNaN + : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig64 |= UINT64_C( 0x0001000000000000 ); + z = sig64>>shiftDist; + if ( exact && ((uint_fast64_t) z< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +uint_fast64_t f128_to_ui64_r_minMag( float128_t a, bool exact ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig64, sig0; + int_fast32_t shiftDist; + int_fast8_t negShiftDist; + uint_fast64_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + sig64 = fracF128UI64( uiA64 ); + sig0 = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x402F - exp; + if ( shiftDist < 0 ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( sign || (shiftDist < -15) ) goto invalid; + sig64 |= UINT64_C( 0x0001000000000000 ); + negShiftDist = -shiftDist; + z = sig64<>(shiftDist & 63); + if ( exact && (uint64_t) (sig0<>shiftDist; + if ( exact && (sig0 || (z< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast32_t f128_to_i32_r_minMag( float128_t a, bool exact ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + int_fast32_t exp; + uint_fast64_t sig64; + int_fast32_t shiftDist; + bool sign; + int_fast32_t absZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + exp = expF128UI64( uiA64 ); + sig64 = fracF128UI64( uiA64 ) | (uiA0 != 0); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x402F - exp; + if ( 49 <= shiftDist ) { + if ( exact && (exp | sig64) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF128UI64( uiA64 ); + if ( shiftDist < 18 ) { + if ( + sign && (shiftDist == 17) + && (sig64 < UINT64_C( 0x0000000000020000 )) + ) { + if ( exact && sig64 ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return -0x7FFFFFFF - 1; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && sig64 ? i32_fromNaN + : sign ? i32_fromNegOverflow : i32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig64 |= UINT64_C( 0x0001000000000000 ); + absZ = sig64>>shiftDist; + if ( + exact && ((uint_fast64_t) (uint_fast32_t) absZ< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +int_fast64_t f128_to_i64_r_minMag( float128_t a, bool exact ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig64, sig0; + int_fast32_t shiftDist; + int_fast8_t negShiftDist; + int_fast64_t absZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + sig64 = fracF128UI64( uiA64 ); + sig0 = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x402F - exp; + if ( shiftDist < 0 ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( shiftDist < -14 ) { + if ( + (uiA64 == UINT64_C( 0xC03E000000000000 )) + && (sig0 < UINT64_C( 0x0002000000000000 )) + ) { + if ( exact && sig0 ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return -INT64_C( 0x7FFFFFFFFFFFFFFF ) - 1; + } + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && (sig64 | sig0) ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + sig64 |= UINT64_C( 0x0001000000000000 ); + negShiftDist = -shiftDist; + absZ = sig64<>(shiftDist & 63); + if ( exact && (uint64_t) (sig0<>shiftDist; + if ( exact && (sig0 || (absZ< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float16_t f128_to_f16( float128_t a ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t frac64; + struct commonNaN commonNaN; + uint_fast16_t uiZ, frac16; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + frac64 = fracF128UI64( uiA64 ) | (uiA0 != 0); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( frac64 ) { + softfloat_f128UIToCommonNaN( uiA64, uiA0, &commonNaN ); + uiZ = softfloat_commonNaNToF16UI( &commonNaN ); + } else { + uiZ = packToF16UI( sign, 0x1F, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac16 = softfloat_shortShiftRightJam64( frac64, 34 ); + if ( ! (exp | frac16) ) { + uiZ = packToF16UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp -= 0x3FF1; + if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) { + if ( exp < -0x40 ) exp = -0x40; + } + return softfloat_roundPackToF16( sign, exp, frac16 | 0x4000 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f128_to_f16.c ****/ +/**** start inlining ../../source/f128_to_f32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float32_t f128_to_f32( float128_t a ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t frac64; + struct commonNaN commonNaN; + uint_fast32_t uiZ, frac32; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + frac64 = fracF128UI64( uiA64 ) | (uiA0 != 0); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( frac64 ) { + softfloat_f128UIToCommonNaN( uiA64, uiA0, &commonNaN ); + uiZ = softfloat_commonNaNToF32UI( &commonNaN ); + } else { + uiZ = packToF32UI( sign, 0xFF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac32 = softfloat_shortShiftRightJam64( frac64, 18 ); + if ( ! (exp | frac32) ) { + uiZ = packToF32UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp -= 0x3F81; + if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) { + if ( exp < -0x1000 ) exp = -0x1000; + } + return softfloat_roundPackToF32( sign, exp, frac32 | 0x40000000 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f128_to_f32.c ****/ +/**** start inlining ../../source/f128_to_extF80.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +extFloat80_t f128_to_extF80( float128_t a ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t frac64, frac0; + struct commonNaN commonNaN; + struct uint128 uiZ; + uint_fast16_t uiZ64; + uint_fast64_t uiZ0; + struct exp32_sig128 normExpSig; + struct uint128 sig128; + union { struct extFloat80M s; extFloat80_t f; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + frac64 = fracF128UI64( uiA64 ); + frac0 = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( frac64 | frac0 ) { + softfloat_f128UIToCommonNaN( uiA64, uiA0, &commonNaN ); + uiZ = softfloat_commonNaNToExtF80UI( &commonNaN ); + uiZ64 = uiZ.v64; + uiZ0 = uiZ.v0; + } else { + uiZ64 = packToExtF80UI64( sign, 0x7FFF ); + uiZ0 = UINT64_C( 0x8000000000000000 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! (frac64 | frac0) ) { + uiZ64 = packToExtF80UI64( sign, 0 ); + uiZ0 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF128Sig( frac64, frac0 ); + exp = normExpSig.exp; + frac64 = normExpSig.sig.v64; + frac0 = normExpSig.sig.v0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig128 = + softfloat_shortShiftLeft128( + frac64 | UINT64_C( 0x0001000000000000 ), frac0, 15 ); + return softfloat_roundPackToExtF80( sign, exp, sig128.v64, sig128.v0, 80 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.s.signExp = uiZ64; + uZ.s.signif = uiZ0; + return uZ.f; + +} + +/**** ended inlining ../../source/f128_to_extF80.c ****/ +/**** start inlining ../../source/f128_to_f64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float64_t f128_to_f64( float128_t a ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t frac64, frac0; + struct commonNaN commonNaN; + uint_fast64_t uiZ; + struct uint128 frac128; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + sign = signF128UI64( uiA64 ); + exp = expF128UI64( uiA64 ); + frac64 = fracF128UI64( uiA64 ); + frac0 = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( frac64 | frac0 ) { + softfloat_f128UIToCommonNaN( uiA64, uiA0, &commonNaN ); + uiZ = softfloat_commonNaNToF64UI( &commonNaN ); + } else { + uiZ = packToF64UI( sign, 0x7FF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac128 = softfloat_shortShiftLeft128( frac64, frac0, 14 ); + frac64 = frac128.v64 | (frac128.v0 != 0); + if ( ! (exp | frac64) ) { + uiZ = packToF64UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp -= 0x3C01; + if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) { + if ( exp < -0x1000 ) exp = -0x1000; + } + return + softfloat_roundPackToF64( + sign, exp, frac64 | UINT64_C( 0x4000000000000000 ) ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f128_to_f64.c ****/ +/**** start inlining ../../source/f128_roundToInt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t + f128_roundToInt( float128_t a, uint_fast8_t roundingMode, bool exact ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + int_fast32_t exp; + struct uint128 uiZ; + uint_fast64_t lastBitMask0, roundBitsMask; + bool roundNearEven; + uint_fast64_t lastBitMask64; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + exp = expF128UI64( uiA64 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x402F <= exp ) { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( 0x406F <= exp ) { + if ( (exp == 0x7FFF) && (fracF128UI64( uiA64 ) | uiA0) ) { + uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, 0, 0 ); + goto uiZ; + } + return a; + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + lastBitMask0 = (uint_fast64_t) 2<<(0x406E - exp); + roundBitsMask = lastBitMask0 - 1; + uiZ.v64 = uiA64; + uiZ.v0 = uiA0; + roundNearEven = (roundingMode == softfloat_round_near_even); + if ( roundNearEven || (roundingMode == softfloat_round_near_maxMag) ) { + if ( exp == 0x402F ) { + if ( UINT64_C( 0x8000000000000000 ) <= uiZ.v0 ) { + ++uiZ.v64; + if ( + roundNearEven + && (uiZ.v0 == UINT64_C( 0x8000000000000000 )) + ) { + uiZ.v64 &= ~1; + } + } + } else { + uiZ = softfloat_add128( uiZ.v64, uiZ.v0, 0, lastBitMask0>>1 ); + if ( roundNearEven && !(uiZ.v0 & roundBitsMask) ) { + uiZ.v0 &= ~lastBitMask0; + } + } + } else if ( + roundingMode + == (signF128UI64( uiZ.v64 ) ? softfloat_round_min + : softfloat_round_max) + ) { + uiZ = softfloat_add128( uiZ.v64, uiZ.v0, 0, roundBitsMask ); + } + uiZ.v0 &= ~roundBitsMask; + lastBitMask64 = !lastBitMask0; + } else { + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + if ( exp < 0x3FFF ) { + if ( !((uiA64 & UINT64_C( 0x7FFFFFFFFFFFFFFF )) | uiA0) ) return a; + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + uiZ.v64 = uiA64 & packToF128UI64( 1, 0, 0 ); + uiZ.v0 = 0; + switch ( roundingMode ) { + case softfloat_round_near_even: + if ( !(fracF128UI64( uiA64 ) | uiA0) ) break; + case softfloat_round_near_maxMag: + if ( exp == 0x3FFE ) uiZ.v64 |= packToF128UI64( 0, 0x3FFF, 0 ); + break; + case softfloat_round_min: + if ( uiZ.v64 ) uiZ.v64 = packToF128UI64( 1, 0x3FFF, 0 ); + break; + case softfloat_round_max: + if ( !uiZ.v64 ) uiZ.v64 = packToF128UI64( 0, 0x3FFF, 0 ); + break; +#ifdef SOFTFLOAT_ROUND_ODD + case softfloat_round_odd: + uiZ.v64 |= packToF128UI64( 0, 0x3FFF, 0 ); + break; +#endif + } + goto uiZ; + } + /*-------------------------------------------------------------------- + *--------------------------------------------------------------------*/ + uiZ.v64 = uiA64; + uiZ.v0 = 0; + lastBitMask64 = (uint_fast64_t) 1<<(0x402F - exp); + roundBitsMask = lastBitMask64 - 1; + if ( roundingMode == softfloat_round_near_maxMag ) { + uiZ.v64 += lastBitMask64>>1; + } else if ( roundingMode == softfloat_round_near_even ) { + uiZ.v64 += lastBitMask64>>1; + if ( !((uiZ.v64 & roundBitsMask) | uiA0) ) { + uiZ.v64 &= ~lastBitMask64; + } + } else if ( + roundingMode + == (signF128UI64( uiZ.v64 ) ? softfloat_round_min + : softfloat_round_max) + ) { + uiZ.v64 = (uiZ.v64 | (uiA0 != 0)) + roundBitsMask; + } + uiZ.v64 &= ~roundBitsMask; + lastBitMask0 = 0; + } + if ( (uiZ.v64 != uiA64) || (uiZ.v0 != uiA0) ) { +#ifdef SOFTFLOAT_ROUND_ODD + if ( roundingMode == softfloat_round_odd ) { + uiZ.v64 |= lastBitMask64; + uiZ.v0 |= lastBitMask0; + } +#endif + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + } + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f128_roundToInt.c ****/ +/**** start inlining ../../source/f128_add.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f128_add( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool signA; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + float128_t + (*magsFuncPtr)( + uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool ); +#endif + + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + signA = signF128UI64( uiA64 ); + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + signB = signF128UI64( uiB64 ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + return softfloat_addMagsF128( uiA64, uiA0, uiB64, uiB0, signA ); + } else { + return softfloat_subMagsF128( uiA64, uiA0, uiB64, uiB0, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_addMagsF128 : softfloat_subMagsF128; + return (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA ); +#endif + +} + +/**** ended inlining ../../source/f128_add.c ****/ +/**** start inlining ../../source/f128_sub.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f128_sub( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool signA; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + float128_t + (*magsFuncPtr)( + uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool ); +#endif + + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + signA = signF128UI64( uiA64 ); + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + signB = signF128UI64( uiB64 ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + return softfloat_subMagsF128( uiA64, uiA0, uiB64, uiB0, signA ); + } else { + return softfloat_addMagsF128( uiA64, uiA0, uiB64, uiB0, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_subMagsF128 : softfloat_addMagsF128; + return (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA ); +#endif + +} + +/**** ended inlining ../../source/f128_sub.c ****/ +/**** start inlining ../../source/f128_mul.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f128_mul( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool signA; + int_fast32_t expA; + struct uint128 sigA; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + bool signB; + int_fast32_t expB; + struct uint128 sigB; + bool signZ; + uint_fast64_t magBits; + struct exp32_sig128 normExpSig; + int_fast32_t expZ; + uint64_t sig256Z[4]; + uint_fast64_t sigZExtra; + struct uint128 sigZ; + struct uint128_extra sig128Extra; + struct uint128 uiZ; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + signA = signF128UI64( uiA64 ); + expA = expF128UI64( uiA64 ); + sigA.v64 = fracF128UI64( uiA64 ); + sigA.v0 = uiA0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + signB = signF128UI64( uiB64 ); + expB = expF128UI64( uiB64 ); + sigB.v64 = fracF128UI64( uiB64 ); + sigB.v0 = uiB0; + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( + (sigA.v64 | sigA.v0) || ((expB == 0x7FFF) && (sigB.v64 | sigB.v0)) + ) { + goto propagateNaN; + } + magBits = expB | sigB.v64 | sigB.v0; + goto infArg; + } + if ( expB == 0x7FFF ) { + if ( sigB.v64 | sigB.v0 ) goto propagateNaN; + magBits = expA | sigA.v64 | sigA.v0; + goto infArg; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! (sigA.v64 | sigA.v0) ) goto zero; + normExpSig = softfloat_normSubnormalF128Sig( sigA.v64, sigA.v0 ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! (sigB.v64 | sigB.v0) ) goto zero; + normExpSig = softfloat_normSubnormalF128Sig( sigB.v64, sigB.v0 ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x4000; + sigA.v64 |= UINT64_C( 0x0001000000000000 ); + sigB = softfloat_shortShiftLeft128( sigB.v64, sigB.v0, 16 ); + softfloat_mul128To256M( sigA.v64, sigA.v0, sigB.v64, sigB.v0, sig256Z ); + sigZExtra = sig256Z[indexWord( 4, 1 )] | (sig256Z[indexWord( 4, 0 )] != 0); + sigZ = + softfloat_add128( + sig256Z[indexWord( 4, 3 )], sig256Z[indexWord( 4, 2 )], + sigA.v64, sigA.v0 + ); + if ( UINT64_C( 0x0002000000000000 ) <= sigZ.v64 ) { + ++expZ; + sig128Extra = + softfloat_shortShiftRightJam128Extra( + sigZ.v64, sigZ.v0, sigZExtra, 1 ); + sigZ = sig128Extra.v; + sigZExtra = sig128Extra.extra; + } + return + softfloat_roundPackToF128( signZ, expZ, sigZ.v64, sigZ.v0, sigZExtra ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, uiB64, uiB0 ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infArg: + if ( ! magBits ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ.v64 = defaultNaNF128UI64; + uiZ.v0 = defaultNaNF128UI0; + goto uiZ; + } + uiZ.v64 = packToF128UI64( signZ, 0x7FFF, 0 ); + goto uiZ0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ.v64 = packToF128UI64( signZ, 0, 0 ); + uiZ0: + uiZ.v0 = 0; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f128_mul.c ****/ +/**** start inlining ../../source/f128_mulAdd.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f128_mulAdd( float128_t a, float128_t b, float128_t c ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + union ui128_f128 uC; + uint_fast64_t uiC64, uiC0; + + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + uC.f = c; + uiC64 = uC.ui.v64; + uiC0 = uC.ui.v0; + return softfloat_mulAddF128( uiA64, uiA0, uiB64, uiB0, uiC64, uiC0, 0 ); + +} + +/**** ended inlining ../../source/f128_mulAdd.c ****/ +/**** start inlining ../../source/f128_div.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f128_div( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool signA; + int_fast32_t expA; + struct uint128 sigA; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + bool signB; + int_fast32_t expB; + struct uint128 sigB; + bool signZ; + struct exp32_sig128 normExpSig; + int_fast32_t expZ; + struct uint128 rem; + uint_fast32_t recip32; + int ix; + uint_fast64_t q64; + uint_fast32_t q; + struct uint128 term; + uint_fast32_t qs[3]; + uint_fast64_t sigZExtra; + struct uint128 sigZ, uiZ; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + signA = signF128UI64( uiA64 ); + expA = expF128UI64( uiA64 ); + sigA.v64 = fracF128UI64( uiA64 ); + sigA.v0 = uiA0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + signB = signF128UI64( uiB64 ); + expB = expF128UI64( uiB64 ); + sigB.v64 = fracF128UI64( uiB64 ); + sigB.v0 = uiB0; + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( sigA.v64 | sigA.v0 ) goto propagateNaN; + if ( expB == 0x7FFF ) { + if ( sigB.v64 | sigB.v0 ) goto propagateNaN; + goto invalid; + } + goto infinity; + } + if ( expB == 0x7FFF ) { + if ( sigB.v64 | sigB.v0 ) goto propagateNaN; + goto zero; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) { + if ( ! (sigB.v64 | sigB.v0) ) { + if ( ! (expA | sigA.v64 | sigA.v0) ) goto invalid; + softfloat_raiseFlags( softfloat_flag_infinite ); + goto infinity; + } + normExpSig = softfloat_normSubnormalF128Sig( sigB.v64, sigB.v0 ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) { + if ( ! (sigA.v64 | sigA.v0) ) goto zero; + normExpSig = softfloat_normSubnormalF128Sig( sigA.v64, sigA.v0 ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA - expB + 0x3FFE; + sigA.v64 |= UINT64_C( 0x0001000000000000 ); + sigB.v64 |= UINT64_C( 0x0001000000000000 ); + rem = sigA; + if ( softfloat_lt128( sigA.v64, sigA.v0, sigB.v64, sigB.v0 ) ) { + --expZ; + rem = softfloat_add128( sigA.v64, sigA.v0, sigA.v64, sigA.v0 ); + } + recip32 = softfloat_approxRecip32_1( sigB.v64>>17 ); + ix = 3; + for (;;) { + q64 = (uint_fast64_t) (uint32_t) (rem.v64>>19) * recip32; + q = (q64 + 0x80000000)>>32; + --ix; + if ( ix < 0 ) break; + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 ); + term = softfloat_mul128By32( sigB.v64, sigB.v0, q ); + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + --q; + rem = softfloat_add128( rem.v64, rem.v0, sigB.v64, sigB.v0 ); + } + qs[ix] = q; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ((q + 1) & 7) < 2 ) { + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 ); + term = softfloat_mul128By32( sigB.v64, sigB.v0, q ); + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + --q; + rem = softfloat_add128( rem.v64, rem.v0, sigB.v64, sigB.v0 ); + } else if ( softfloat_le128( sigB.v64, sigB.v0, rem.v64, rem.v0 ) ) { + ++q; + rem = softfloat_sub128( rem.v64, rem.v0, sigB.v64, sigB.v0 ); + } + if ( rem.v64 | rem.v0 ) q |= 1; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sigZExtra = (uint64_t) ((uint_fast64_t) q<<60); + term = softfloat_shortShiftLeft128( 0, qs[1], 54 ); + sigZ = + softfloat_add128( + (uint_fast64_t) qs[2]<<19, ((uint_fast64_t) qs[0]<<25) + (q>>4), + term.v64, term.v0 + ); + return + softfloat_roundPackToF128( signZ, expZ, sigZ.v64, sigZ.v0, sigZExtra ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, uiB64, uiB0 ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ.v64 = defaultNaNF128UI64; + uiZ.v0 = defaultNaNF128UI0; + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infinity: + uiZ.v64 = packToF128UI64( signZ, 0x7FFF, 0 ); + goto uiZ0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ.v64 = packToF128UI64( signZ, 0, 0 ); + uiZ0: + uiZ.v0 = 0; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f128_div.c ****/ +/**** start inlining ../../source/f128_rem.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f128_rem( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool signA; + int_fast32_t expA; + struct uint128 sigA; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + int_fast32_t expB; + struct uint128 sigB; + struct exp32_sig128 normExpSig; + struct uint128 rem; + int_fast32_t expDiff; + uint_fast32_t q, recip32; + uint_fast64_t q64; + struct uint128 term, altRem, meanRem; + bool signRem; + struct uint128 uiZ; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + signA = signF128UI64( uiA64 ); + expA = expF128UI64( uiA64 ); + sigA.v64 = fracF128UI64( uiA64 ); + sigA.v0 = uiA0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + expB = expF128UI64( uiB64 ); + sigB.v64 = fracF128UI64( uiB64 ); + sigB.v0 = uiB0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( + (sigA.v64 | sigA.v0) || ((expB == 0x7FFF) && (sigB.v64 | sigB.v0)) + ) { + goto propagateNaN; + } + goto invalid; + } + if ( expB == 0x7FFF ) { + if ( sigB.v64 | sigB.v0 ) goto propagateNaN; + return a; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expB ) { + if ( ! (sigB.v64 | sigB.v0) ) goto invalid; + normExpSig = softfloat_normSubnormalF128Sig( sigB.v64, sigB.v0 ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) { + if ( ! (sigA.v64 | sigA.v0) ) return a; + normExpSig = softfloat_normSubnormalF128Sig( sigA.v64, sigA.v0 ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sigA.v64 |= UINT64_C( 0x0001000000000000 ); + sigB.v64 |= UINT64_C( 0x0001000000000000 ); + rem = sigA; + expDiff = expA - expB; + if ( expDiff < 1 ) { + if ( expDiff < -1 ) return a; + if ( expDiff ) { + --expB; + sigB = softfloat_add128( sigB.v64, sigB.v0, sigB.v64, sigB.v0 ); + q = 0; + } else { + q = softfloat_le128( sigB.v64, sigB.v0, rem.v64, rem.v0 ); + if ( q ) { + rem = softfloat_sub128( rem.v64, rem.v0, sigB.v64, sigB.v0 ); + } + } + } else { + recip32 = softfloat_approxRecip32_1( sigB.v64>>17 ); + expDiff -= 30; + for (;;) { + q64 = (uint_fast64_t) (uint32_t) (rem.v64>>19) * recip32; + if ( expDiff < 0 ) break; + q = (q64 + 0x80000000)>>32; + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 ); + term = softfloat_mul128By32( sigB.v64, sigB.v0, q ); + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + rem = softfloat_add128( rem.v64, rem.v0, sigB.v64, sigB.v0 ); + } + expDiff -= 29; + } + /*-------------------------------------------------------------------- + | (`expDiff' cannot be less than -29 here.) + *--------------------------------------------------------------------*/ + q = (uint32_t) (q64>>32)>>(~expDiff & 31); + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, expDiff + 30 ); + term = softfloat_mul128By32( sigB.v64, sigB.v0, q ); + rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 ); + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + altRem = softfloat_add128( rem.v64, rem.v0, sigB.v64, sigB.v0 ); + goto selectRem; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + do { + altRem = rem; + ++q; + rem = softfloat_sub128( rem.v64, rem.v0, sigB.v64, sigB.v0 ); + } while ( ! (rem.v64 & UINT64_C( 0x8000000000000000 )) ); + selectRem: + meanRem = softfloat_add128( rem.v64, rem.v0, altRem.v64, altRem.v0 ); + if ( + (meanRem.v64 & UINT64_C( 0x8000000000000000 )) + || (! (meanRem.v64 | meanRem.v0) && (q & 1)) + ) { + rem = altRem; + } + signRem = signA; + if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) { + signRem = ! signRem; + rem = softfloat_sub128( 0, 0, rem.v64, rem.v0 ); + } + return softfloat_normRoundPackToF128( signRem, expB - 1, rem.v64, rem.v0 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, uiB64, uiB0 ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ.v64 = defaultNaNF128UI64; + uiZ.v0 = defaultNaNF128UI0; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f128_rem.c ****/ +/**** start inlining ../../source/f128_sqrt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +float128_t f128_sqrt( float128_t a ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + bool signA; + int_fast32_t expA; + struct uint128 sigA, uiZ; + struct exp32_sig128 normExpSig; + int_fast32_t expZ; + uint_fast32_t sig32A, recipSqrt32, sig32Z; + struct uint128 rem; + uint32_t qs[3]; + uint_fast32_t q; + uint_fast64_t x64, sig64Z; + struct uint128 y, term; + uint_fast64_t sigZExtra; + struct uint128 sigZ; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + signA = signF128UI64( uiA64 ); + expA = expF128UI64( uiA64 ); + sigA.v64 = fracF128UI64( uiA64 ); + sigA.v0 = uiA0; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0x7FFF ) { + if ( sigA.v64 | sigA.v0 ) { + uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, 0, 0 ); + goto uiZ; + } + if ( ! signA ) return a; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( signA ) { + if ( ! (expA | sigA.v64 | sigA.v0) ) return a; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! (sigA.v64 | sigA.v0) ) return a; + normExpSig = softfloat_normSubnormalF128Sig( sigA.v64, sigA.v0 ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + /*------------------------------------------------------------------------ + | (`sig32Z' is guaranteed to be a lower bound on the square root of + | `sig32A', which makes `sig32Z' also a lower bound on the square root of + | `sigA'.) + *------------------------------------------------------------------------*/ + expZ = ((expA - 0x3FFF)>>1) + 0x3FFE; + expA &= 1; + sigA.v64 |= UINT64_C( 0x0001000000000000 ); + sig32A = sigA.v64>>17; + recipSqrt32 = softfloat_approxRecipSqrt32_1( expA, sig32A ); + sig32Z = ((uint_fast64_t) sig32A * recipSqrt32)>>32; + if ( expA ) { + sig32Z >>= 1; + rem = softfloat_shortShiftLeft128( sigA.v64, sigA.v0, 12 ); + } else { + rem = softfloat_shortShiftLeft128( sigA.v64, sigA.v0, 13 ); + } + qs[2] = sig32Z; + rem.v64 -= (uint_fast64_t) sig32Z * sig32Z; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = ((uint32_t) (rem.v64>>2) * (uint_fast64_t) recipSqrt32)>>32; + x64 = (uint_fast64_t) sig32Z<<32; + sig64Z = x64 + ((uint_fast64_t) q<<3); + y = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 ); + /*------------------------------------------------------------------------ + | (Repeating this loop is a rare occurrence.) + *------------------------------------------------------------------------*/ + for (;;) { + term = softfloat_mul64ByShifted32To128( x64 + sig64Z, q ); + rem = softfloat_sub128( y.v64, y.v0, term.v64, term.v0 ); + if ( ! (rem.v64 & UINT64_C( 0x8000000000000000 )) ) break; + --q; + sig64Z -= 1<<3; + } + qs[1] = q; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = ((rem.v64>>2) * recipSqrt32)>>32; + y = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 ); + sig64Z <<= 1; + /*------------------------------------------------------------------------ + | (Repeating this loop is a rare occurrence.) + *------------------------------------------------------------------------*/ + for (;;) { + term = softfloat_shortShiftLeft128( 0, sig64Z, 32 ); + term = softfloat_add128( term.v64, term.v0, 0, (uint_fast64_t) q<<6 ); + term = softfloat_mul128By32( term.v64, term.v0, q ); + rem = softfloat_sub128( y.v64, y.v0, term.v64, term.v0 ); + if ( ! (rem.v64 & UINT64_C( 0x8000000000000000 )) ) break; + --q; + } + qs[0] = q; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = (((rem.v64>>2) * recipSqrt32)>>32) + 2; + sigZExtra = (uint64_t) ((uint_fast64_t) q<<59); + term = softfloat_shortShiftLeft128( 0, qs[1], 53 ); + sigZ = + softfloat_add128( + (uint_fast64_t) qs[2]<<18, ((uint_fast64_t) qs[0]<<24) + (q>>5), + term.v64, term.v0 + ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (q & 0xF) <= 2 ) { + q &= ~3; + sigZExtra = (uint64_t) ((uint_fast64_t) q<<59); + y = softfloat_shortShiftLeft128( sigZ.v64, sigZ.v0, 6 ); + y.v0 |= sigZExtra>>58; + term = softfloat_sub128( y.v64, y.v0, 0, q ); + y = softfloat_mul64ByShifted32To128( term.v0, q ); + term = softfloat_mul64ByShifted32To128( term.v64, q ); + term = softfloat_add128( term.v64, term.v0, 0, y.v64 ); + rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 20 ); + term = softfloat_sub128( term.v64, term.v0, rem.v64, rem.v0 ); + /*-------------------------------------------------------------------- + | The concatenation of `term' and `y.v0' is now the negative remainder + | (3 words altogether). + *--------------------------------------------------------------------*/ + if ( term.v64 & UINT64_C( 0x8000000000000000 ) ) { + sigZExtra |= 1; + } else { + if ( term.v64 | term.v0 | y.v0 ) { + if ( sigZExtra ) { + --sigZExtra; + } else { + sigZ = softfloat_sub128( sigZ.v64, sigZ.v0, 0, 1 ); + sigZExtra = ~0; + } + } + } + } + return softfloat_roundPackToF128( 0, expZ, sigZ.v64, sigZ.v0, sigZExtra ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ.v64 = defaultNaNF128UI64; + uiZ.v0 = defaultNaNF128UI0; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +/**** ended inlining ../../source/f128_sqrt.c ****/ +/**** start inlining ../../source/f128_eq.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f128_eq( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNF128UI( uiA64, uiA0 ) + || softfloat_isSigNaNF128UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + return + (uiA0 == uiB0) + && ( (uiA64 == uiB64) + || (! uiA0 && ! ((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF ))) + ); + +} + +/**** ended inlining ../../source/f128_eq.c ****/ +/**** start inlining ../../source/f128_le.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f128_le( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + bool signA, signB; + + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signF128UI64( uiA64 ); + signB = signF128UI64( uiB64 ); + return + (signA != signB) + ? signA + || ! (((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + | uiA0 | uiB0) + : ((uiA64 == uiB64) && (uiA0 == uiB0)) + || (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 )); + +} + +/**** ended inlining ../../source/f128_le.c ****/ +/**** start inlining ../../source/f128_lt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f128_lt( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + bool signA, signB; + + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + signA = signF128UI64( uiA64 ); + signB = signF128UI64( uiB64 ); + return + (signA != signB) + ? signA + && (((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + | uiA0 | uiB0) + : ((uiA64 != uiB64) || (uiA0 != uiB0)) + && (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 )); + +} + +/**** ended inlining ../../source/f128_lt.c ****/ +/**** start inlining ../../source/f128_eq_signaling.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f128_eq_signaling( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + return + (uiA0 == uiB0) + && ( (uiA64 == uiB64) + || (! uiA0 && ! ((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF ))) + ); + +} + +/**** ended inlining ../../source/f128_eq_signaling.c ****/ +/**** start inlining ../../source/f128_le_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f128_le_quiet( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + bool signA, signB; + + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNF128UI( uiA64, uiA0 ) + || softfloat_isSigNaNF128UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signF128UI64( uiA64 ); + signB = signF128UI64( uiB64 ); + return + (signA != signB) + ? signA + || ! (((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + | uiA0 | uiB0) + : ((uiA64 == uiB64) && (uiA0 == uiB0)) + || (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 )); + +} + +/**** ended inlining ../../source/f128_le_quiet.c ****/ +/**** start inlining ../../source/f128_lt_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f128_lt_quiet( float128_t a, float128_t b ) +{ + union ui128_f128 uA; + uint_fast64_t uiA64, uiA0; + union ui128_f128 uB; + uint_fast64_t uiB64, uiB0; + bool signA, signB; + + uA.f = a; + uiA64 = uA.ui.v64; + uiA0 = uA.ui.v0; + uB.f = b; + uiB64 = uB.ui.v64; + uiB0 = uB.ui.v0; + if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNF128UI( uiA64, uiA0 ) + || softfloat_isSigNaNF128UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + signA = signF128UI64( uiA64 ); + signB = signF128UI64( uiB64 ); + return + (signA != signB) + ? signA + && (((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF )) + | uiA0 | uiB0) + : ((uiA64 != uiB64) || (uiA0 != uiB0)) + && (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 )); + +} + +/**** ended inlining ../../source/f128_lt_quiet.c ****/ +/**** start inlining ../../source/f128_isSignalingNaN.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +bool f128_isSignalingNaN( float128_t a ) +{ + union ui128_f128 uA; + + uA.f = a; + return softfloat_isSigNaNF128UI( uA.ui.v64, uA.ui.v0 ); + +} + +/**** ended inlining ../../source/f128_isSignalingNaN.c ****/ +/**** start inlining ../../source/f128M_to_ui32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +uint_fast32_t + f128M_to_ui32( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + + return f128_to_ui32( *aPtr, roundingMode, exact ); + +} + +#else + +uint_fast32_t + f128M_to_ui32( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint64_t sig64; + int32_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + sig64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )]; + if ( aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) sig64 |= 1; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (ui32_fromNaN != ui32_fromPosOverflow) || (ui32_fromNaN != ui32_fromNegOverflow) + if ( (exp == 0x7FFF) && sig64 ) { +#if (ui32_fromNaN == ui32_fromPosOverflow) + sign = 0; +#elif (ui32_fromNaN == ui32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return ui32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 ); + shiftDist = 0x4023 - exp; + if ( 0 < shiftDist ) sig64 = softfloat_shiftRightJam64( sig64, shiftDist ); + return softfloat_roundToUI32( sign, sig64, roundingMode, exact ); + +} + +#endif + +/**** ended inlining ../../source/f128M_to_ui32.c ****/ +/**** start inlining ../../source/f128M_to_ui64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +uint_fast64_t + f128M_to_ui64( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + + return f128_to_ui64( *aPtr, roundingMode, exact ); + +} + +#else + +uint_fast64_t + f128M_to_ui64( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint32_t sig96; + int32_t shiftDist; + uint32_t sig[4]; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + sig96 = fracF128UI96( uiA96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x404F - exp; + if ( shiftDist < 17 ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) + && (sig96 + || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )] + | aWPtr[indexWord( 4, 0 )])) + ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig96 |= 0x00010000; + sig[indexWord( 4, 3 )] = sig96; + sig[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )]; + sig[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )]; + sig[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )]; + softfloat_shiftRightJam128M( sig, shiftDist, sig ); + return + softfloat_roundMToUI64( + sign, sig + indexMultiwordLo( 4, 3 ), roundingMode, exact ); + +} + +#endif + +/**** ended inlining ../../source/f128M_to_ui64.c ****/ +/**** start inlining ../../source/f128M_to_i32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +int_fast32_t + f128M_to_i32( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + + return f128_to_i32( *aPtr, roundingMode, exact ); + +} + +#else + +int_fast32_t + f128M_to_i32( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint64_t sig64; + int32_t shiftDist; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + sig64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )]; + if ( aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) sig64 |= 1; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ +#if (i32_fromNaN != i32_fromPosOverflow) || (i32_fromNaN != i32_fromNegOverflow) + if ( (exp == 0x7FFF) && sig64 ) { +#if (i32_fromNaN == i32_fromPosOverflow) + sign = 0; +#elif (i32_fromNaN == i32_fromNegOverflow) + sign = 1; +#else + softfloat_raiseFlags( softfloat_flag_invalid ); + return i32_fromNaN; +#endif + } +#endif + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 ); + shiftDist = 0x4023 - exp; + if ( 0 < shiftDist ) sig64 = softfloat_shiftRightJam64( sig64, shiftDist ); + return softfloat_roundToI32( sign, sig64, roundingMode, exact ); + +} + +#endif + +/**** ended inlining ../../source/f128M_to_i32.c ****/ +/**** start inlining ../../source/f128M_to_i64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +int_fast64_t + f128M_to_i64( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + + return f128_to_i64( *aPtr, roundingMode, exact ); + +} + +#else + +int_fast64_t + f128M_to_i64( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint32_t sig96; + int32_t shiftDist; + uint32_t sig[4]; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + sig96 = fracF128UI96( uiA96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x404F - exp; + if ( shiftDist < 17 ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) + && (sig96 + || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )] + | aWPtr[indexWord( 4, 0 )])) + ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp ) sig96 |= 0x00010000; + sig[indexWord( 4, 3 )] = sig96; + sig[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )]; + sig[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )]; + sig[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )]; + softfloat_shiftRightJam128M( sig, shiftDist, sig ); + return + softfloat_roundMToI64( + sign, sig + indexMultiwordLo( 4, 3 ), roundingMode, exact ); + +} + +#endif + +/**** ended inlining ../../source/f128M_to_i64.c ****/ +/**** start inlining ../../source/f128M_to_ui32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +uint_fast32_t f128M_to_ui32_r_minMag( const float128_t *aPtr, bool exact ) +{ + + return f128_to_ui32_r_minMag( *aPtr, exact ); + +} + +#else + +uint_fast32_t f128M_to_ui32_r_minMag( const float128_t *aPtr, bool exact ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + int32_t exp; + uint64_t sig64; + int32_t shiftDist; + bool sign; + uint32_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + exp = expF128UI96( uiA96 ); + sig64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )]; + if ( aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) sig64 |= 1; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x402F - exp; + if ( 49 <= shiftDist ) { + if ( exact && (exp | sig64) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sign = signF128UI96( uiA96 ); + if ( sign || (shiftDist < 17) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) && sig64 ? ui32_fromNaN + : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + sig64 |= UINT64_C( 0x0001000000000000 ); + z = sig64>>shiftDist; + if ( exact && ((uint64_t) z< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +uint_fast64_t f128M_to_ui64_r_minMag( const float128_t *aPtr, bool exact ) +{ + + return f128_to_ui64_r_minMag( *aPtr, exact ); + +} + +#else + +uint_fast64_t f128M_to_ui64_r_minMag( const float128_t *aPtr, bool exact ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint32_t sig96; + int32_t shiftDist; + uint32_t sig[4]; + uint64_t z; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + sig96 = fracF128UI96( uiA96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( shiftDist < 0 ) goto invalid; + if ( exact ) { + if ( exp ) sig96 |= 0x00010000; + sig[indexWord( 4, 3 )] = sig96; + sig[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )]; + sig[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )]; + sig[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )]; + softfloat_shiftRightJam128M( sig, shiftDist + 17, sig ); + z = (uint64_t) sig[indexWord( 4, 2 )]<<32 | sig[indexWord( 4, 1 )]; + if ( sign && z ) goto invalid; + if ( sig[indexWordLo( 4 )] ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + } else { + if ( 64 <= shiftDist ) return 0; + if ( sign ) goto invalid; + z = UINT64_C( 0x8000000000000000 ) + | (uint64_t) sig96<<47 + | (uint64_t) aWPtr[indexWord( 4, 2 )]<<15 + | aWPtr[indexWord( 4, 1 )]>>17; + z >>= shiftDist; + } + return z; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) + && (sig96 + || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )] + | aWPtr[indexWord( 4, 0 )])) + ? ui64_fromNaN + : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow; + +} + +#endif + +/**** ended inlining ../../source/f128M_to_ui64_r_minMag.c ****/ +/**** start inlining ../../source/f128M_to_i32_r_minMag.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +int_fast32_t f128M_to_i32_r_minMag( const float128_t *aPtr, bool exact ) +{ + + return f128_to_i32_r_minMag( *aPtr, exact ); + +} + +#else + +int_fast32_t f128M_to_i32_r_minMag( const float128_t *aPtr, bool exact ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint64_t sig64; + int32_t shiftDist; + uint32_t absZ, uiZ; + union { uint32_t ui; int32_t i; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + sig64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )]; + if ( aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) sig64 |= 1; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp < 0x3FFF ) { + if ( exact && (exp | sig64) ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + return 0; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x401F <= exp ) goto invalid; + shiftDist = 0x402F - exp; + sig64 |= UINT64_C( 0x0001000000000000 ); + absZ = sig64>>shiftDist; + uiZ = sign ? -absZ : absZ; + if ( uiZ>>31 != sign ) goto invalid; + if ( exact && ((uint64_t) absZ< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +int_fast64_t f128M_to_i64_r_minMag( const float128_t *aPtr, bool exact ) +{ + + return f128_to_i64_r_minMag( *aPtr, exact ); + +} + +#else + +int_fast64_t f128M_to_i64_r_minMag( const float128_t *aPtr, bool exact ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint32_t sig96; + int32_t shiftDist; + uint32_t sig[4]; + uint64_t uiZ; + union { uint64_t ui; int64_t i; } uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + sig96 = fracF128UI96( uiA96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + shiftDist = 0x403E - exp; + if ( shiftDist < 0 ) goto invalid; + if ( exact ) { + if ( exp ) sig96 |= 0x00010000; + sig[indexWord( 4, 3 )] = sig96; + sig[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )]; + sig[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )]; + sig[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )]; + softfloat_shiftRightJam128M( sig, shiftDist + 17, sig ); + uiZ = (uint64_t) sig[indexWord( 4, 2 )]<<32 | sig[indexWord( 4, 1 )]; + if ( uiZ>>63 && (! sign || (uiZ != UINT64_C( 0x8000000000000000 ))) ) { + goto invalid; + } + if ( sig[indexWordLo( 4 )] ) { + softfloat_exceptionFlags |= softfloat_flag_inexact; + } + } else { + if ( 64 <= shiftDist ) return 0; + uiZ = + (uint64_t) sig96<<47 + | (uint64_t) aWPtr[indexWord( 4, 2 )]<<15 + | aWPtr[indexWord( 4, 1 )]>>17; + if ( shiftDist ) { + uiZ |= UINT64_C( 0x8000000000000000 ); + uiZ >>= shiftDist; + } else { + if ( uiZ || ! sign ) goto invalid; + uiZ |= UINT64_C( 0x8000000000000000 ); + } + } + if ( sign ) uiZ = -uiZ; + uZ.ui = uiZ; + return uZ.i; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + return + (exp == 0x7FFF) + && (sig96 + || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )] + | aWPtr[indexWord( 4, 0 )])) + ? i64_fromNaN + : sign ? i64_fromNegOverflow : i64_fromPosOverflow; + +} + +#endif + +/**** ended inlining ../../source/f128M_to_i64_r_minMag.c ****/ +/**** start inlining ../../source/f128M_to_f16.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +float16_t f128M_to_f16( const float128_t *aPtr ) +{ + + return f128_to_f16( *aPtr ); + +} + +#else + +float16_t f128M_to_f16( const float128_t *aPtr ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint32_t frac32; + struct commonNaN commonNaN; + uint16_t uiZ, frac16; + union ui16_f16 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + frac32 = + fracF128UI96( uiA96 ) + | ((aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )] + | aWPtr[indexWord( 4, 0 )]) + != 0); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( frac32 ) { + softfloat_f128MToCommonNaN( aWPtr, &commonNaN ); + uiZ = softfloat_commonNaNToF16UI( &commonNaN ); + } else { + uiZ = packToF16UI( sign, 0x1F, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac16 = frac32>>2 | (frac32 & 3); + if ( ! (exp | frac16) ) { + uiZ = packToF16UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp -= 0x3FF1; + if ( sizeof (int_fast16_t) < sizeof (int32_t) ) { + if ( exp < -0x40 ) exp = -0x40; + } + return softfloat_roundPackToF16( sign, exp, frac16 | 0x4000 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +#endif + +/**** ended inlining ../../source/f128M_to_f16.c ****/ +/**** start inlining ../../source/f128M_to_f32.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +float32_t f128M_to_f32( const float128_t *aPtr ) +{ + + return f128_to_f32( *aPtr ); + +} + +#else + +float32_t f128M_to_f32( const float128_t *aPtr ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint64_t frac64; + struct commonNaN commonNaN; + uint32_t uiZ, frac32; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + frac64 = + (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )] + | ((aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )]) != 0); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( frac64 ) { + softfloat_f128MToCommonNaN( aWPtr, &commonNaN ); + uiZ = softfloat_commonNaNToF32UI( &commonNaN ); + } else { + uiZ = packToF32UI( sign, 0xFF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac32 = softfloat_shortShiftRightJam64( frac64, 18 ); + if ( ! (exp | frac32) ) { + uiZ = packToF32UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp -= 0x3F81; + if ( sizeof (int_fast16_t) < sizeof (int32_t) ) { + if ( exp < -0x1000 ) exp = -0x1000; + } + return softfloat_roundPackToF32( sign, exp, frac32 | 0x40000000 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +#endif + +/**** ended inlining ../../source/f128M_to_f32.c ****/ +/**** start inlining ../../source/f128M_to_extF80M.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void f128M_to_extF80M( const float128_t *aPtr, extFloat80_t *zPtr ) +{ + + *zPtr = f128_to_extF80( *aPtr ); + +} + +#else + +void f128M_to_extF80M( const float128_t *aPtr, extFloat80_t *zPtr ) +{ + const uint32_t *aWPtr; + struct extFloat80M *zSPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + struct commonNaN commonNaN; + uint32_t sig[4]; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + zSPtr = (struct extFloat80M *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( softfloat_isNaNF128M( aWPtr ) ) { + softfloat_f128MToCommonNaN( aWPtr, &commonNaN ); + softfloat_commonNaNToExtF80M( &commonNaN, zSPtr ); + return; + } + zSPtr->signExp = packToExtF80UI64( sign, 0x7FFF ); + zSPtr->signif = UINT64_C( 0x8000000000000000 ); + return; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp = softfloat_shiftNormSigF128M( aWPtr, 15, sig ); + if ( exp == -128 ) { + zSPtr->signExp = packToExtF80UI64( sign, 0 ); + zSPtr->signif = 0; + return; + } + if ( sig[indexWord( 4, 0 )] ) sig[indexWord( 4, 1 )] |= 1; + softfloat_roundPackMToExtF80M( + sign, exp, &sig[indexMultiwordHi( 4, 3 )], 80, zSPtr ); + +} + +#endif + +/**** ended inlining ../../source/f128M_to_extF80M.c ****/ +/**** start inlining ../../source/f128M_to_f64.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +float64_t f128M_to_f64( const float128_t *aPtr ) +{ + + return f128_to_f64( *aPtr ); + +} + +#else + +float64_t f128M_to_f64( const float128_t *aPtr ) +{ + const uint32_t *aWPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + uint64_t frac64; + struct commonNaN commonNaN; + uint64_t uiZ; + uint32_t frac32; + union ui64_f64 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + frac64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )]; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( frac64 || aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) { + softfloat_f128MToCommonNaN( aWPtr, &commonNaN ); + uiZ = softfloat_commonNaNToF64UI( &commonNaN ); + } else { + uiZ = packToF64UI( sign, 0x7FF, 0 ); + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + frac32 = aWPtr[indexWord( 4, 1 )]; + frac64 = frac64<<14 | frac32>>18; + if ( (frac32 & 0x0003FFFF) || aWPtr[indexWord( 4, 0 )] ) frac64 |= 1; + if ( ! (exp | frac64) ) { + uiZ = packToF64UI( sign, 0, 0 ); + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp -= 0x3C01; + if ( sizeof (int_fast16_t) < sizeof (int32_t) ) { + if ( exp < -0x1000 ) exp = -0x1000; + } + return + softfloat_roundPackToF64( + sign, exp, frac64 | UINT64_C( 0x4000000000000000 ) ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + +#endif + +/**** ended inlining ../../source/f128M_to_f64.c ****/ +/**** start inlining ../../source/f128M_roundToInt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + f128M_roundToInt( + const float128_t *aPtr, + uint_fast8_t roundingMode, + bool exact, + float128_t *zPtr + ) +{ + + *zPtr = f128_roundToInt( *aPtr, roundingMode, exact ); + +} + +#else + +void + f128M_roundToInt( + const float128_t *aPtr, + uint_fast8_t roundingMode, + bool exact, + float128_t *zPtr + ) +{ + const uint32_t *aWPtr; + uint32_t *zWPtr; + uint32_t ui96; + int32_t exp; + uint32_t sigExtra; + bool sign; + uint_fast8_t bitPos; + bool roundNear; + unsigned int index, lastIndex; + bool extra; + uint32_t wordA, bit, wordZ; + uint_fast8_t carry; + uint32_t extrasMask; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + zWPtr = (uint32_t *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + ui96 = aWPtr[indexWordHi( 4 )]; + exp = expF128UI96( ui96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp < 0x3FFF ) { + zWPtr[indexWord( 4, 2 )] = 0; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + sigExtra = aWPtr[indexWord( 4, 2 )]; + if ( !sigExtra ) { + sigExtra = aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )]; + } + if ( !sigExtra && !(ui96 & 0x7FFFFFFF) ) goto ui96; + if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact; + sign = signF128UI96( ui96 ); + switch ( roundingMode ) { + case softfloat_round_near_even: + if ( !fracF128UI96( ui96 ) && !sigExtra ) break; + case softfloat_round_near_maxMag: + if ( exp == 0x3FFE ) goto mag1; + break; + case softfloat_round_min: + if ( sign ) goto mag1; + break; + case softfloat_round_max: + if ( !sign ) goto mag1; + break; +#ifdef SOFTFLOAT_ROUND_ODD + case softfloat_round_odd: + goto mag1; +#endif + } + ui96 = packToF128UI96( sign, 0, 0 ); + goto ui96; + mag1: + ui96 = packToF128UI96( sign, 0x3FFF, 0 ); + goto ui96; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( 0x406F <= exp ) { + if ( + (exp == 0x7FFF) + && (fracF128UI96( ui96 ) + || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )] + | aWPtr[indexWord( 4, 0 )])) + ) { + softfloat_propagateNaNF128M( aWPtr, 0, zWPtr ); + return; + } + zWPtr[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )]; + zWPtr[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )]; + zWPtr[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )]; + goto ui96; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + bitPos = 0x406F - exp; + roundNear = + (roundingMode == softfloat_round_near_maxMag) + || (roundingMode == softfloat_round_near_even); + bitPos -= roundNear; + index = indexWordLo( 4 ); + lastIndex = indexWordHi( 4 ); + extra = 0; + for (;;) { + wordA = aWPtr[index]; + if ( bitPos < 32 ) break; + if ( wordA ) extra = 1; + zWPtr[index] = 0; + index += wordIncr; + bitPos -= 32; + } + bit = (uint32_t) 1< +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + f128M_add( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + const uint64_t *aWPtr, *bWPtr; + uint_fast64_t uiA64, uiA0; + bool signA; + uint_fast64_t uiB64, uiB0; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + float128_t + (*magsFuncPtr)( + uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool ); +#endif + + aWPtr = (const uint64_t *) aPtr; + bWPtr = (const uint64_t *) bPtr; + uiA64 = aWPtr[indexWord( 2, 1 )]; + uiA0 = aWPtr[indexWord( 2, 0 )]; + signA = signF128UI64( uiA64 ); + uiB64 = bWPtr[indexWord( 2, 1 )]; + uiB0 = bWPtr[indexWord( 2, 0 )]; + signB = signF128UI64( uiB64 ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + *zPtr = softfloat_addMagsF128( uiA64, uiA0, uiB64, uiB0, signA ); + } else { + *zPtr = softfloat_subMagsF128( uiA64, uiA0, uiB64, uiB0, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_addMagsF128 : softfloat_subMagsF128; + *zPtr = (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA ); +#endif + +} + +#else + +void + f128M_add( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + + softfloat_addF128M( + (const uint32_t *) aPtr, + (const uint32_t *) bPtr, + (uint32_t *) zPtr, + false + ); + +} + +#endif + +/**** ended inlining ../../source/f128M_add.c ****/ +/**** start inlining ../../source/f128M_sub.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + f128M_sub( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + const uint64_t *aWPtr, *bWPtr; + uint_fast64_t uiA64, uiA0; + bool signA; + uint_fast64_t uiB64, uiB0; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + float128_t + (*magsFuncPtr)( + uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool ); +#endif + + aWPtr = (const uint64_t *) aPtr; + bWPtr = (const uint64_t *) bPtr; + uiA64 = aWPtr[indexWord( 2, 1 )]; + uiA0 = aWPtr[indexWord( 2, 0 )]; + signA = signF128UI64( uiA64 ); + uiB64 = bWPtr[indexWord( 2, 1 )]; + uiB0 = bWPtr[indexWord( 2, 0 )]; + signB = signF128UI64( uiB64 ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + *zPtr = softfloat_subMagsF128( uiA64, uiA0, uiB64, uiB0, signA ); + } else { + *zPtr = softfloat_addMagsF128( uiA64, uiA0, uiB64, uiB0, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_subMagsF128 : softfloat_addMagsF128; + *zPtr = (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA ); +#endif + +} + +#else + +void + f128M_sub( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + + softfloat_addF128M( + (const uint32_t *) aPtr, + (const uint32_t *) bPtr, + (uint32_t *) zPtr, + true + ); + +} + +#endif + +/**** ended inlining ../../source/f128M_sub.c ****/ +/**** start inlining ../../source/f128M_mul.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + f128M_mul( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + + *zPtr = f128_mul( *aPtr, *bPtr ); + +} + +#else + +void + f128M_mul( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + const uint32_t *aWPtr, *bWPtr; + uint32_t *zWPtr; + uint32_t uiA96; + int32_t expA; + uint32_t uiB96; + int32_t expB; + bool signZ; + const uint32_t *ptr; + uint32_t uiZ96, sigA[4]; + uint_fast8_t shiftDist; + uint32_t sigB[4]; + int32_t expZ; + uint32_t sigProd[8], *extSigZPtr; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + bWPtr = (const uint32_t *) bPtr; + zWPtr = (uint32_t *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA96 = aWPtr[indexWordHi( 4 )]; + expA = expF128UI96( uiA96 ); + uiB96 = bWPtr[indexWordHi( 4 )]; + expB = expF128UI96( uiB96 ); + signZ = signF128UI96( uiA96 ) ^ signF128UI96( uiB96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) { + if ( softfloat_tryPropagateNaNF128M( aWPtr, bWPtr, zWPtr ) ) return; + ptr = aWPtr; + if ( ! expA ) goto possiblyInvalid; + if ( ! expB ) { + ptr = bWPtr; + possiblyInvalid: + if ( + ! fracF128UI96( ptr[indexWordHi( 4 )] ) + && ! (ptr[indexWord( 4, 2 )] | ptr[indexWord( 4, 1 )] + | ptr[indexWord( 4, 0 )]) + ) { + softfloat_invalidF128M( zWPtr ); + return; + } + } + uiZ96 = packToF128UI96( signZ, 0x7FFF, 0 ); + goto uiZ96; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA ) { + sigA[indexWordHi( 4 )] = fracF128UI96( uiA96 ) | 0x00010000; + sigA[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )]; + sigA[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )]; + sigA[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )]; + } else { + expA = softfloat_shiftNormSigF128M( aWPtr, 0, sigA ); + if ( expA == -128 ) goto zero; + } + if ( expB ) { + sigB[indexWordHi( 4 )] = fracF128UI96( uiB96 ) | 0x00010000; + sigB[indexWord( 4, 2 )] = bWPtr[indexWord( 4, 2 )]; + sigB[indexWord( 4, 1 )] = bWPtr[indexWord( 4, 1 )]; + sigB[indexWord( 4, 0 )] = bWPtr[indexWord( 4, 0 )]; + } else { + expB = softfloat_shiftNormSigF128M( bWPtr, 0, sigB ); + if ( expB == -128 ) goto zero; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x4000; + softfloat_mul128MTo256M( sigA, sigB, sigProd ); + if ( + sigProd[indexWord( 8, 2 )] + || (sigProd[indexWord( 8, 1 )] | sigProd[indexWord( 8, 0 )]) + ) { + sigProd[indexWord( 8, 3 )] |= 1; + } + extSigZPtr = &sigProd[indexMultiwordHi( 8, 5 )]; + shiftDist = 16; + if ( extSigZPtr[indexWordHi( 5 )] & 2 ) { + ++expZ; + shiftDist = 15; + } + softfloat_shortShiftLeft160M( extSigZPtr, shiftDist, extSigZPtr ); + softfloat_roundPackMToF128M( signZ, expZ, extSigZPtr, zWPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ96 = packToF128UI96( signZ, 0, 0 ); + uiZ96: + zWPtr[indexWordHi( 4 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = 0; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + +} + +#endif + +/**** ended inlining ../../source/f128M_mul.c ****/ +/**** start inlining ../../source/f128M_mulAdd.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + f128M_mulAdd( + const float128_t *aPtr, + const float128_t *bPtr, + const float128_t *cPtr, + float128_t *zPtr + ) +{ + const uint64_t *aWPtr, *bWPtr, *cWPtr; + uint_fast64_t uiA64, uiA0; + uint_fast64_t uiB64, uiB0; + uint_fast64_t uiC64, uiC0; + + aWPtr = (const uint64_t *) aPtr; + bWPtr = (const uint64_t *) bPtr; + cWPtr = (const uint64_t *) cPtr; + uiA64 = aWPtr[indexWord( 2, 1 )]; + uiA0 = aWPtr[indexWord( 2, 0 )]; + uiB64 = bWPtr[indexWord( 2, 1 )]; + uiB0 = bWPtr[indexWord( 2, 0 )]; + uiC64 = cWPtr[indexWord( 2, 1 )]; + uiC0 = cWPtr[indexWord( 2, 0 )]; + *zPtr = softfloat_mulAddF128( uiA64, uiA0, uiB64, uiB0, uiC64, uiC0, 0 ); + +} + +#else + +void + f128M_mulAdd( + const float128_t *aPtr, + const float128_t *bPtr, + const float128_t *cPtr, + float128_t *zPtr + ) +{ + + softfloat_mulAddF128M( + (const uint32_t *) aPtr, + (const uint32_t *) bPtr, + (const uint32_t *) cPtr, + (uint32_t *) zPtr, + 0 + ); + +} + +#endif + +/**** ended inlining ../../source/f128M_mulAdd.c ****/ +/**** start inlining ../../source/f128M_div.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + f128M_div( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + + *zPtr = f128_div( *aPtr, *bPtr ); + +} + +#else + +void + f128M_div( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + const uint32_t *aWPtr, *bWPtr; + uint32_t *zWPtr, uiA96; + bool signA; + int32_t expA; + uint32_t uiB96; + bool signB; + int32_t expB; + bool signZ; + uint32_t y[5], sigB[4]; + int32_t expZ; + uint32_t recip32; + int ix; + uint64_t q64; + uint32_t q, qs[3], uiZ96; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + bWPtr = (const uint32_t *) bPtr; + zWPtr = (uint32_t *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA96 = aWPtr[indexWordHi( 4 )]; + signA = signF128UI96( uiA96 ); + expA = expF128UI96( uiA96 ); + uiB96 = bWPtr[indexWordHi( 4 )]; + signB = signF128UI96( uiB96 ); + expB = expF128UI96( uiB96 ); + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) { + if ( softfloat_tryPropagateNaNF128M( aWPtr, bWPtr, zWPtr ) ) return; + if ( expA == 0x7FFF ) { + if ( expB == 0x7FFF ) goto invalid; + goto infinity; + } + goto zero; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = softfloat_shiftNormSigF128M( aWPtr, 13, y ); + expB = softfloat_shiftNormSigF128M( bWPtr, 13, sigB ); + if ( expA == -128 ) { + if ( expB == -128 ) goto invalid; + goto zero; + } + if ( expB == -128 ) { + softfloat_raiseFlags( softfloat_flag_infinite ); + goto infinity; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA - expB + 0x3FFE; + if ( softfloat_compare128M( y, sigB ) < 0 ) { + --expZ; + softfloat_add128M( y, y, y ); + } + recip32 = + softfloat_approxRecip32_1( + ((uint64_t) sigB[indexWord( 4, 3 )]<<32 | sigB[indexWord( 4, 2 )]) + >>30 + ); + ix = 3; + for (;;) { + q64 = (uint64_t) y[indexWordHi( 4 )] * recip32; + q = (q64 + 0x80000000)>>32; + --ix; + if ( ix < 0 ) break; + softfloat_remStep128MBy32( y, 29, sigB, q, y ); + if ( y[indexWordHi( 4 )] & 0x80000000 ) { + --q; + softfloat_add128M( y, sigB, y ); + } + qs[ix] = q; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ((q + 1) & 7) < 2 ) { + softfloat_remStep128MBy32( y, 29, sigB, q, y ); + if ( y[indexWordHi( 4 )] & 0x80000000 ) { + --q; + softfloat_add128M( y, sigB, y ); + } else if ( softfloat_compare128M( sigB, y ) <= 0 ) { + ++q; + softfloat_sub128M( y, sigB, y ); + } + if ( + y[indexWordLo( 4 )] || y[indexWord( 4, 1 )] + || (y[indexWord( 4, 2 )] | y[indexWord( 4, 3 )]) + ) { + q |= 1; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q64 = (uint64_t) q<<28; + y[indexWord( 5, 0 )] = q64; + q64 = ((uint64_t) qs[0]<<25) + (q64>>32); + y[indexWord( 5, 1 )] = q64; + q64 = ((uint64_t) qs[1]<<22) + (q64>>32); + y[indexWord( 5, 2 )] = q64; + q64 = ((uint64_t) qs[2]<<19) + (q64>>32); + y[indexWord( 5, 3 )] = q64; + y[indexWord( 5, 4 )] = q64>>32; + softfloat_roundPackMToF128M( signZ, expZ, y, zWPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_invalidF128M( zWPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infinity: + uiZ96 = packToF128UI96( signZ, 0x7FFF, 0 ); + goto uiZ96; + zero: + uiZ96 = packToF128UI96( signZ, 0, 0 ); + uiZ96: + zWPtr[indexWordHi( 4 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = 0; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + +} + +#endif + +/**** ended inlining ../../source/f128M_div.c ****/ +/**** start inlining ../../source/f128M_rem.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void + f128M_rem( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + + *zPtr = f128_rem( *aPtr, *bPtr ); + +} + +#else + +void + f128M_rem( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr ) +{ + const uint32_t *aWPtr, *bWPtr; + uint32_t *zWPtr, uiA96; + int32_t expA, expB; + uint32_t x[4], rem1[5], *remPtr; + bool signRem; + int32_t expDiff; + uint32_t q, recip32; + uint64_t q64; + uint32_t rem2[5], *altRemPtr, *newRemPtr, wordMeanRem; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + bWPtr = (const uint32_t *) bPtr; + zWPtr = (uint32_t *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA96 = aWPtr[indexWordHi( 4 )]; + expA = expF128UI96( uiA96 ); + expB = expF128UI96( bWPtr[indexWordHi( 4 )] ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) { + if ( softfloat_tryPropagateNaNF128M( aWPtr, bWPtr, zWPtr ) ) return; + if ( expA == 0x7FFF ) goto invalid; + goto copyA; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA < expB - 1 ) goto copyA; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expB = softfloat_shiftNormSigF128M( bWPtr, 13, x ); + if ( expB == -128 ) goto invalid; + remPtr = &rem1[indexMultiwordLo( 5, 4 )]; + expA = softfloat_shiftNormSigF128M( aWPtr, 13, remPtr ); + if ( expA == -128 ) goto copyA; + signRem = signF128UI96( uiA96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expDiff = expA - expB; + if ( expDiff < 1 ) { + if ( expDiff < -1 ) goto copyA; + if ( expDiff ) { + --expB; + softfloat_add128M( x, x, x ); + q = 0; + } else { + q = (softfloat_compare128M( x, remPtr ) <= 0); + if ( q ) softfloat_sub128M( remPtr, x, remPtr ); + } + } else { + recip32 = + softfloat_approxRecip32_1( + ((uint64_t) x[indexWord( 4, 3 )]<<32 | x[indexWord( 4, 2 )]) + >>30 + ); + expDiff -= 30; + for (;;) { + q64 = (uint64_t) remPtr[indexWordHi( 4 )] * recip32; + if ( expDiff < 0 ) break; + q = (q64 + 0x80000000)>>32; + softfloat_remStep128MBy32( remPtr, 29, x, q, remPtr ); + if ( remPtr[indexWordHi( 4 )] & 0x80000000 ) { + softfloat_add128M( remPtr, x, remPtr ); + } + expDiff -= 29; + } + /*-------------------------------------------------------------------- + | (`expDiff' cannot be less than -29 here.) + *--------------------------------------------------------------------*/ + q = (uint32_t) (q64>>32)>>(~expDiff & 31); + softfloat_remStep128MBy32( remPtr, expDiff + 30, x, q, remPtr ); + if ( remPtr[indexWordHi( 4 )] & 0x80000000 ) { + altRemPtr = &rem2[indexMultiwordLo( 5, 4 )]; + softfloat_add128M( remPtr, x, altRemPtr ); + goto selectRem; + } + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + altRemPtr = &rem2[indexMultiwordLo( 5, 4 )]; + do { + ++q; + newRemPtr = altRemPtr; + softfloat_sub128M( remPtr, x, newRemPtr ); + altRemPtr = remPtr; + remPtr = newRemPtr; + } while ( ! (remPtr[indexWordHi( 4 )] & 0x80000000) ); + selectRem: + softfloat_add128M( remPtr, altRemPtr, x ); + wordMeanRem = x[indexWordHi( 4 )]; + if ( + (wordMeanRem & 0x80000000) + || (! wordMeanRem && (q & 1) && ! x[indexWord( 4, 0 )] + && ! (x[indexWord( 4, 2 )] | x[indexWord( 4, 1 )])) + ) { + remPtr = altRemPtr; + } + if ( remPtr[indexWordHi( 4 )] & 0x80000000 ) { + signRem = ! signRem; + softfloat_negX128M( remPtr ); + } + remPtr -= indexMultiwordLo( 5, 4 ); + remPtr[indexWordHi( 5 )] = 0; + softfloat_normRoundPackMToF128M( signRem, expB + 18, remPtr, zWPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_invalidF128M( zWPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + copyA: + zWPtr[indexWordHi( 4 )] = uiA96; + zWPtr[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )]; + zWPtr[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )]; + zWPtr[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )]; + +} + +#endif + +/**** ended inlining ../../source/f128M_rem.c ****/ +/**** start inlining ../../source/f128M_sqrt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of +California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +void f128M_sqrt( const float128_t *aPtr, float128_t *zPtr ) +{ + + *zPtr = f128_sqrt( *aPtr ); + +} + +#else + +void f128M_sqrt( const float128_t *aPtr, float128_t *zPtr ) +{ + const uint32_t *aWPtr; + uint32_t *zWPtr; + uint32_t uiA96; + bool signA; + int32_t rawExpA; + uint32_t rem[6]; + int32_t expA, expZ; + uint64_t rem64; + uint32_t sig32A, recipSqrt32, sig32Z, qs[3], q; + uint64_t sig64Z; + uint32_t term[5]; + uint64_t x64; + uint32_t y[5], rem32; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + zWPtr = (uint32_t *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA96 = aWPtr[indexWordHi( 4 )]; + signA = signF128UI96( uiA96 ); + rawExpA = expF128UI96( uiA96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( rawExpA == 0x7FFF ) { + if ( + fracF128UI96( uiA96 ) + || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )] + | aWPtr[indexWord( 4, 0 )]) + ) { + softfloat_propagateNaNF128M( aWPtr, 0, zWPtr ); + return; + } + if ( ! signA ) goto copyA; + goto invalid; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expA = softfloat_shiftNormSigF128M( aWPtr, 13 - (rawExpA & 1), rem ); + if ( expA == -128 ) goto copyA; + if ( signA ) goto invalid; + /*------------------------------------------------------------------------ + | (`sig32Z' is guaranteed to be a lower bound on the square root of + | `sig32A', which makes `sig32Z' also a lower bound on the square root of + | `sigA'.) + *------------------------------------------------------------------------*/ + expZ = ((expA - 0x3FFF)>>1) + 0x3FFE; + expA &= 1; + rem64 = (uint64_t) rem[indexWord( 4, 3 )]<<32 | rem[indexWord( 4, 2 )]; + if ( expA ) { + if ( ! rawExpA ) { + softfloat_shortShiftRight128M( rem, 1, rem ); + rem64 >>= 1; + } + sig32A = rem64>>29; + } else { + sig32A = rem64>>30; + } + recipSqrt32 = softfloat_approxRecipSqrt32_1( expA, sig32A ); + sig32Z = ((uint64_t) sig32A * recipSqrt32)>>32; + if ( expA ) sig32Z >>= 1; + qs[2] = sig32Z; + rem64 -= (uint64_t) sig32Z * sig32Z; + rem[indexWord( 4, 3 )] = rem64>>32; + rem[indexWord( 4, 2 )] = rem64; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = ((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32; + sig64Z = ((uint64_t) sig32Z<<32) + ((uint64_t) q<<3); + term[indexWord( 4, 3 )] = 0; + term[indexWord( 4, 0 )] = 0; + /*------------------------------------------------------------------------ + | (Repeating this loop is a rare occurrence.) + *------------------------------------------------------------------------*/ + for (;;) { + x64 = ((uint64_t) sig32Z<<32) + sig64Z; + term[indexWord( 4, 2 )] = x64>>32; + term[indexWord( 4, 1 )] = x64; + softfloat_remStep128MBy32( rem, 29, term, q, y ); + rem32 = y[indexWord( 4, 3 )]; + if ( ! (rem32 & 0x80000000) ) break; + --q; + sig64Z -= 1<<3; + } + qs[1] = q; + rem64 = (uint64_t) rem32<<32 | y[indexWord( 4, 2 )]; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = ((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32; + if ( rem64>>34 ) q += recipSqrt32; + sig64Z <<= 1; + /*------------------------------------------------------------------------ + | (Repeating this loop is a rare occurrence.) + *------------------------------------------------------------------------*/ + for (;;) { + x64 = sig64Z + (q>>26); + term[indexWord( 4, 2 )] = x64>>32; + term[indexWord( 4, 1 )] = x64; + term[indexWord( 4, 0 )] = q<<6; + softfloat_remStep128MBy32( + y, 29, term, q, &rem[indexMultiwordHi( 6, 4 )] ); + rem32 = rem[indexWordHi( 6 )]; + if ( ! (rem32 & 0x80000000) ) break; + --q; + } + qs[0] = q; + rem64 = (uint64_t) rem32<<32 | rem[indexWord( 6, 4 )]; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + q = (((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32) + 2; + if ( rem64>>34 ) q += recipSqrt32; + x64 = (uint64_t) q<<27; + y[indexWord( 5, 0 )] = x64; + x64 = ((uint64_t) qs[0]<<24) + (x64>>32); + y[indexWord( 5, 1 )] = x64; + x64 = ((uint64_t) qs[1]<<21) + (x64>>32); + y[indexWord( 5, 2 )] = x64; + x64 = ((uint64_t) qs[2]<<18) + (x64>>32); + y[indexWord( 5, 3 )] = x64; + y[indexWord( 5, 4 )] = x64>>32; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( (q & 0xF) <= 2 ) { + q &= ~3; + y[indexWordLo( 5 )] = q<<27; + term[indexWord( 5, 4 )] = 0; + term[indexWord( 5, 3 )] = 0; + term[indexWord( 5, 2 )] = 0; + term[indexWord( 5, 1 )] = q>>6; + term[indexWord( 5, 0 )] = q<<26; + softfloat_sub160M( y, term, term ); + rem[indexWord( 6, 1 )] = 0; + rem[indexWord( 6, 0 )] = 0; + softfloat_remStep160MBy32( + &rem[indexMultiwordLo( 6, 5 )], + 14, + term, + q, + &rem[indexMultiwordLo( 6, 5 )] + ); + rem32 = rem[indexWord( 6, 4 )]; + if ( rem32 & 0x80000000 ) { + softfloat_sub1X160M( y ); + } else { + if ( + rem32 || rem[indexWord( 6, 0 )] || rem[indexWord( 6, 1 )] + || (rem[indexWord( 6, 3 )] | rem[indexWord( 6, 2 )]) + ) { + y[indexWordLo( 5 )] |= 1; + } + } + } + softfloat_roundPackMToF128M( 0, expZ, y, zWPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + invalid: + softfloat_invalidF128M( zWPtr ); + return; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + copyA: + zWPtr[indexWordHi( 4 )] = uiA96; + zWPtr[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )]; + zWPtr[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )]; + zWPtr[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )]; + +} + +#endif + +/**** ended inlining ../../source/f128M_sqrt.c ****/ +/**** start inlining ../../source/f128M_eq.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool f128M_eq( const float128_t *aPtr, const float128_t *bPtr ) +{ + + return f128_eq( *aPtr, *bPtr ); + +} + +#else + +bool f128M_eq( const float128_t *aPtr, const float128_t *bPtr ) +{ + const uint32_t *aWPtr, *bWPtr; + uint32_t wordA, wordB, uiA96, uiB96; + bool possibleOppositeZeros; + uint32_t mashWord; + + aWPtr = (const uint32_t *) aPtr; + bWPtr = (const uint32_t *) bPtr; + wordA = aWPtr[indexWord( 4, 2 )]; + wordB = bWPtr[indexWord( 4, 2 )]; + if ( wordA != wordB ) goto false_checkSigNaNs; + uiA96 = aWPtr[indexWordHi( 4 )]; + uiB96 = bWPtr[indexWordHi( 4 )]; + possibleOppositeZeros = false; + if ( uiA96 != uiB96 ) { + possibleOppositeZeros = (((uiA96 | uiB96) & 0x7FFFFFFF) == 0); + if ( ! possibleOppositeZeros ) goto false_checkSigNaNs; + } + mashWord = wordA | wordB; + wordA = aWPtr[indexWord( 4, 1 )]; + wordB = bWPtr[indexWord( 4, 1 )]; + if ( wordA != wordB ) goto false_checkSigNaNs; + mashWord |= wordA | wordB; + wordA = aWPtr[indexWord( 4, 0 )]; + wordB = bWPtr[indexWord( 4, 0 )]; + if ( wordA != wordB ) goto false_checkSigNaNs; + if ( possibleOppositeZeros && ((mashWord | wordA | wordB) != 0) ) { + goto false_checkSigNaNs; + } + if ( ! softfloat_isNaNF128M( aWPtr ) && ! softfloat_isNaNF128M( bWPtr ) ) { + return true; + } + false_checkSigNaNs: + if ( + f128M_isSignalingNaN( (const float128_t *) aWPtr ) + || f128M_isSignalingNaN( (const float128_t *) bWPtr ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + +} + +#endif + +/**** ended inlining ../../source/f128M_eq.c ****/ +/**** start inlining ../../source/f128M_le.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool f128M_le( const float128_t *aPtr, const float128_t *bPtr ) +{ + + return f128_le( *aPtr, *bPtr ); + +} + +#else + +bool f128M_le( const float128_t *aPtr, const float128_t *bPtr ) +{ + const uint32_t *aWPtr, *bWPtr; + uint32_t uiA96, uiB96; + bool signA, signB; + uint32_t wordA, wordB; + + aWPtr = (const uint32_t *) aPtr; + bWPtr = (const uint32_t *) bPtr; + if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + uiA96 = aWPtr[indexWordHi( 4 )]; + uiB96 = bWPtr[indexWordHi( 4 )]; + signA = signF128UI96( uiA96 ); + signB = signF128UI96( uiB96 ); + if ( signA != signB ) { + if ( signA ) return true; + if ( (uiA96 | uiB96) & 0x7FFFFFFF ) return false; + wordA = aWPtr[indexWord( 4, 2 )]; + wordB = bWPtr[indexWord( 4, 2 )]; + if ( wordA | wordB ) return false; + wordA = aWPtr[indexWord( 4, 1 )]; + wordB = bWPtr[indexWord( 4, 1 )]; + if ( wordA | wordB ) return false; + wordA = aWPtr[indexWord( 4, 0 )]; + wordB = bWPtr[indexWord( 4, 0 )]; + return ((wordA | wordB) == 0); + } + if ( signA ) { + aWPtr = (const uint32_t *) bPtr; + bWPtr = (const uint32_t *) aPtr; + } + return (softfloat_compare128M( aWPtr, bWPtr ) <= 0); + +} + +#endif + +/**** ended inlining ../../source/f128M_le.c ****/ +/**** start inlining ../../source/f128M_lt.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool f128M_lt( const float128_t *aPtr, const float128_t *bPtr ) +{ + + return f128_lt( *aPtr, *bPtr ); + +} + +#else + +bool f128M_lt( const float128_t *aPtr, const float128_t *bPtr ) +{ + const uint32_t *aWPtr, *bWPtr; + uint32_t uiA96, uiB96; + bool signA, signB; + uint32_t wordA, wordB; + + aWPtr = (const uint32_t *) aPtr; + bWPtr = (const uint32_t *) bPtr; + if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + uiA96 = aWPtr[indexWordHi( 4 )]; + uiB96 = bWPtr[indexWordHi( 4 )]; + signA = signF128UI96( uiA96 ); + signB = signF128UI96( uiB96 ); + if ( signA != signB ) { + if ( signB ) return false; + if ( (uiA96 | uiB96) & 0x7FFFFFFF ) return true; + wordA = aWPtr[indexWord( 4, 2 )]; + wordB = bWPtr[indexWord( 4, 2 )]; + if ( wordA | wordB ) return true; + wordA = aWPtr[indexWord( 4, 1 )]; + wordB = bWPtr[indexWord( 4, 1 )]; + if ( wordA | wordB ) return true; + wordA = aWPtr[indexWord( 4, 0 )]; + wordB = bWPtr[indexWord( 4, 0 )]; + return ((wordA | wordB) != 0); + } + if ( signA ) { + aWPtr = (const uint32_t *) bPtr; + bWPtr = (const uint32_t *) aPtr; + } + return (softfloat_compare128M( aWPtr, bWPtr ) < 0); + +} + +#endif + +/**** ended inlining ../../source/f128M_lt.c ****/ +/**** start inlining ../../source/f128M_eq_signaling.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool f128M_eq_signaling( const float128_t *aPtr, const float128_t *bPtr ) +{ + + return f128_eq_signaling( *aPtr, *bPtr ); + +} + +#else + +bool f128M_eq_signaling( const float128_t *aPtr, const float128_t *bPtr ) +{ + const uint32_t *aWPtr, *bWPtr; + uint32_t wordA, wordB, uiA96, uiB96; + bool possibleOppositeZeros; + uint32_t mashWord; + + aWPtr = (const uint32_t *) aPtr; + bWPtr = (const uint32_t *) bPtr; + if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + return false; + } + wordA = aWPtr[indexWord( 4, 2 )]; + wordB = bWPtr[indexWord( 4, 2 )]; + if ( wordA != wordB ) return false; + uiA96 = aWPtr[indexWordHi( 4 )]; + uiB96 = bWPtr[indexWordHi( 4 )]; + possibleOppositeZeros = false; + if ( uiA96 != uiB96 ) { + possibleOppositeZeros = (((uiA96 | uiB96) & 0x7FFFFFFF) == 0); + if ( ! possibleOppositeZeros ) return false; + } + mashWord = wordA | wordB; + wordA = aWPtr[indexWord( 4, 1 )]; + wordB = bWPtr[indexWord( 4, 1 )]; + if ( wordA != wordB ) return false; + mashWord |= wordA | wordB; + wordA = aWPtr[indexWord( 4, 0 )]; + wordB = bWPtr[indexWord( 4, 0 )]; + return + (wordA == wordB) + && (! possibleOppositeZeros || ((mashWord | wordA | wordB) == 0)); + +} + +#endif + +/**** ended inlining ../../source/f128M_eq_signaling.c ****/ +/**** start inlining ../../source/f128M_le_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool f128M_le_quiet( const float128_t *aPtr, const float128_t *bPtr ) +{ + + return f128_le_quiet( *aPtr, *bPtr ); + +} + +#else + +bool f128M_le_quiet( const float128_t *aPtr, const float128_t *bPtr ) +{ + const uint32_t *aWPtr, *bWPtr; + uint32_t uiA96, uiB96; + bool signA, signB; + uint32_t wordA, wordB; + + aWPtr = (const uint32_t *) aPtr; + bWPtr = (const uint32_t *) bPtr; + if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) { + if ( f128M_isSignalingNaN( aPtr ) || f128M_isSignalingNaN( bPtr ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + uiA96 = aWPtr[indexWordHi( 4 )]; + uiB96 = bWPtr[indexWordHi( 4 )]; + signA = signF128UI96( uiA96 ); + signB = signF128UI96( uiB96 ); + if ( signA != signB ) { + if ( signA ) return true; + if ( (uiA96 | uiB96) & 0x7FFFFFFF ) return false; + wordA = aWPtr[indexWord( 4, 2 )]; + wordB = bWPtr[indexWord( 4, 2 )]; + if ( wordA | wordB ) return false; + wordA = aWPtr[indexWord( 4, 1 )]; + wordB = bWPtr[indexWord( 4, 1 )]; + if ( wordA | wordB ) return false; + wordA = aWPtr[indexWord( 4, 0 )]; + wordB = bWPtr[indexWord( 4, 0 )]; + return ((wordA | wordB) == 0); + } + if ( signA ) { + aWPtr = (const uint32_t *) bPtr; + bWPtr = (const uint32_t *) aPtr; + } + return (softfloat_compare128M( aWPtr, bWPtr ) <= 0); + +} + +#endif + +/**** ended inlining ../../source/f128M_le_quiet.c ****/ +/**** start inlining ../../source/f128M_lt_quiet.c ****/ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +/**** skipping file: platform.h ****/ +/**** skipping file: internals.h ****/ +/**** skipping file: specialize.h ****/ +/**** skipping file: softfloat.h ****/ + +#ifdef SOFTFLOAT_FAST_INT64 + +bool f128M_lt_quiet( const float128_t *aPtr, const float128_t *bPtr ) +{ + + return f128_lt_quiet( *aPtr, *bPtr ); + +} + +#else + +bool f128M_lt_quiet( const float128_t *aPtr, const float128_t *bPtr ) +{ + const uint32_t *aWPtr, *bWPtr; + uint32_t uiA96, uiB96; + bool signA, signB; + uint32_t wordA, wordB; + + aWPtr = (const uint32_t *) aPtr; + bWPtr = (const uint32_t *) bPtr; + if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) { + if ( f128M_isSignalingNaN( aPtr ) || f128M_isSignalingNaN( bPtr ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + uiA96 = aWPtr[indexWordHi( 4 )]; + uiB96 = bWPtr[indexWordHi( 4 )]; + signA = signF128UI96( uiA96 ); + signB = signF128UI96( uiB96 ); + if ( signA != signB ) { + if ( signB ) return false; + if ( (uiA96 | uiB96) & 0x7FFFFFFF ) return true; + wordA = aWPtr[indexWord( 4, 2 )]; + wordB = bWPtr[indexWord( 4, 2 )]; + if ( wordA | wordB ) return true; + wordA = aWPtr[indexWord( 4, 1 )]; + wordB = bWPtr[indexWord( 4, 1 )]; + if ( wordA | wordB ) return true; + wordA = aWPtr[indexWord( 4, 0 )]; + wordB = bWPtr[indexWord( 4, 0 )]; + return ((wordA | wordB) != 0); + } + if ( signA ) { + aWPtr = (const uint32_t *) bPtr; + bWPtr = (const uint32_t *) aPtr; + } + return (softfloat_compare128M( aWPtr, bWPtr ) < 0); + +} + +#endif + +/**** ended inlining ../../source/f128M_lt_quiet.c ****/ diff --git a/lib/utf8.js b/lib/utf8.js new file mode 100644 index 0000000..4875834 --- /dev/null +++ b/lib/utf8.js @@ -0,0 +1,63 @@ +// ------------------------------------------------- +// ------------------ UTF8 Helpers ----------------- +// ------------------------------------------------- + +"use strict"; + +var UTF8 = {}; + +/** @constructor */ +function UTF8StreamToUnicode() { + + this.stream = new Uint8Array(5); + this.ofs = 0; + + this.Put = function(key) { + this.stream[this.ofs] = key; + this.ofs++; + switch(this.ofs) { + case 1: + if (this.stream[0] < 128) { + this.ofs = 0; + return this.stream[0]; + } + break; + + case 2: + if ((this.stream[0]&0xE0) == 0xC0) + if ((this.stream[1]&0xC0) == 0x80) { + this.ofs = 0; + return ((this.stream[0]&0x1F)<<6) | (this.stream[1]&0x3F); + } + break; + + case 3: + break; + + case 4: + break; + + default: + return -1; + //this.ofs = 0; + //break; + } + return -1; + }; +} + +function UnicodeToUTF8Stream(key) +{ + if (key < 0x80) return [key]; + if (key < 0x800) return [0xC0|((key>>6)&0x1F), 0x80|(key&0x3F)]; +} + +UTF8.UTF8Length = function(s) +{ + var length = 0; + for(var i=0; i +void *calloc(size_t nmemb, size_t size); +void *memset(void *s, int c, size_t n); +void *memcpy(void *dest, const void *src, size_t n); +void *memmove(void *dest, const void *src, size_t n); +void *malloc(size_t size); +void free(void *ptr); +/** + * \file zstddeclib.c + * Single-file Zstandard decompressor. + * + * Generate using: + * \code + * combine.sh -r ../../lib -o zstddeclib.c zstddeclib-in.c + * \endcode + */ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ +/* + * Settings to bake for the standalone decompressor. + * + * Note: It's important that none of these affects 'zstd.h' (only the + * implementation files we're amalgamating). + * + * Note: MEM_MODULE stops xxhash redefining BYTE, U16, etc., which are also + * defined in mem.h (breaking C99 compatibility). + * + * Note: the undefs for xxHash allow Zstd's implementation to coinside with with + * standalone xxHash usage (with global defines). + */ +#define DEBUGLEVEL 0 +#define MEM_MODULE +#undef XXH_NAMESPACE +#define XXH_NAMESPACE ZSTD_ +#undef XXH_PRIVATE_API +#define XXH_PRIVATE_API +#undef XXH_INLINE_ALL +#define XXH_INLINE_ALL +#define ZSTD_LEGACY_SUPPORT 0 +#define ZSTD_LIB_COMPRESSION 0 +#define ZSTD_LIB_DEPRECATED 0 +#define ZSTD_NOBENCH +#define ZSTD_STRIP_ERROR_STRINGS + +/**** start inlining common/debug.c ****/ +/* ****************************************************************** + * debug + * Part of FSE library + * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + + +/* + * This module only hosts one global variable + * which can be used to dynamically influence the verbosity of traces, + * such as DEBUGLOG and RAWLOG + */ + +/**** start inlining debug.h ****/ +/* ****************************************************************** + * debug + * Part of FSE library + * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + + +/* + * The purpose of this header is to enable debug functions. + * They regroup assert(), DEBUGLOG() and RAWLOG() for run-time, + * and DEBUG_STATIC_ASSERT() for compile-time. + * + * By default, DEBUGLEVEL==0, which means run-time debug is disabled. + * + * Level 1 enables assert() only. + * Starting level 2, traces can be generated and pushed to stderr. + * The higher the level, the more verbose the traces. + * + * It's possible to dynamically adjust level using variable g_debug_level, + * which is only declared if DEBUGLEVEL>=2, + * and is a global variable, not multi-thread protected (use with care) + */ + +#ifndef DEBUG_H_12987983217 +#define DEBUG_H_12987983217 + +#if defined (__cplusplus) +extern "C" { +#endif + + +/* static assert is triggered at compile time, leaving no runtime artefact. + * static assert only works with compile-time constants. + * Also, this variant can only be used inside a function. */ +#define DEBUG_STATIC_ASSERT(c) (void)sizeof(char[(c) ? 1 : -1]) + + +/* DEBUGLEVEL is expected to be defined externally, + * typically through compiler command line. + * Value must be a number. */ +#ifndef DEBUGLEVEL +# define DEBUGLEVEL 0 +#endif + + +/* DEBUGFILE can be defined externally, + * typically through compiler command line. + * note : currently useless. + * Value must be stderr or stdout */ +#ifndef DEBUGFILE +# define DEBUGFILE stderr +#endif + + +/* recommended values for DEBUGLEVEL : + * 0 : release mode, no debug, all run-time checks disabled + * 1 : enables assert() only, no display + * 2 : reserved, for currently active debug path + * 3 : events once per object lifetime (CCtx, CDict, etc.) + * 4 : events once per frame + * 5 : events once per block + * 6 : events once per sequence (verbose) + * 7+: events at every position (*very* verbose) + * + * It's generally inconvenient to output traces > 5. + * In which case, it's possible to selectively trigger high verbosity levels + * by modifying g_debug_level. + */ + +#if (DEBUGLEVEL>=1) +# include +#else +# ifndef assert /* assert may be already defined, due to prior #include */ +# define assert(condition) ((void)0) /* disable assert (default) */ +# endif +#endif + +#if (DEBUGLEVEL>=2) +# include +extern int g_debuglevel; /* the variable is only declared, + it actually lives in debug.c, + and is shared by the whole process. + It's not thread-safe. + It's useful when enabling very verbose levels + on selective conditions (such as position in src) */ + +# define RAWLOG(l, ...) { \ + if (l<=g_debuglevel) { \ + fprintf(stderr, __VA_ARGS__); \ + } } +# define DEBUGLOG(l, ...) { \ + if (l<=g_debuglevel) { \ + fprintf(stderr, __FILE__ ": " __VA_ARGS__); \ + fprintf(stderr, " \n"); \ + } } +#else +# define RAWLOG(l, ...) {} /* disabled */ +# define DEBUGLOG(l, ...) {} /* disabled */ +#endif + + +#if defined (__cplusplus) +} +#endif + +#endif /* DEBUG_H_12987983217 */ +/**** ended inlining debug.h ****/ + +int g_debuglevel = DEBUGLEVEL; +/**** ended inlining common/debug.c ****/ +/**** start inlining common/entropy_common.c ****/ +/* ****************************************************************** + * Common functions of New Generation Entropy library + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy + * - Public forum : https://groups.google.com/forum/#!forum/lz4c + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + +/* ************************************* +* Dependencies +***************************************/ +/**** start inlining mem.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef MEM_H_MODULE +#define MEM_H_MODULE + +#if defined (__cplusplus) +extern "C" { +#endif + +/*-**************************************** +* Dependencies +******************************************/ +#include /* size_t, ptrdiff_t */ + + +/*-**************************************** +* Compiler specifics +******************************************/ +#if defined(_MSC_VER) /* Visual Studio */ +# include /* _byteswap_* */ +#endif +#if defined(__GNUC__) +# define MEM_STATIC static __inline __attribute__((unused)) +#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define MEM_STATIC static inline +#elif defined(_MSC_VER) +# define MEM_STATIC static __inline +#else +# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ +#endif + +#ifndef __has_builtin +# define __has_builtin(x) 0 /* compat. with non-clang compilers */ +#endif + +/* code only tested on 32 and 64 bits systems */ +#define MEM_STATIC_ASSERT(c) { enum { MEM_static_assert = 1/(int)(!!(c)) }; } +MEM_STATIC void MEM_check(void) { MEM_STATIC_ASSERT((sizeof(size_t)==4) || (sizeof(size_t)==8)); } + +/* detects whether we are being compiled under msan */ +#if defined (__has_feature) +# if __has_feature(memory_sanitizer) +# define MEMORY_SANITIZER 1 +# endif +#endif + +#if defined (MEMORY_SANITIZER) +/* Not all platforms that support msan provide sanitizers/msan_interface.h. + * We therefore declare the functions we need ourselves, rather than trying to + * include the header file... */ + +#include /* intptr_t */ + +/* Make memory region fully initialized (without changing its contents). */ +void __msan_unpoison(const volatile void *a, size_t size); + +/* Make memory region fully uninitialized (without changing its contents). + This is a legacy interface that does not update origin information. Use + __msan_allocated_memory() instead. */ +void __msan_poison(const volatile void *a, size_t size); + +/* Returns the offset of the first (at least partially) poisoned byte in the + memory range, or -1 if the whole range is good. */ +intptr_t __msan_test_shadow(const volatile void *x, size_t size); +#endif + +/* detects whether we are being compiled under asan */ +#if defined (__has_feature) +# if __has_feature(address_sanitizer) +# define ADDRESS_SANITIZER 1 +# endif +#elif defined(__SANITIZE_ADDRESS__) +# define ADDRESS_SANITIZER 1 +#endif + +#if defined (ADDRESS_SANITIZER) +/* Not all platforms that support asan provide sanitizers/asan_interface.h. + * We therefore declare the functions we need ourselves, rather than trying to + * include the header file... */ + +/** + * Marks a memory region ([addr, addr+size)) as unaddressable. + * + * This memory must be previously allocated by your program. Instrumented + * code is forbidden from accessing addresses in this region until it is + * unpoisoned. This function is not guaranteed to poison the entire region - + * it could poison only a subregion of [addr, addr+size) due to ASan + * alignment restrictions. + * + * \note This function is not thread-safe because no two threads can poison or + * unpoison memory in the same memory region simultaneously. + * + * \param addr Start of memory region. + * \param size Size of memory region. */ +void __asan_poison_memory_region(void const volatile *addr, size_t size); + +/** + * Marks a memory region ([addr, addr+size)) as addressable. + * + * This memory must be previously allocated by your program. Accessing + * addresses in this region is allowed until this region is poisoned again. + * This function could unpoison a super-region of [addr, addr+size) due + * to ASan alignment restrictions. + * + * \note This function is not thread-safe because no two threads can + * poison or unpoison memory in the same memory region simultaneously. + * + * \param addr Start of memory region. + * \param size Size of memory region. */ +void __asan_unpoison_memory_region(void const volatile *addr, size_t size); +#endif + + +/*-************************************************************** +* Basic Types +*****************************************************************/ +#if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# include + typedef uint8_t BYTE; + typedef uint16_t U16; + typedef int16_t S16; + typedef uint32_t U32; + typedef int32_t S32; + typedef uint64_t U64; + typedef int64_t S64; +#else +# include +#if CHAR_BIT != 8 +# error "this implementation requires char to be exactly 8-bit type" +#endif + typedef unsigned char BYTE; +#if USHRT_MAX != 65535 +# error "this implementation requires short to be exactly 16-bit type" +#endif + typedef unsigned short U16; + typedef signed short S16; +#if UINT_MAX != 4294967295 +# error "this implementation requires int to be exactly 32-bit type" +#endif + typedef unsigned int U32; + typedef signed int S32; +/* note : there are no limits defined for long long type in C90. + * limits exist in C99, however, in such case, is preferred */ + typedef unsigned long long U64; + typedef signed long long S64; +#endif + + +/*-************************************************************** +* Memory I/O +*****************************************************************/ +/* MEM_FORCE_MEMORY_ACCESS : + * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. + * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. + * The below switch allow to select different access method for improved performance. + * Method 0 (default) : use `memcpy()`. Safe and portable. + * Method 1 : `__packed` statement. It depends on compiler extension (i.e., not portable). + * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. + * Method 2 : direct access. This method is portable but violate C standard. + * It can generate buggy code on targets depending on alignment. + * In some circumstances, it's the only known way to get the most performance (i.e. GCC + ARMv6) + * See http://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details. + * Prefer these methods in priority order (0 > 1 > 2) + */ +#ifndef MEM_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ +# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) +# define MEM_FORCE_MEMORY_ACCESS 2 +# elif defined(__INTEL_COMPILER) || defined(__GNUC__) || defined(__ICCARM__) +# define MEM_FORCE_MEMORY_ACCESS 1 +# endif +#endif + +MEM_STATIC unsigned MEM_32bits(void) { return sizeof(size_t)==4; } +MEM_STATIC unsigned MEM_64bits(void) { return sizeof(size_t)==8; } + +MEM_STATIC unsigned MEM_isLittleEndian(void) +{ + const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ + return one.c[0]; +} + +#if defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==2) + +/* violates C standard, by lying on structure alignment. +Only use if no other choice to achieve best performance on target platform */ +MEM_STATIC U16 MEM_read16(const void* memPtr) { return *(const U16*) memPtr; } +MEM_STATIC U32 MEM_read32(const void* memPtr) { return *(const U32*) memPtr; } +MEM_STATIC U64 MEM_read64(const void* memPtr) { return *(const U64*) memPtr; } +MEM_STATIC size_t MEM_readST(const void* memPtr) { return *(const size_t*) memPtr; } + +MEM_STATIC void MEM_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } +MEM_STATIC void MEM_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } +MEM_STATIC void MEM_write64(void* memPtr, U64 value) { *(U64*)memPtr = value; } + +#elif defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==1) + +/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ +/* currently only defined for gcc and icc */ +#if defined(_MSC_VER) || (defined(__INTEL_COMPILER) && defined(WIN32)) + __pragma( pack(push, 1) ) + typedef struct { U16 v; } unalign16; + typedef struct { U32 v; } unalign32; + typedef struct { U64 v; } unalign64; + typedef struct { size_t v; } unalignArch; + __pragma( pack(pop) ) +#else + typedef struct { U16 v; } __attribute__((packed)) unalign16; + typedef struct { U32 v; } __attribute__((packed)) unalign32; + typedef struct { U64 v; } __attribute__((packed)) unalign64; + typedef struct { size_t v; } __attribute__((packed)) unalignArch; +#endif + +MEM_STATIC U16 MEM_read16(const void* ptr) { return ((const unalign16*)ptr)->v; } +MEM_STATIC U32 MEM_read32(const void* ptr) { return ((const unalign32*)ptr)->v; } +MEM_STATIC U64 MEM_read64(const void* ptr) { return ((const unalign64*)ptr)->v; } +MEM_STATIC size_t MEM_readST(const void* ptr) { return ((const unalignArch*)ptr)->v; } + +MEM_STATIC void MEM_write16(void* memPtr, U16 value) { ((unalign16*)memPtr)->v = value; } +MEM_STATIC void MEM_write32(void* memPtr, U32 value) { ((unalign32*)memPtr)->v = value; } +MEM_STATIC void MEM_write64(void* memPtr, U64 value) { ((unalign64*)memPtr)->v = value; } + +#else + +/* default method, safe and standard. + can sometimes prove slower */ + +MEM_STATIC U16 MEM_read16(const void* memPtr) +{ + U16 val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC U32 MEM_read32(const void* memPtr) +{ + U32 val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC U64 MEM_read64(const void* memPtr) +{ + U64 val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC size_t MEM_readST(const void* memPtr) +{ + size_t val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC void MEM_write16(void* memPtr, U16 value) +{ + memcpy(memPtr, &value, sizeof(value)); +} + +MEM_STATIC void MEM_write32(void* memPtr, U32 value) +{ + memcpy(memPtr, &value, sizeof(value)); +} + +MEM_STATIC void MEM_write64(void* memPtr, U64 value) +{ + memcpy(memPtr, &value, sizeof(value)); +} + +#endif /* MEM_FORCE_MEMORY_ACCESS */ + +MEM_STATIC U32 MEM_swap32(U32 in) +{ +#if defined(_MSC_VER) /* Visual Studio */ + return _byteswap_ulong(in); +#elif (defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) \ + || (defined(__clang__) && __has_builtin(__builtin_bswap32)) + return __builtin_bswap32(in); +#else + return ((in << 24) & 0xff000000 ) | + ((in << 8) & 0x00ff0000 ) | + ((in >> 8) & 0x0000ff00 ) | + ((in >> 24) & 0x000000ff ); +#endif +} + +MEM_STATIC U64 MEM_swap64(U64 in) +{ +#if defined(_MSC_VER) /* Visual Studio */ + return _byteswap_uint64(in); +#elif (defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) \ + || (defined(__clang__) && __has_builtin(__builtin_bswap64)) + return __builtin_bswap64(in); +#else + return ((in << 56) & 0xff00000000000000ULL) | + ((in << 40) & 0x00ff000000000000ULL) | + ((in << 24) & 0x0000ff0000000000ULL) | + ((in << 8) & 0x000000ff00000000ULL) | + ((in >> 8) & 0x00000000ff000000ULL) | + ((in >> 24) & 0x0000000000ff0000ULL) | + ((in >> 40) & 0x000000000000ff00ULL) | + ((in >> 56) & 0x00000000000000ffULL); +#endif +} + +MEM_STATIC size_t MEM_swapST(size_t in) +{ + if (MEM_32bits()) + return (size_t)MEM_swap32((U32)in); + else + return (size_t)MEM_swap64((U64)in); +} + +/*=== Little endian r/w ===*/ + +MEM_STATIC U16 MEM_readLE16(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_read16(memPtr); + else { + const BYTE* p = (const BYTE*)memPtr; + return (U16)(p[0] + (p[1]<<8)); + } +} + +MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val) +{ + if (MEM_isLittleEndian()) { + MEM_write16(memPtr, val); + } else { + BYTE* p = (BYTE*)memPtr; + p[0] = (BYTE)val; + p[1] = (BYTE)(val>>8); + } +} + +MEM_STATIC U32 MEM_readLE24(const void* memPtr) +{ + return MEM_readLE16(memPtr) + (((const BYTE*)memPtr)[2] << 16); +} + +MEM_STATIC void MEM_writeLE24(void* memPtr, U32 val) +{ + MEM_writeLE16(memPtr, (U16)val); + ((BYTE*)memPtr)[2] = (BYTE)(val>>16); +} + +MEM_STATIC U32 MEM_readLE32(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_read32(memPtr); + else + return MEM_swap32(MEM_read32(memPtr)); +} + +MEM_STATIC void MEM_writeLE32(void* memPtr, U32 val32) +{ + if (MEM_isLittleEndian()) + MEM_write32(memPtr, val32); + else + MEM_write32(memPtr, MEM_swap32(val32)); +} + +MEM_STATIC U64 MEM_readLE64(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_read64(memPtr); + else + return MEM_swap64(MEM_read64(memPtr)); +} + +MEM_STATIC void MEM_writeLE64(void* memPtr, U64 val64) +{ + if (MEM_isLittleEndian()) + MEM_write64(memPtr, val64); + else + MEM_write64(memPtr, MEM_swap64(val64)); +} + +MEM_STATIC size_t MEM_readLEST(const void* memPtr) +{ + if (MEM_32bits()) + return (size_t)MEM_readLE32(memPtr); + else + return (size_t)MEM_readLE64(memPtr); +} + +MEM_STATIC void MEM_writeLEST(void* memPtr, size_t val) +{ + if (MEM_32bits()) + MEM_writeLE32(memPtr, (U32)val); + else + MEM_writeLE64(memPtr, (U64)val); +} + +/*=== Big endian r/w ===*/ + +MEM_STATIC U32 MEM_readBE32(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_swap32(MEM_read32(memPtr)); + else + return MEM_read32(memPtr); +} + +MEM_STATIC void MEM_writeBE32(void* memPtr, U32 val32) +{ + if (MEM_isLittleEndian()) + MEM_write32(memPtr, MEM_swap32(val32)); + else + MEM_write32(memPtr, val32); +} + +MEM_STATIC U64 MEM_readBE64(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_swap64(MEM_read64(memPtr)); + else + return MEM_read64(memPtr); +} + +MEM_STATIC void MEM_writeBE64(void* memPtr, U64 val64) +{ + if (MEM_isLittleEndian()) + MEM_write64(memPtr, MEM_swap64(val64)); + else + MEM_write64(memPtr, val64); +} + +MEM_STATIC size_t MEM_readBEST(const void* memPtr) +{ + if (MEM_32bits()) + return (size_t)MEM_readBE32(memPtr); + else + return (size_t)MEM_readBE64(memPtr); +} + +MEM_STATIC void MEM_writeBEST(void* memPtr, size_t val) +{ + if (MEM_32bits()) + MEM_writeBE32(memPtr, (U32)val); + else + MEM_writeBE64(memPtr, (U64)val); +} + + +#if defined (__cplusplus) +} +#endif + +#endif /* MEM_H_MODULE */ +/**** ended inlining mem.h ****/ +/**** start inlining error_private.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* Note : this module is expected to remain private, do not expose it */ + +#ifndef ERROR_H_MODULE +#define ERROR_H_MODULE + +#if defined (__cplusplus) +extern "C" { +#endif + + +/* **************************************** +* Dependencies +******************************************/ +#include /* size_t */ +/**** start inlining zstd_errors.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_ERRORS_H_398273423 +#define ZSTD_ERRORS_H_398273423 + +#if defined (__cplusplus) +extern "C" { +#endif + +/*===== dependency =====*/ +#include /* size_t */ + + +/* ===== ZSTDERRORLIB_API : control library symbols visibility ===== */ +#ifndef ZSTDERRORLIB_VISIBILITY +# if defined(__GNUC__) && (__GNUC__ >= 4) +# define ZSTDERRORLIB_VISIBILITY __attribute__ ((visibility ("default"))) +# else +# define ZSTDERRORLIB_VISIBILITY +# endif +#endif +#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) +# define ZSTDERRORLIB_API __declspec(dllexport) ZSTDERRORLIB_VISIBILITY +#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) +# define ZSTDERRORLIB_API __declspec(dllimport) ZSTDERRORLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define ZSTDERRORLIB_API ZSTDERRORLIB_VISIBILITY +#endif + +/*-********************************************* + * Error codes list + *-********************************************* + * Error codes _values_ are pinned down since v1.3.1 only. + * Therefore, don't rely on values if you may link to any version < v1.3.1. + * + * Only values < 100 are considered stable. + * + * note 1 : this API shall be used with static linking only. + * dynamic linking is not yet officially supported. + * note 2 : Prefer relying on the enum than on its value whenever possible + * This is the only supported way to use the error list < v1.3.1 + * note 3 : ZSTD_isError() is always correct, whatever the library version. + **********************************************/ +typedef enum { + ZSTD_error_no_error = 0, + ZSTD_error_GENERIC = 1, + ZSTD_error_prefix_unknown = 10, + ZSTD_error_version_unsupported = 12, + ZSTD_error_frameParameter_unsupported = 14, + ZSTD_error_frameParameter_windowTooLarge = 16, + ZSTD_error_corruption_detected = 20, + ZSTD_error_checksum_wrong = 22, + ZSTD_error_dictionary_corrupted = 30, + ZSTD_error_dictionary_wrong = 32, + ZSTD_error_dictionaryCreation_failed = 34, + ZSTD_error_parameter_unsupported = 40, + ZSTD_error_parameter_outOfBound = 42, + ZSTD_error_tableLog_tooLarge = 44, + ZSTD_error_maxSymbolValue_tooLarge = 46, + ZSTD_error_maxSymbolValue_tooSmall = 48, + ZSTD_error_stage_wrong = 60, + ZSTD_error_init_missing = 62, + ZSTD_error_memory_allocation = 64, + ZSTD_error_workSpace_tooSmall= 66, + ZSTD_error_dstSize_tooSmall = 70, + ZSTD_error_srcSize_wrong = 72, + ZSTD_error_dstBuffer_null = 74, + /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */ + ZSTD_error_frameIndex_tooLarge = 100, + ZSTD_error_seekableIO = 102, + ZSTD_error_dstBuffer_wrong = 104, + ZSTD_error_maxCode = 120 /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */ +} ZSTD_ErrorCode; + +/*! ZSTD_getErrorCode() : + convert a `size_t` function result into a `ZSTD_ErrorCode` enum type, + which can be used to compare with enum list published above */ +ZSTDERRORLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult); +ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code); /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_ERRORS_H_398273423 */ +/**** ended inlining zstd_errors.h ****/ + + +/* **************************************** +* Compiler-specific +******************************************/ +#if defined(__GNUC__) +# define ERR_STATIC static __attribute__((unused)) +#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define ERR_STATIC static inline +#elif defined(_MSC_VER) +# define ERR_STATIC static __inline +#else +# define ERR_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ +#endif + + +/*-**************************************** +* Customization (error_public.h) +******************************************/ +typedef ZSTD_ErrorCode ERR_enum; +#define PREFIX(name) ZSTD_error_##name + + +/*-**************************************** +* Error codes handling +******************************************/ +#undef ERROR /* already defined on Visual Studio */ +#define ERROR(name) ZSTD_ERROR(name) +#define ZSTD_ERROR(name) ((size_t)-PREFIX(name)) + +ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); } + +ERR_STATIC ERR_enum ERR_getErrorCode(size_t code) { if (!ERR_isError(code)) return (ERR_enum)0; return (ERR_enum) (0-code); } + +/* check and forward error code */ +#define CHECK_V_F(e, f) size_t const e = f; if (ERR_isError(e)) return e +#define CHECK_F(f) { CHECK_V_F(_var_err__, f); } + + +/*-**************************************** +* Error Strings +******************************************/ + +const char* ERR_getErrorString(ERR_enum code); /* error_private.c */ + +ERR_STATIC const char* ERR_getErrorName(size_t code) +{ + return ERR_getErrorString(ERR_getErrorCode(code)); +} + +#if defined (__cplusplus) +} +#endif + +#endif /* ERROR_H_MODULE */ +/**** ended inlining error_private.h ****/ +#define FSE_STATIC_LINKING_ONLY /* FSE_MIN_TABLELOG */ +/**** start inlining fse.h ****/ +/* ****************************************************************** + * FSE : Finite State Entropy codec + * Public Prototypes declaration + * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + +#if defined (__cplusplus) +extern "C" { +#endif + +#ifndef FSE_H +#define FSE_H + + +/*-***************************************** +* Dependencies +******************************************/ +#include /* size_t, ptrdiff_t */ + + +/*-***************************************** +* FSE_PUBLIC_API : control library symbols visibility +******************************************/ +#if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4) +# define FSE_PUBLIC_API __attribute__ ((visibility ("default"))) +#elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) /* Visual expected */ +# define FSE_PUBLIC_API __declspec(dllexport) +#elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1) +# define FSE_PUBLIC_API __declspec(dllimport) /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define FSE_PUBLIC_API +#endif + +/*------ Version ------*/ +#define FSE_VERSION_MAJOR 0 +#define FSE_VERSION_MINOR 9 +#define FSE_VERSION_RELEASE 0 + +#define FSE_LIB_VERSION FSE_VERSION_MAJOR.FSE_VERSION_MINOR.FSE_VERSION_RELEASE +#define FSE_QUOTE(str) #str +#define FSE_EXPAND_AND_QUOTE(str) FSE_QUOTE(str) +#define FSE_VERSION_STRING FSE_EXPAND_AND_QUOTE(FSE_LIB_VERSION) + +#define FSE_VERSION_NUMBER (FSE_VERSION_MAJOR *100*100 + FSE_VERSION_MINOR *100 + FSE_VERSION_RELEASE) +FSE_PUBLIC_API unsigned FSE_versionNumber(void); /**< library version number; to be used when checking dll version */ + + +/*-**************************************** +* FSE simple functions +******************************************/ +/*! FSE_compress() : + Compress content of buffer 'src', of size 'srcSize', into destination buffer 'dst'. + 'dst' buffer must be already allocated. Compression runs faster is dstCapacity >= FSE_compressBound(srcSize). + @return : size of compressed data (<= dstCapacity). + Special values : if return == 0, srcData is not compressible => Nothing is stored within dst !!! + if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression instead. + if FSE_isError(return), compression failed (more details using FSE_getErrorName()) +*/ +FSE_PUBLIC_API size_t FSE_compress(void* dst, size_t dstCapacity, + const void* src, size_t srcSize); + +/*! FSE_decompress(): + Decompress FSE data from buffer 'cSrc', of size 'cSrcSize', + into already allocated destination buffer 'dst', of size 'dstCapacity'. + @return : size of regenerated data (<= maxDstSize), + or an error code, which can be tested using FSE_isError() . + + ** Important ** : FSE_decompress() does not decompress non-compressible nor RLE data !!! + Why ? : making this distinction requires a header. + Header management is intentionally delegated to the user layer, which can better manage special cases. +*/ +FSE_PUBLIC_API size_t FSE_decompress(void* dst, size_t dstCapacity, + const void* cSrc, size_t cSrcSize); + + +/*-***************************************** +* Tool functions +******************************************/ +FSE_PUBLIC_API size_t FSE_compressBound(size_t size); /* maximum compressed size */ + +/* Error Management */ +FSE_PUBLIC_API unsigned FSE_isError(size_t code); /* tells if a return value is an error code */ +FSE_PUBLIC_API const char* FSE_getErrorName(size_t code); /* provides error code string (useful for debugging) */ + + +/*-***************************************** +* FSE advanced functions +******************************************/ +/*! FSE_compress2() : + Same as FSE_compress(), but allows the selection of 'maxSymbolValue' and 'tableLog' + Both parameters can be defined as '0' to mean : use default value + @return : size of compressed data + Special values : if return == 0, srcData is not compressible => Nothing is stored within cSrc !!! + if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression. + if FSE_isError(return), it's an error code. +*/ +FSE_PUBLIC_API size_t FSE_compress2 (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog); + + +/*-***************************************** +* FSE detailed API +******************************************/ +/*! +FSE_compress() does the following: +1. count symbol occurrence from source[] into table count[] (see hist.h) +2. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog) +3. save normalized counters to memory buffer using writeNCount() +4. build encoding table 'CTable' from normalized counters +5. encode the data stream using encoding table 'CTable' + +FSE_decompress() does the following: +1. read normalized counters with readNCount() +2. build decoding table 'DTable' from normalized counters +3. decode the data stream using decoding table 'DTable' + +The following API allows targeting specific sub-functions for advanced tasks. +For example, it's possible to compress several blocks using the same 'CTable', +or to save and provide normalized distribution using external method. +*/ + +/* *** COMPRESSION *** */ + +/*! FSE_optimalTableLog(): + dynamically downsize 'tableLog' when conditions are met. + It saves CPU time, by using smaller tables, while preserving or even improving compression ratio. + @return : recommended tableLog (necessarily <= 'maxTableLog') */ +FSE_PUBLIC_API unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue); + +/*! FSE_normalizeCount(): + normalize counts so that sum(count[]) == Power_of_2 (2^tableLog) + 'normalizedCounter' is a table of short, of minimum size (maxSymbolValue+1). + @return : tableLog, + or an errorCode, which can be tested using FSE_isError() */ +FSE_PUBLIC_API size_t FSE_normalizeCount(short* normalizedCounter, unsigned tableLog, + const unsigned* count, size_t srcSize, unsigned maxSymbolValue); + +/*! FSE_NCountWriteBound(): + Provides the maximum possible size of an FSE normalized table, given 'maxSymbolValue' and 'tableLog'. + Typically useful for allocation purpose. */ +FSE_PUBLIC_API size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog); + +/*! FSE_writeNCount(): + Compactly save 'normalizedCounter' into 'buffer'. + @return : size of the compressed table, + or an errorCode, which can be tested using FSE_isError(). */ +FSE_PUBLIC_API size_t FSE_writeNCount (void* buffer, size_t bufferSize, + const short* normalizedCounter, + unsigned maxSymbolValue, unsigned tableLog); + +/*! Constructor and Destructor of FSE_CTable. + Note that FSE_CTable size depends on 'tableLog' and 'maxSymbolValue' */ +typedef unsigned FSE_CTable; /* don't allocate that. It's only meant to be more restrictive than void* */ +FSE_PUBLIC_API FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog); +FSE_PUBLIC_API void FSE_freeCTable (FSE_CTable* ct); + +/*! FSE_buildCTable(): + Builds `ct`, which must be already allocated, using FSE_createCTable(). + @return : 0, or an errorCode, which can be tested using FSE_isError() */ +FSE_PUBLIC_API size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog); + +/*! FSE_compress_usingCTable(): + Compress `src` using `ct` into `dst` which must be already allocated. + @return : size of compressed data (<= `dstCapacity`), + or 0 if compressed data could not fit into `dst`, + or an errorCode, which can be tested using FSE_isError() */ +FSE_PUBLIC_API size_t FSE_compress_usingCTable (void* dst, size_t dstCapacity, const void* src, size_t srcSize, const FSE_CTable* ct); + +/*! +Tutorial : +---------- +The first step is to count all symbols. FSE_count() does this job very fast. +Result will be saved into 'count', a table of unsigned int, which must be already allocated, and have 'maxSymbolValuePtr[0]+1' cells. +'src' is a table of bytes of size 'srcSize'. All values within 'src' MUST be <= maxSymbolValuePtr[0] +maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value) +FSE_count() will return the number of occurrence of the most frequent symbol. +This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility. +If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()). + +The next step is to normalize the frequencies. +FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'. +It also guarantees a minimum of 1 to any Symbol with frequency >= 1. +You can use 'tableLog'==0 to mean "use default tableLog value". +If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(), +which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default"). + +The result of FSE_normalizeCount() will be saved into a table, +called 'normalizedCounter', which is a table of signed short. +'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells. +The return value is tableLog if everything proceeded as expected. +It is 0 if there is a single symbol within distribution. +If there is an error (ex: invalid tableLog value), the function will return an ErrorCode (which can be tested using FSE_isError()). + +'normalizedCounter' can be saved in a compact manner to a memory area using FSE_writeNCount(). +'buffer' must be already allocated. +For guaranteed success, buffer size must be at least FSE_headerBound(). +The result of the function is the number of bytes written into 'buffer'. +If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError(); ex : buffer size too small). + +'normalizedCounter' can then be used to create the compression table 'CTable'. +The space required by 'CTable' must be already allocated, using FSE_createCTable(). +You can then use FSE_buildCTable() to fill 'CTable'. +If there is an error, both functions will return an ErrorCode (which can be tested using FSE_isError()). + +'CTable' can then be used to compress 'src', with FSE_compress_usingCTable(). +Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize' +The function returns the size of compressed data (without header), necessarily <= `dstCapacity`. +If it returns '0', compressed data could not fit into 'dst'. +If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()). +*/ + + +/* *** DECOMPRESSION *** */ + +/*! FSE_readNCount(): + Read compactly saved 'normalizedCounter' from 'rBuffer'. + @return : size read from 'rBuffer', + or an errorCode, which can be tested using FSE_isError(). + maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */ +FSE_PUBLIC_API size_t FSE_readNCount (short* normalizedCounter, + unsigned* maxSymbolValuePtr, unsigned* tableLogPtr, + const void* rBuffer, size_t rBuffSize); + +/*! Constructor and Destructor of FSE_DTable. + Note that its size depends on 'tableLog' */ +typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */ +FSE_PUBLIC_API FSE_DTable* FSE_createDTable(unsigned tableLog); +FSE_PUBLIC_API void FSE_freeDTable(FSE_DTable* dt); + +/*! FSE_buildDTable(): + Builds 'dt', which must be already allocated, using FSE_createDTable(). + return : 0, or an errorCode, which can be tested using FSE_isError() */ +FSE_PUBLIC_API size_t FSE_buildDTable (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog); + +/*! FSE_decompress_usingDTable(): + Decompress compressed source `cSrc` of size `cSrcSize` using `dt` + into `dst` which must be already allocated. + @return : size of regenerated data (necessarily <= `dstCapacity`), + or an errorCode, which can be tested using FSE_isError() */ +FSE_PUBLIC_API size_t FSE_decompress_usingDTable(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, const FSE_DTable* dt); + +/*! +Tutorial : +---------- +(Note : these functions only decompress FSE-compressed blocks. + If block is uncompressed, use memcpy() instead + If block is a single repeated byte, use memset() instead ) + +The first step is to obtain the normalized frequencies of symbols. +This can be performed by FSE_readNCount() if it was saved using FSE_writeNCount(). +'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short. +In practice, that means it's necessary to know 'maxSymbolValue' beforehand, +or size the table to handle worst case situations (typically 256). +FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'. +The result of FSE_readNCount() is the number of bytes read from 'rBuffer'. +Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that. +If there is an error, the function will return an error code, which can be tested using FSE_isError(). + +The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'. +This is performed by the function FSE_buildDTable(). +The space required by 'FSE_DTable' must be already allocated using FSE_createDTable(). +If there is an error, the function will return an error code, which can be tested using FSE_isError(). + +`FSE_DTable` can then be used to decompress `cSrc`, with FSE_decompress_usingDTable(). +`cSrcSize` must be strictly correct, otherwise decompression will fail. +FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`). +If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small) +*/ + +#endif /* FSE_H */ + +#if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY) +#define FSE_H_FSE_STATIC_LINKING_ONLY + +/* *** Dependency *** */ +/**** start inlining bitstream.h ****/ +/* ****************************************************************** + * bitstream + * Part of FSE library + * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ +#ifndef BITSTREAM_H_MODULE +#define BITSTREAM_H_MODULE + +#if defined (__cplusplus) +extern "C" { +#endif + +/* +* This API consists of small unitary functions, which must be inlined for best performance. +* Since link-time-optimization is not available for all compilers, +* these functions are defined into a .h to be included. +*/ + +/*-**************************************** +* Dependencies +******************************************/ +/**** skipping file: mem.h ****/ +/**** start inlining compiler.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_COMPILER_H +#define ZSTD_COMPILER_H + +/*-******************************************************* +* Compiler specifics +*********************************************************/ +/* force inlining */ + +#if !defined(ZSTD_NO_INLINE) +#if (defined(__GNUC__) && !defined(__STRICT_ANSI__)) || defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ +# define INLINE_KEYWORD inline +#else +# define INLINE_KEYWORD +#endif + +#if defined(__GNUC__) || defined(__ICCARM__) +# define FORCE_INLINE_ATTR __attribute__((always_inline)) +#elif defined(_MSC_VER) +# define FORCE_INLINE_ATTR __forceinline +#else +# define FORCE_INLINE_ATTR +#endif + +#else + +#define INLINE_KEYWORD +#define FORCE_INLINE_ATTR + +#endif + +/** + On MSVC qsort requires that functions passed into it use the __cdecl calling conversion(CC). + This explictly marks such functions as __cdecl so that the code will still compile + if a CC other than __cdecl has been made the default. +*/ +#if defined(_MSC_VER) +# define WIN_CDECL __cdecl +#else +# define WIN_CDECL +#endif + +/** + * FORCE_INLINE_TEMPLATE is used to define C "templates", which take constant + * parameters. They must be inlined for the compiler to eliminate the constant + * branches. + */ +#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR +/** + * HINT_INLINE is used to help the compiler generate better code. It is *not* + * used for "templates", so it can be tweaked based on the compilers + * performance. + * + * gcc-4.8 and gcc-4.9 have been shown to benefit from leaving off the + * always_inline attribute. + * + * clang up to 5.0.0 (trunk) benefit tremendously from the always_inline + * attribute. + */ +#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 && __GNUC__ < 5 +# define HINT_INLINE static INLINE_KEYWORD +#else +# define HINT_INLINE static INLINE_KEYWORD FORCE_INLINE_ATTR +#endif + +/* UNUSED_ATTR tells the compiler it is okay if the function is unused. */ +#if defined(__GNUC__) +# define UNUSED_ATTR __attribute__((unused)) +#else +# define UNUSED_ATTR +#endif + +/* force no inlining */ +#ifdef _MSC_VER +# define FORCE_NOINLINE static __declspec(noinline) +#else +# if defined(__GNUC__) || defined(__ICCARM__) +# define FORCE_NOINLINE static __attribute__((__noinline__)) +# else +# define FORCE_NOINLINE static +# endif +#endif + +/* target attribute */ +#ifndef __has_attribute + #define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */ +#endif +#if defined(__GNUC__) || defined(__ICCARM__) +# define TARGET_ATTRIBUTE(target) __attribute__((__target__(target))) +#else +# define TARGET_ATTRIBUTE(target) +#endif + +/* Enable runtime BMI2 dispatch based on the CPU. + * Enabled for clang & gcc >=4.8 on x86 when BMI2 isn't enabled by default. + */ +#ifndef DYNAMIC_BMI2 + #if ((defined(__clang__) && __has_attribute(__target__)) \ + || (defined(__GNUC__) \ + && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))) \ + && (defined(__x86_64__) || defined(_M_X86)) \ + && !defined(__BMI2__) + # define DYNAMIC_BMI2 1 + #else + # define DYNAMIC_BMI2 0 + #endif +#endif + +/* prefetch + * can be disabled, by declaring NO_PREFETCH build macro */ +#if defined(NO_PREFETCH) +# define PREFETCH_L1(ptr) (void)(ptr) /* disabled */ +# define PREFETCH_L2(ptr) (void)(ptr) /* disabled */ +#else +# if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) /* _mm_prefetch() is not defined outside of x86/x64 */ +# include /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */ +# define PREFETCH_L1(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0) +# define PREFETCH_L2(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T1) +# elif defined(__aarch64__) +# define PREFETCH_L1(ptr) __asm__ __volatile__("prfm pldl1keep, %0" ::"Q"(*(ptr))) +# define PREFETCH_L2(ptr) __asm__ __volatile__("prfm pldl2keep, %0" ::"Q"(*(ptr))) +# elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) ) +# define PREFETCH_L1(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */) +# define PREFETCH_L2(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 2 /* locality */) +# else +# define PREFETCH_L1(ptr) (void)(ptr) /* disabled */ +# define PREFETCH_L2(ptr) (void)(ptr) /* disabled */ +# endif +#endif /* NO_PREFETCH */ + +#define CACHELINE_SIZE 64 + +#define PREFETCH_AREA(p, s) { \ + const char* const _ptr = (const char*)(p); \ + size_t const _size = (size_t)(s); \ + size_t _pos; \ + for (_pos=0; _pos<_size; _pos+=CACHELINE_SIZE) { \ + PREFETCH_L2(_ptr + _pos); \ + } \ +} + +/* vectorization + * older GCC (pre gcc-4.3 picked as the cutoff) uses a different syntax */ +#if !defined(__INTEL_COMPILER) && !defined(__clang__) && defined(__GNUC__) +# if (__GNUC__ == 4 && __GNUC_MINOR__ > 3) || (__GNUC__ >= 5) +# define DONT_VECTORIZE __attribute__((optimize("no-tree-vectorize"))) +# else +# define DONT_VECTORIZE _Pragma("GCC optimize(\"no-tree-vectorize\")") +# endif +#else +# define DONT_VECTORIZE +#endif + +/* Tell the compiler that a branch is likely or unlikely. + * Only use these macros if it causes the compiler to generate better code. + * If you can remove a LIKELY/UNLIKELY annotation without speed changes in gcc + * and clang, please do. + */ +#if defined(__GNUC__) +#define LIKELY(x) (__builtin_expect((x), 1)) +#define UNLIKELY(x) (__builtin_expect((x), 0)) +#else +#define LIKELY(x) (x) +#define UNLIKELY(x) (x) +#endif + +/* disable warnings */ +#ifdef _MSC_VER /* Visual Studio */ +# include /* For Visual 2005 */ +# pragma warning(disable : 4100) /* disable: C4100: unreferenced formal parameter */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +# pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */ +# pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */ +# pragma warning(disable : 4324) /* disable: C4324: padded structure */ +#endif + +#endif /* ZSTD_COMPILER_H */ +/**** ended inlining compiler.h ****/ +/**** skipping file: debug.h ****/ +/**** skipping file: error_private.h ****/ + + +/*========================================= +* Target specific +=========================================*/ +#if defined(__BMI__) && defined(__GNUC__) +# include /* support for bextr (experimental) */ +#elif defined(__ICCARM__) +# include +#endif + +#define STREAM_ACCUMULATOR_MIN_32 25 +#define STREAM_ACCUMULATOR_MIN_64 57 +#define STREAM_ACCUMULATOR_MIN ((U32)(MEM_32bits() ? STREAM_ACCUMULATOR_MIN_32 : STREAM_ACCUMULATOR_MIN_64)) + + +/*-****************************************** +* bitStream encoding API (write forward) +********************************************/ +/* bitStream can mix input from multiple sources. + * A critical property of these streams is that they encode and decode in **reverse** direction. + * So the first bit sequence you add will be the last to be read, like a LIFO stack. + */ +typedef struct { + size_t bitContainer; + unsigned bitPos; + char* startPtr; + char* ptr; + char* endPtr; +} BIT_CStream_t; + +MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, void* dstBuffer, size_t dstCapacity); +MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, size_t value, unsigned nbBits); +MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC); +MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC); + +/* Start with initCStream, providing the size of buffer to write into. +* bitStream will never write outside of this buffer. +* `dstCapacity` must be >= sizeof(bitD->bitContainer), otherwise @return will be an error code. +* +* bits are first added to a local register. +* Local register is size_t, hence 64-bits on 64-bits systems, or 32-bits on 32-bits systems. +* Writing data into memory is an explicit operation, performed by the flushBits function. +* Hence keep track how many bits are potentially stored into local register to avoid register overflow. +* After a flushBits, a maximum of 7 bits might still be stored into local register. +* +* Avoid storing elements of more than 24 bits if you want compatibility with 32-bits bitstream readers. +* +* Last operation is to close the bitStream. +* The function returns the final size of CStream in bytes. +* If data couldn't fit into `dstBuffer`, it will return a 0 ( == not storable) +*/ + + +/*-******************************************** +* bitStream decoding API (read backward) +**********************************************/ +typedef struct { + size_t bitContainer; + unsigned bitsConsumed; + const char* ptr; + const char* start; + const char* limitPtr; +} BIT_DStream_t; + +typedef enum { BIT_DStream_unfinished = 0, + BIT_DStream_endOfBuffer = 1, + BIT_DStream_completed = 2, + BIT_DStream_overflow = 3 } BIT_DStream_status; /* result of BIT_reloadDStream() */ + /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */ + +MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize); +MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits); +MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD); +MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD); + + +/* Start by invoking BIT_initDStream(). +* A chunk of the bitStream is then stored into a local register. +* Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t). +* You can then retrieve bitFields stored into the local register, **in reverse order**. +* Local register is explicitly reloaded from memory by the BIT_reloadDStream() method. +* A reload guarantee a minimum of ((8*sizeof(bitD->bitContainer))-7) bits when its result is BIT_DStream_unfinished. +* Otherwise, it can be less than that, so proceed accordingly. +* Checking if DStream has reached its end can be performed with BIT_endOfDStream(). +*/ + + +/*-**************************************** +* unsafe API +******************************************/ +MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, size_t value, unsigned nbBits); +/* faster, but works only if value is "clean", meaning all high bits above nbBits are 0 */ + +MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC); +/* unsafe version; does not check buffer overflow */ + +MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits); +/* faster, but works only if nbBits >= 1 */ + + + +/*-************************************************************** +* Internal functions +****************************************************************/ +MEM_STATIC unsigned BIT_highbit32 (U32 val) +{ + assert(val != 0); + { +# if defined(_MSC_VER) /* Visual */ + unsigned long r=0; + return _BitScanReverse ( &r, val ) ? (unsigned)r : 0; +# elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */ + return __builtin_clz (val) ^ 31; +# elif defined(__ICCARM__) /* IAR Intrinsic */ + return 31 - __CLZ(val); +# else /* Software version */ + static const unsigned DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, + 11, 14, 16, 18, 22, 25, 3, 30, + 8, 12, 20, 28, 15, 17, 24, 7, + 19, 27, 23, 6, 26, 5, 4, 31 }; + U32 v = val; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + return DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27]; +# endif + } +} + +/*===== Local Constants =====*/ +static const unsigned BIT_mask[] = { + 0, 1, 3, 7, 0xF, 0x1F, + 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, + 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0x1FFFF, + 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF, + 0xFFFFFF, 0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF, + 0x3FFFFFFF, 0x7FFFFFFF}; /* up to 31 bits */ +#define BIT_MASK_SIZE (sizeof(BIT_mask) / sizeof(BIT_mask[0])) + +/*-************************************************************** +* bitStream encoding +****************************************************************/ +/*! BIT_initCStream() : + * `dstCapacity` must be > sizeof(size_t) + * @return : 0 if success, + * otherwise an error code (can be tested using ERR_isError()) */ +MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, + void* startPtr, size_t dstCapacity) +{ + bitC->bitContainer = 0; + bitC->bitPos = 0; + bitC->startPtr = (char*)startPtr; + bitC->ptr = bitC->startPtr; + bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer); + if (dstCapacity <= sizeof(bitC->bitContainer)) return ERROR(dstSize_tooSmall); + return 0; +} + +/*! BIT_addBits() : + * can add up to 31 bits into `bitC`. + * Note : does not check for register overflow ! */ +MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, + size_t value, unsigned nbBits) +{ + MEM_STATIC_ASSERT(BIT_MASK_SIZE == 32); + assert(nbBits < BIT_MASK_SIZE); + assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8); + bitC->bitContainer |= (value & BIT_mask[nbBits]) << bitC->bitPos; + bitC->bitPos += nbBits; +} + +/*! BIT_addBitsFast() : + * works only if `value` is _clean_, + * meaning all high bits above nbBits are 0 */ +MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, + size_t value, unsigned nbBits) +{ + assert((value>>nbBits) == 0); + assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8); + bitC->bitContainer |= value << bitC->bitPos; + bitC->bitPos += nbBits; +} + +/*! BIT_flushBitsFast() : + * assumption : bitContainer has not overflowed + * unsafe version; does not check buffer overflow */ +MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC) +{ + size_t const nbBytes = bitC->bitPos >> 3; + assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8); + assert(bitC->ptr <= bitC->endPtr); + MEM_writeLEST(bitC->ptr, bitC->bitContainer); + bitC->ptr += nbBytes; + bitC->bitPos &= 7; + bitC->bitContainer >>= nbBytes*8; +} + +/*! BIT_flushBits() : + * assumption : bitContainer has not overflowed + * safe version; check for buffer overflow, and prevents it. + * note : does not signal buffer overflow. + * overflow will be revealed later on using BIT_closeCStream() */ +MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC) +{ + size_t const nbBytes = bitC->bitPos >> 3; + assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8); + assert(bitC->ptr <= bitC->endPtr); + MEM_writeLEST(bitC->ptr, bitC->bitContainer); + bitC->ptr += nbBytes; + if (bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr; + bitC->bitPos &= 7; + bitC->bitContainer >>= nbBytes*8; +} + +/*! BIT_closeCStream() : + * @return : size of CStream, in bytes, + * or 0 if it could not fit into dstBuffer */ +MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC) +{ + BIT_addBitsFast(bitC, 1, 1); /* endMark */ + BIT_flushBits(bitC); + if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */ + return (bitC->ptr - bitC->startPtr) + (bitC->bitPos > 0); +} + + +/*-******************************************************** +* bitStream decoding +**********************************************************/ +/*! BIT_initDStream() : + * Initialize a BIT_DStream_t. + * `bitD` : a pointer to an already allocated BIT_DStream_t structure. + * `srcSize` must be the *exact* size of the bitStream, in bytes. + * @return : size of stream (== srcSize), or an errorCode if a problem is detected + */ +MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize) +{ + if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); } + + bitD->start = (const char*)srcBuffer; + bitD->limitPtr = bitD->start + sizeof(bitD->bitContainer); + + if (srcSize >= sizeof(bitD->bitContainer)) { /* normal case */ + bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(bitD->bitContainer); + bitD->bitContainer = MEM_readLEST(bitD->ptr); + { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1]; + bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0; /* ensures bitsConsumed is always set */ + if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ } + } else { + bitD->ptr = bitD->start; + bitD->bitContainer = *(const BYTE*)(bitD->start); + switch(srcSize) + { + case 7: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16); + /* fall-through */ + + case 6: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24); + /* fall-through */ + + case 5: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32); + /* fall-through */ + + case 4: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[3]) << 24; + /* fall-through */ + + case 3: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[2]) << 16; + /* fall-through */ + + case 2: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[1]) << 8; + /* fall-through */ + + default: break; + } + { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1]; + bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0; + if (lastByte == 0) return ERROR(corruption_detected); /* endMark not present */ + } + bitD->bitsConsumed += (U32)(sizeof(bitD->bitContainer) - srcSize)*8; + } + + return srcSize; +} + +MEM_STATIC size_t BIT_getUpperBits(size_t bitContainer, U32 const start) +{ + return bitContainer >> start; +} + +MEM_STATIC size_t BIT_getMiddleBits(size_t bitContainer, U32 const start, U32 const nbBits) +{ + U32 const regMask = sizeof(bitContainer)*8 - 1; + /* if start > regMask, bitstream is corrupted, and result is undefined */ + assert(nbBits < BIT_MASK_SIZE); + return (bitContainer >> (start & regMask)) & BIT_mask[nbBits]; +} + +MEM_STATIC size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits) +{ + assert(nbBits < BIT_MASK_SIZE); + return bitContainer & BIT_mask[nbBits]; +} + +/*! BIT_lookBits() : + * Provides next n bits from local register. + * local register is not modified. + * On 32-bits, maxNbBits==24. + * On 64-bits, maxNbBits==56. + * @return : value extracted */ +MEM_STATIC size_t BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits) +{ + /* arbitrate between double-shift and shift+mask */ +#if 1 + /* if bitD->bitsConsumed + nbBits > sizeof(bitD->bitContainer)*8, + * bitstream is likely corrupted, and result is undefined */ + return BIT_getMiddleBits(bitD->bitContainer, (sizeof(bitD->bitContainer)*8) - bitD->bitsConsumed - nbBits, nbBits); +#else + /* this code path is slower on my os-x laptop */ + U32 const regMask = sizeof(bitD->bitContainer)*8 - 1; + return ((bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> 1) >> ((regMask-nbBits) & regMask); +#endif +} + +/*! BIT_lookBitsFast() : + * unsafe version; only works if nbBits >= 1 */ +MEM_STATIC size_t BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits) +{ + U32 const regMask = sizeof(bitD->bitContainer)*8 - 1; + assert(nbBits >= 1); + return (bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> (((regMask+1)-nbBits) & regMask); +} + +MEM_STATIC void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits) +{ + bitD->bitsConsumed += nbBits; +} + +/*! BIT_readBits() : + * Read (consume) next n bits from local register and update. + * Pay attention to not read more than nbBits contained into local register. + * @return : extracted value. */ +MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits) +{ + size_t const value = BIT_lookBits(bitD, nbBits); + BIT_skipBits(bitD, nbBits); + return value; +} + +/*! BIT_readBitsFast() : + * unsafe version; only works only if nbBits >= 1 */ +MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits) +{ + size_t const value = BIT_lookBitsFast(bitD, nbBits); + assert(nbBits >= 1); + BIT_skipBits(bitD, nbBits); + return value; +} + +/*! BIT_reloadDStreamFast() : + * Similar to BIT_reloadDStream(), but with two differences: + * 1. bitsConsumed <= sizeof(bitD->bitContainer)*8 must hold! + * 2. Returns BIT_DStream_overflow when bitD->ptr < bitD->limitPtr, at this + * point you must use BIT_reloadDStream() to reload. + */ +MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t* bitD) +{ + if (UNLIKELY(bitD->ptr < bitD->limitPtr)) + return BIT_DStream_overflow; + assert(bitD->bitsConsumed <= sizeof(bitD->bitContainer)*8); + bitD->ptr -= bitD->bitsConsumed >> 3; + bitD->bitsConsumed &= 7; + bitD->bitContainer = MEM_readLEST(bitD->ptr); + return BIT_DStream_unfinished; +} + +/*! BIT_reloadDStream() : + * Refill `bitD` from buffer previously set in BIT_initDStream() . + * This function is safe, it guarantees it will not read beyond src buffer. + * @return : status of `BIT_DStream_t` internal register. + * when status == BIT_DStream_unfinished, internal register is filled with at least 25 or 57 bits */ +MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD) +{ + if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* overflow detected, like end of stream */ + return BIT_DStream_overflow; + + if (bitD->ptr >= bitD->limitPtr) { + return BIT_reloadDStreamFast(bitD); + } + if (bitD->ptr == bitD->start) { + if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer; + return BIT_DStream_completed; + } + /* start < ptr < limitPtr */ + { U32 nbBytes = bitD->bitsConsumed >> 3; + BIT_DStream_status result = BIT_DStream_unfinished; + if (bitD->ptr - nbBytes < bitD->start) { + nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */ + result = BIT_DStream_endOfBuffer; + } + bitD->ptr -= nbBytes; + bitD->bitsConsumed -= nbBytes*8; + bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD->bitContainer), otherwise bitD->ptr == bitD->start */ + return result; + } +} + +/*! BIT_endOfDStream() : + * @return : 1 if DStream has _exactly_ reached its end (all bits consumed). + */ +MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream) +{ + return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8)); +} + +#if defined (__cplusplus) +} +#endif + +#endif /* BITSTREAM_H_MODULE */ +/**** ended inlining bitstream.h ****/ + + +/* ***************************************** +* Static allocation +*******************************************/ +/* FSE buffer bounds */ +#define FSE_NCOUNTBOUND 512 +#define FSE_BLOCKBOUND(size) (size + (size>>7) + 4 /* fse states */ + sizeof(size_t) /* bitContainer */) +#define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size)) /* Macro version, useful for static allocation */ + +/* It is possible to statically allocate FSE CTable/DTable as a table of FSE_CTable/FSE_DTable using below macros */ +#define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) (1 + (1<<(maxTableLog-1)) + ((maxSymbolValue+1)*2)) +#define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1< 12) ? (1 << (maxTableLog - 2)) : 1024) ) +size_t FSE_compress_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize); + +size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits); +/**< build a fake FSE_CTable, designed for a flat distribution, where each symbol uses nbBits */ + +size_t FSE_buildCTable_rle (FSE_CTable* ct, unsigned char symbolValue); +/**< build a fake FSE_CTable, designed to compress always the same symbolValue */ + +/* FSE_buildCTable_wksp() : + * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`). + * `wkspSize` must be >= `(1<= BIT_DStream_completed + +When it's done, verify decompression is fully completed, by checking both DStream and the relevant states. +Checking if DStream has reached its end is performed by : + BIT_endOfDStream(&DStream); +Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible. + FSE_endOfDState(&DState); +*/ + + +/* ***************************************** +* FSE unsafe API +*******************************************/ +static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD); +/* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */ + + +/* ***************************************** +* Implementation of inlined functions +*******************************************/ +typedef struct { + int deltaFindState; + U32 deltaNbBits; +} FSE_symbolCompressionTransform; /* total 8 bytes */ + +MEM_STATIC void FSE_initCState(FSE_CState_t* statePtr, const FSE_CTable* ct) +{ + const void* ptr = ct; + const U16* u16ptr = (const U16*) ptr; + const U32 tableLog = MEM_read16(ptr); + statePtr->value = (ptrdiff_t)1<stateTable = u16ptr+2; + statePtr->symbolTT = ct + 1 + (tableLog ? (1<<(tableLog-1)) : 1); + statePtr->stateLog = tableLog; +} + + +/*! FSE_initCState2() : +* Same as FSE_initCState(), but the first symbol to include (which will be the last to be read) +* uses the smallest state value possible, saving the cost of this symbol */ +MEM_STATIC void FSE_initCState2(FSE_CState_t* statePtr, const FSE_CTable* ct, U32 symbol) +{ + FSE_initCState(statePtr, ct); + { const FSE_symbolCompressionTransform symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol]; + const U16* stateTable = (const U16*)(statePtr->stateTable); + U32 nbBitsOut = (U32)((symbolTT.deltaNbBits + (1<<15)) >> 16); + statePtr->value = (nbBitsOut << 16) - symbolTT.deltaNbBits; + statePtr->value = stateTable[(statePtr->value >> nbBitsOut) + symbolTT.deltaFindState]; + } +} + +MEM_STATIC void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* statePtr, unsigned symbol) +{ + FSE_symbolCompressionTransform const symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol]; + const U16* const stateTable = (const U16*)(statePtr->stateTable); + U32 const nbBitsOut = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16); + BIT_addBits(bitC, statePtr->value, nbBitsOut); + statePtr->value = stateTable[ (statePtr->value >> nbBitsOut) + symbolTT.deltaFindState]; +} + +MEM_STATIC void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* statePtr) +{ + BIT_addBits(bitC, statePtr->value, statePtr->stateLog); + BIT_flushBits(bitC); +} + + +/* FSE_getMaxNbBits() : + * Approximate maximum cost of a symbol, in bits. + * Fractional get rounded up (i.e : a symbol with a normalized frequency of 3 gives the same result as a frequency of 2) + * note 1 : assume symbolValue is valid (<= maxSymbolValue) + * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */ +MEM_STATIC U32 FSE_getMaxNbBits(const void* symbolTTPtr, U32 symbolValue) +{ + const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr; + return (symbolTT[symbolValue].deltaNbBits + ((1<<16)-1)) >> 16; +} + +/* FSE_bitCost() : + * Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits) + * note 1 : assume symbolValue is valid (<= maxSymbolValue) + * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */ +MEM_STATIC U32 FSE_bitCost(const void* symbolTTPtr, U32 tableLog, U32 symbolValue, U32 accuracyLog) +{ + const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr; + U32 const minNbBits = symbolTT[symbolValue].deltaNbBits >> 16; + U32 const threshold = (minNbBits+1) << 16; + assert(tableLog < 16); + assert(accuracyLog < 31-tableLog); /* ensure enough room for renormalization double shift */ + { U32 const tableSize = 1 << tableLog; + U32 const deltaFromThreshold = threshold - (symbolTT[symbolValue].deltaNbBits + tableSize); + U32 const normalizedDeltaFromThreshold = (deltaFromThreshold << accuracyLog) >> tableLog; /* linear interpolation (very approximate) */ + U32 const bitMultiplier = 1 << accuracyLog; + assert(symbolTT[symbolValue].deltaNbBits + tableSize <= threshold); + assert(normalizedDeltaFromThreshold <= bitMultiplier); + return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold; + } +} + + +/* ====== Decompression ====== */ + +typedef struct { + U16 tableLog; + U16 fastMode; +} FSE_DTableHeader; /* sizeof U32 */ + +typedef struct +{ + unsigned short newState; + unsigned char symbol; + unsigned char nbBits; +} FSE_decode_t; /* size == U32 */ + +MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt) +{ + const void* ptr = dt; + const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)ptr; + DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog); + BIT_reloadDStream(bitD); + DStatePtr->table = dt + 1; +} + +MEM_STATIC BYTE FSE_peekSymbol(const FSE_DState_t* DStatePtr) +{ + FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + return DInfo.symbol; +} + +MEM_STATIC void FSE_updateState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD) +{ + FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + U32 const nbBits = DInfo.nbBits; + size_t const lowBits = BIT_readBits(bitD, nbBits); + DStatePtr->state = DInfo.newState + lowBits; +} + +MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD) +{ + FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + U32 const nbBits = DInfo.nbBits; + BYTE const symbol = DInfo.symbol; + size_t const lowBits = BIT_readBits(bitD, nbBits); + + DStatePtr->state = DInfo.newState + lowBits; + return symbol; +} + +/*! FSE_decodeSymbolFast() : + unsafe, only works if no symbol has a probability > 50% */ +MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD) +{ + FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + U32 const nbBits = DInfo.nbBits; + BYTE const symbol = DInfo.symbol; + size_t const lowBits = BIT_readBitsFast(bitD, nbBits); + + DStatePtr->state = DInfo.newState + lowBits; + return symbol; +} + +MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr) +{ + return DStatePtr->state == 0; +} + + + +#ifndef FSE_COMMONDEFS_ONLY + +/* ************************************************************** +* Tuning parameters +****************************************************************/ +/*!MEMORY_USAGE : +* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) +* Increasing memory usage improves compression ratio +* Reduced memory usage can improve speed, due to cache effect +* Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ +#ifndef FSE_MAX_MEMORY_USAGE +# define FSE_MAX_MEMORY_USAGE 14 +#endif +#ifndef FSE_DEFAULT_MEMORY_USAGE +# define FSE_DEFAULT_MEMORY_USAGE 13 +#endif + +/*!FSE_MAX_SYMBOL_VALUE : +* Maximum symbol value authorized. +* Required for proper stack allocation */ +#ifndef FSE_MAX_SYMBOL_VALUE +# define FSE_MAX_SYMBOL_VALUE 255 +#endif + +/* ************************************************************** +* template functions type & suffix +****************************************************************/ +#define FSE_FUNCTION_TYPE BYTE +#define FSE_FUNCTION_EXTENSION +#define FSE_DECODE_TYPE FSE_decode_t + + +#endif /* !FSE_COMMONDEFS_ONLY */ + + +/* *************************************************************** +* Constants +*****************************************************************/ +#define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2) +#define FSE_MAX_TABLESIZE (1U< FSE_TABLELOG_ABSOLUTE_MAX +# error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported" +#endif + +#define FSE_TABLESTEP(tableSize) ((tableSize>>1) + (tableSize>>3) + 3) + + +#endif /* FSE_STATIC_LINKING_ONLY */ + + +#if defined (__cplusplus) +} +#endif +/**** ended inlining fse.h ****/ +#define HUF_STATIC_LINKING_ONLY /* HUF_TABLELOG_ABSOLUTEMAX */ +/**** start inlining huf.h ****/ +/* ****************************************************************** + * huff0 huffman codec, + * part of Finite State Entropy library + * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + +#if defined (__cplusplus) +extern "C" { +#endif + +#ifndef HUF_H_298734234 +#define HUF_H_298734234 + +/* *** Dependencies *** */ +#include /* size_t */ + + +/* *** library symbols visibility *** */ +/* Note : when linking with -fvisibility=hidden on gcc, or by default on Visual, + * HUF symbols remain "private" (internal symbols for library only). + * Set macro FSE_DLL_EXPORT to 1 if you want HUF symbols visible on DLL interface */ +#if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4) +# define HUF_PUBLIC_API __attribute__ ((visibility ("default"))) +#elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) /* Visual expected */ +# define HUF_PUBLIC_API __declspec(dllexport) +#elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1) +# define HUF_PUBLIC_API __declspec(dllimport) /* not required, just to generate faster code (saves a function pointer load from IAT and an indirect jump) */ +#else +# define HUF_PUBLIC_API +#endif + + +/* ========================== */ +/* *** simple functions *** */ +/* ========================== */ + +/** HUF_compress() : + * Compress content from buffer 'src', of size 'srcSize', into buffer 'dst'. + * 'dst' buffer must be already allocated. + * Compression runs faster if `dstCapacity` >= HUF_compressBound(srcSize). + * `srcSize` must be <= `HUF_BLOCKSIZE_MAX` == 128 KB. + * @return : size of compressed data (<= `dstCapacity`). + * Special values : if return == 0, srcData is not compressible => Nothing is stored within dst !!! + * if HUF_isError(return), compression failed (more details using HUF_getErrorName()) + */ +HUF_PUBLIC_API size_t HUF_compress(void* dst, size_t dstCapacity, + const void* src, size_t srcSize); + +/** HUF_decompress() : + * Decompress HUF data from buffer 'cSrc', of size 'cSrcSize', + * into already allocated buffer 'dst', of minimum size 'dstSize'. + * `originalSize` : **must** be the ***exact*** size of original (uncompressed) data. + * Note : in contrast with FSE, HUF_decompress can regenerate + * RLE (cSrcSize==1) and uncompressed (cSrcSize==dstSize) data, + * because it knows size to regenerate (originalSize). + * @return : size of regenerated data (== originalSize), + * or an error code, which can be tested using HUF_isError() + */ +HUF_PUBLIC_API size_t HUF_decompress(void* dst, size_t originalSize, + const void* cSrc, size_t cSrcSize); + + +/* *** Tool functions *** */ +#define HUF_BLOCKSIZE_MAX (128 * 1024) /**< maximum input size for a single block compressed with HUF_compress */ +HUF_PUBLIC_API size_t HUF_compressBound(size_t size); /**< maximum compressed size (worst case) */ + +/* Error Management */ +HUF_PUBLIC_API unsigned HUF_isError(size_t code); /**< tells if a return value is an error code */ +HUF_PUBLIC_API const char* HUF_getErrorName(size_t code); /**< provides error code string (useful for debugging) */ + + +/* *** Advanced function *** */ + +/** HUF_compress2() : + * Same as HUF_compress(), but offers control over `maxSymbolValue` and `tableLog`. + * `maxSymbolValue` must be <= HUF_SYMBOLVALUE_MAX . + * `tableLog` must be `<= HUF_TABLELOG_MAX` . */ +HUF_PUBLIC_API size_t HUF_compress2 (void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + unsigned maxSymbolValue, unsigned tableLog); + +/** HUF_compress4X_wksp() : + * Same as HUF_compress2(), but uses externally allocated `workSpace`. + * `workspace` must have minimum alignment of 4, and be at least as large as HUF_WORKSPACE_SIZE */ +#define HUF_WORKSPACE_SIZE ((6 << 10) + 256) +#define HUF_WORKSPACE_SIZE_U32 (HUF_WORKSPACE_SIZE / sizeof(U32)) +HUF_PUBLIC_API size_t HUF_compress4X_wksp (void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + unsigned maxSymbolValue, unsigned tableLog, + void* workSpace, size_t wkspSize); + +#endif /* HUF_H_298734234 */ + +/* ****************************************************************** + * WARNING !! + * The following section contains advanced and experimental definitions + * which shall never be used in the context of a dynamic library, + * because they are not guaranteed to remain stable in the future. + * Only consider them in association with static linking. + * *****************************************************************/ +#if defined(HUF_STATIC_LINKING_ONLY) && !defined(HUF_H_HUF_STATIC_LINKING_ONLY) +#define HUF_H_HUF_STATIC_LINKING_ONLY + +/* *** Dependencies *** */ +/**** skipping file: mem.h ****/ + + +/* *** Constants *** */ +#define HUF_TABLELOG_MAX 12 /* max runtime value of tableLog (due to static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */ +#define HUF_TABLELOG_DEFAULT 11 /* default tableLog value when none specified */ +#define HUF_SYMBOLVALUE_MAX 255 + +#define HUF_TABLELOG_ABSOLUTEMAX 15 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */ +#if (HUF_TABLELOG_MAX > HUF_TABLELOG_ABSOLUTEMAX) +# error "HUF_TABLELOG_MAX is too large !" +#endif + + +/* **************************************** +* Static allocation +******************************************/ +/* HUF buffer bounds */ +#define HUF_CTABLEBOUND 129 +#define HUF_BLOCKBOUND(size) (size + (size>>8) + 8) /* only true when incompressible is pre-filtered with fast heuristic */ +#define HUF_COMPRESSBOUND(size) (HUF_CTABLEBOUND + HUF_BLOCKBOUND(size)) /* Macro version, useful for static allocation */ + +/* static allocation of HUF's Compression Table */ +#define HUF_CTABLE_SIZE_U32(maxSymbolValue) ((maxSymbolValue)+1) /* Use tables of U32, for proper alignment */ +#define HUF_CTABLE_SIZE(maxSymbolValue) (HUF_CTABLE_SIZE_U32(maxSymbolValue) * sizeof(U32)) +#define HUF_CREATE_STATIC_CTABLE(name, maxSymbolValue) \ + U32 name##hb[HUF_CTABLE_SIZE_U32(maxSymbolValue)]; \ + void* name##hv = &(name##hb); \ + HUF_CElt* name = (HUF_CElt*)(name##hv) /* no final ; */ + +/* static allocation of HUF's DTable */ +typedef U32 HUF_DTable; +#define HUF_DTABLE_SIZE(maxTableLog) (1 + (1<<(maxTableLog))) +#define HUF_CREATE_STATIC_DTABLEX1(DTable, maxTableLog) \ + HUF_DTable DTable[HUF_DTABLE_SIZE((maxTableLog)-1)] = { ((U32)((maxTableLog)-1) * 0x01000001) } +#define HUF_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \ + HUF_DTable DTable[HUF_DTABLE_SIZE(maxTableLog)] = { ((U32)(maxTableLog) * 0x01000001) } + + +/* **************************************** +* Advanced decompression functions +******************************************/ +size_t HUF_decompress4X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< single-symbol decoder */ +#ifndef HUF_FORCE_DECOMPRESS_X1 +size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< double-symbols decoder */ +#endif + +size_t HUF_decompress4X_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< decodes RLE and uncompressed */ +size_t HUF_decompress4X_hufOnly(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< considers RLE and uncompressed as errors */ +size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< considers RLE and uncompressed as errors */ +size_t HUF_decompress4X1_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< single-symbol decoder */ +size_t HUF_decompress4X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< single-symbol decoder */ +#ifndef HUF_FORCE_DECOMPRESS_X1 +size_t HUF_decompress4X2_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< double-symbols decoder */ +size_t HUF_decompress4X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< double-symbols decoder */ +#endif + + +/* **************************************** + * HUF detailed API + * ****************************************/ + +/*! HUF_compress() does the following: + * 1. count symbol occurrence from source[] into table count[] using FSE_count() (exposed within "fse.h") + * 2. (optional) refine tableLog using HUF_optimalTableLog() + * 3. build Huffman table from count using HUF_buildCTable() + * 4. save Huffman table to memory buffer using HUF_writeCTable() + * 5. encode the data stream using HUF_compress4X_usingCTable() + * + * The following API allows targeting specific sub-functions for advanced tasks. + * For example, it's possible to compress several blocks using the same 'CTable', + * or to save and regenerate 'CTable' using external methods. + */ +unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue); +typedef struct HUF_CElt_s HUF_CElt; /* incomplete type */ +size_t HUF_buildCTable (HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue, unsigned maxNbBits); /* @return : maxNbBits; CTable and count can overlap. In which case, CTable will overwrite count content */ +size_t HUF_writeCTable (void* dst, size_t maxDstSize, const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog); +size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable); +size_t HUF_estimateCompressedSize(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue); +int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue); + +typedef enum { + HUF_repeat_none, /**< Cannot use the previous table */ + HUF_repeat_check, /**< Can use the previous table but it must be checked. Note : The previous table must have been constructed by HUF_compress{1, 4}X_repeat */ + HUF_repeat_valid /**< Can use the previous table and it is assumed to be valid */ + } HUF_repeat; +/** HUF_compress4X_repeat() : + * Same as HUF_compress4X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none. + * If it uses hufTable it does not modify hufTable or repeat. + * If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used. + * If preferRepeat then the old table will always be used if valid. */ +size_t HUF_compress4X_repeat(void* dst, size_t dstSize, + const void* src, size_t srcSize, + unsigned maxSymbolValue, unsigned tableLog, + void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */ + HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2); + +/** HUF_buildCTable_wksp() : + * Same as HUF_buildCTable(), but using externally allocated scratch buffer. + * `workSpace` must be aligned on 4-bytes boundaries, and its size must be >= HUF_CTABLE_WORKSPACE_SIZE. + */ +#define HUF_CTABLE_WORKSPACE_SIZE_U32 (2*HUF_SYMBOLVALUE_MAX +1 +1) +#define HUF_CTABLE_WORKSPACE_SIZE (HUF_CTABLE_WORKSPACE_SIZE_U32 * sizeof(unsigned)) +size_t HUF_buildCTable_wksp (HUF_CElt* tree, + const unsigned* count, U32 maxSymbolValue, U32 maxNbBits, + void* workSpace, size_t wkspSize); + +/*! HUF_readStats() : + * Read compact Huffman tree, saved by HUF_writeCTable(). + * `huffWeight` is destination buffer. + * @return : size read from `src` , or an error Code . + * Note : Needed by HUF_readCTable() and HUF_readDTableXn() . */ +size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, + U32* rankStats, U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize); + +/** HUF_readCTable() : + * Loading a CTable saved with HUF_writeCTable() */ +size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize, unsigned *hasZeroWeights); + +/** HUF_getNbBits() : + * Read nbBits from CTable symbolTable, for symbol `symbolValue` presumed <= HUF_SYMBOLVALUE_MAX + * Note 1 : is not inlined, as HUF_CElt definition is private + * Note 2 : const void* used, so that it can provide a statically allocated table as argument (which uses type U32) */ +U32 HUF_getNbBits(const void* symbolTable, U32 symbolValue); + +/* + * HUF_decompress() does the following: + * 1. select the decompression algorithm (X1, X2) based on pre-computed heuristics + * 2. build Huffman table from save, using HUF_readDTableX?() + * 3. decode 1 or 4 segments in parallel using HUF_decompress?X?_usingDTable() + */ + +/** HUF_selectDecoder() : + * Tells which decoder is likely to decode faster, + * based on a set of pre-computed metrics. + * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 . + * Assumption : 0 < dstSize <= 128 KB */ +U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize); + +/** + * The minimum workspace size for the `workSpace` used in + * HUF_readDTableX1_wksp() and HUF_readDTableX2_wksp(). + * + * The space used depends on HUF_TABLELOG_MAX, ranging from ~1500 bytes when + * HUF_TABLE_LOG_MAX=12 to ~1850 bytes when HUF_TABLE_LOG_MAX=15. + * Buffer overflow errors may potentially occur if code modifications result in + * a required workspace size greater than that specified in the following + * macro. + */ +#define HUF_DECOMPRESS_WORKSPACE_SIZE (2 << 10) +#define HUF_DECOMPRESS_WORKSPACE_SIZE_U32 (HUF_DECOMPRESS_WORKSPACE_SIZE / sizeof(U32)) + +#ifndef HUF_FORCE_DECOMPRESS_X2 +size_t HUF_readDTableX1 (HUF_DTable* DTable, const void* src, size_t srcSize); +size_t HUF_readDTableX1_wksp (HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize); +#endif +#ifndef HUF_FORCE_DECOMPRESS_X1 +size_t HUF_readDTableX2 (HUF_DTable* DTable, const void* src, size_t srcSize); +size_t HUF_readDTableX2_wksp (HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize); +#endif + +size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable); +#ifndef HUF_FORCE_DECOMPRESS_X2 +size_t HUF_decompress4X1_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable); +#endif +#ifndef HUF_FORCE_DECOMPRESS_X1 +size_t HUF_decompress4X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable); +#endif + + +/* ====================== */ +/* single stream variants */ +/* ====================== */ + +size_t HUF_compress1X (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog); +size_t HUF_compress1X_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize); /**< `workSpace` must be a table of at least HUF_WORKSPACE_SIZE_U32 unsigned */ +size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable); +/** HUF_compress1X_repeat() : + * Same as HUF_compress1X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none. + * If it uses hufTable it does not modify hufTable or repeat. + * If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used. + * If preferRepeat then the old table will always be used if valid. */ +size_t HUF_compress1X_repeat(void* dst, size_t dstSize, + const void* src, size_t srcSize, + unsigned maxSymbolValue, unsigned tableLog, + void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */ + HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2); + +size_t HUF_decompress1X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* single-symbol decoder */ +#ifndef HUF_FORCE_DECOMPRESS_X1 +size_t HUF_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* double-symbol decoder */ +#endif + +size_t HUF_decompress1X_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); +size_t HUF_decompress1X_DCtx_wksp (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); +#ifndef HUF_FORCE_DECOMPRESS_X2 +size_t HUF_decompress1X1_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< single-symbol decoder */ +size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< single-symbol decoder */ +#endif +#ifndef HUF_FORCE_DECOMPRESS_X1 +size_t HUF_decompress1X2_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< double-symbols decoder */ +size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< double-symbols decoder */ +#endif + +size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable); /**< automatic selection of sing or double symbol decoder, based on DTable */ +#ifndef HUF_FORCE_DECOMPRESS_X2 +size_t HUF_decompress1X1_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable); +#endif +#ifndef HUF_FORCE_DECOMPRESS_X1 +size_t HUF_decompress1X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable); +#endif + +/* BMI2 variants. + * If the CPU has BMI2 support, pass bmi2=1, otherwise pass bmi2=0. + */ +size_t HUF_decompress1X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2); +#ifndef HUF_FORCE_DECOMPRESS_X2 +size_t HUF_decompress1X1_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2); +#endif +size_t HUF_decompress4X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2); +size_t HUF_decompress4X_hufOnly_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2); + +#endif /* HUF_STATIC_LINKING_ONLY */ + +#if defined (__cplusplus) +} +#endif +/**** ended inlining huf.h ****/ + + +/*=== Version ===*/ +unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; } + + +/*=== Error Management ===*/ +unsigned FSE_isError(size_t code) { return ERR_isError(code); } +const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); } + +unsigned HUF_isError(size_t code) { return ERR_isError(code); } +const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); } + + +/*-************************************************************** +* FSE NCount encoding-decoding +****************************************************************/ +size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, + const void* headerBuffer, size_t hbSize) +{ + const BYTE* const istart = (const BYTE*) headerBuffer; + const BYTE* const iend = istart + hbSize; + const BYTE* ip = istart; + int nbBits; + int remaining; + int threshold; + U32 bitStream; + int bitCount; + unsigned charnum = 0; + int previous0 = 0; + + if (hbSize < 4) { + /* This function only works when hbSize >= 4 */ + char buffer[4]; + memset(buffer, 0, sizeof(buffer)); + memcpy(buffer, headerBuffer, hbSize); + { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr, + buffer, sizeof(buffer)); + if (FSE_isError(countSize)) return countSize; + if (countSize > hbSize) return ERROR(corruption_detected); + return countSize; + } } + assert(hbSize >= 4); + + /* init */ + memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */ + bitStream = MEM_readLE32(ip); + nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */ + if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge); + bitStream >>= 4; + bitCount = 4; + *tableLogPtr = nbBits; + remaining = (1<1) & (charnum<=*maxSVPtr)) { + if (previous0) { + unsigned n0 = charnum; + while ((bitStream & 0xFFFF) == 0xFFFF) { + n0 += 24; + if (ip < iend-5) { + ip += 2; + bitStream = MEM_readLE32(ip) >> bitCount; + } else { + bitStream >>= 16; + bitCount += 16; + } } + while ((bitStream & 3) == 3) { + n0 += 3; + bitStream >>= 2; + bitCount += 2; + } + n0 += bitStream & 3; + bitCount += 2; + if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall); + while (charnum < n0) normalizedCounter[charnum++] = 0; + if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) { + assert((bitCount >> 3) <= 3); /* For first condition to work */ + ip += bitCount>>3; + bitCount &= 7; + bitStream = MEM_readLE32(ip) >> bitCount; + } else { + bitStream >>= 2; + } } + { int const max = (2*threshold-1) - remaining; + int count; + + if ((bitStream & (threshold-1)) < (U32)max) { + count = bitStream & (threshold-1); + bitCount += nbBits-1; + } else { + count = bitStream & (2*threshold-1); + if (count >= threshold) count -= max; + bitCount += nbBits; + } + + count--; /* extra accuracy */ + remaining -= count < 0 ? -count : count; /* -1 means +1 */ + normalizedCounter[charnum++] = (short)count; + previous0 = !count; + while (remaining < threshold) { + nbBits--; + threshold >>= 1; + } + + if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) { + ip += bitCount>>3; + bitCount &= 7; + } else { + bitCount -= (int)(8 * (iend - 4 - ip)); + ip = iend - 4; + } + bitStream = MEM_readLE32(ip) >> (bitCount & 31); + } } /* while ((remaining>1) & (charnum<=*maxSVPtr)) */ + if (remaining != 1) return ERROR(corruption_detected); + if (bitCount > 32) return ERROR(corruption_detected); + *maxSVPtr = charnum-1; + + ip += (bitCount+7)>>3; + return ip-istart; +} + + +/*! HUF_readStats() : + Read compact Huffman tree, saved by HUF_writeCTable(). + `huffWeight` is destination buffer. + `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32. + @return : size read from `src` , or an error Code . + Note : Needed by HUF_readCTable() and HUF_readDTableX?() . +*/ +size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats, + U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize) +{ + U32 weightTotal; + const BYTE* ip = (const BYTE*) src; + size_t iSize; + size_t oSize; + + if (!srcSize) return ERROR(srcSize_wrong); + iSize = ip[0]; + /* memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */ + + if (iSize >= 128) { /* special header */ + oSize = iSize - 127; + iSize = ((oSize+1)/2); + if (iSize+1 > srcSize) return ERROR(srcSize_wrong); + if (oSize >= hwSize) return ERROR(corruption_detected); + ip += 1; + { U32 n; + for (n=0; n> 4; + huffWeight[n+1] = ip[n/2] & 15; + } } } + else { /* header compressed with FSE (normal case) */ + FSE_DTable fseWorkspace[FSE_DTABLE_SIZE_U32(6)]; /* 6 is max possible tableLog for HUF header (maybe even 5, to be tested) */ + if (iSize+1 > srcSize) return ERROR(srcSize_wrong); + oSize = FSE_decompress_wksp(huffWeight, hwSize-1, ip+1, iSize, fseWorkspace, 6); /* max (hwSize-1) values decoded, as last one is implied */ + if (FSE_isError(oSize)) return oSize; + } + + /* collect weight stats */ + memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32)); + weightTotal = 0; + { U32 n; for (n=0; n= HUF_TABLELOG_MAX) return ERROR(corruption_detected); + rankStats[huffWeight[n]]++; + weightTotal += (1 << huffWeight[n]) >> 1; + } } + if (weightTotal == 0) return ERROR(corruption_detected); + + /* get last non-null symbol weight (implied, total must be 2^n) */ + { U32 const tableLog = BIT_highbit32(weightTotal) + 1; + if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected); + *tableLogPtr = tableLog; + /* determine last weight */ + { U32 const total = 1 << tableLog; + U32 const rest = total - weightTotal; + U32 const verif = 1 << BIT_highbit32(rest); + U32 const lastWeight = BIT_highbit32(rest) + 1; + if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */ + huffWeight[oSize] = (BYTE)lastWeight; + rankStats[lastWeight]++; + } } + + /* check tree construction validity */ + if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */ + + /* results */ + *nbSymbolsPtr = (U32)(oSize+1); + return iSize+1; +} +/**** ended inlining common/entropy_common.c ****/ +/**** start inlining common/error_private.c ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* The purpose of this file is to have a single list of error strings embedded in binary */ + +/**** skipping file: error_private.h ****/ + +const char* ERR_getErrorString(ERR_enum code) +{ +#ifdef ZSTD_STRIP_ERROR_STRINGS + (void)code; + return "Error strings stripped"; +#else + static const char* const notErrorCode = "Unspecified error code"; + switch( code ) + { + case PREFIX(no_error): return "No error detected"; + case PREFIX(GENERIC): return "Error (generic)"; + case PREFIX(prefix_unknown): return "Unknown frame descriptor"; + case PREFIX(version_unsupported): return "Version not supported"; + case PREFIX(frameParameter_unsupported): return "Unsupported frame parameter"; + case PREFIX(frameParameter_windowTooLarge): return "Frame requires too much memory for decoding"; + case PREFIX(corruption_detected): return "Corrupted block detected"; + case PREFIX(checksum_wrong): return "Restored data doesn't match checksum"; + case PREFIX(parameter_unsupported): return "Unsupported parameter"; + case PREFIX(parameter_outOfBound): return "Parameter is out of bound"; + case PREFIX(init_missing): return "Context should be init first"; + case PREFIX(memory_allocation): return "Allocation error : not enough memory"; + case PREFIX(workSpace_tooSmall): return "workSpace buffer is not large enough"; + case PREFIX(stage_wrong): return "Operation not authorized at current processing stage"; + case PREFIX(tableLog_tooLarge): return "tableLog requires too much memory : unsupported"; + case PREFIX(maxSymbolValue_tooLarge): return "Unsupported max Symbol Value : too large"; + case PREFIX(maxSymbolValue_tooSmall): return "Specified maxSymbolValue is too small"; + case PREFIX(dictionary_corrupted): return "Dictionary is corrupted"; + case PREFIX(dictionary_wrong): return "Dictionary mismatch"; + case PREFIX(dictionaryCreation_failed): return "Cannot create Dictionary from provided samples"; + case PREFIX(dstSize_tooSmall): return "Destination buffer is too small"; + case PREFIX(srcSize_wrong): return "Src size is incorrect"; + case PREFIX(dstBuffer_null): return "Operation on NULL destination buffer"; + /* following error codes are not stable and may be removed or changed in a future version */ + case PREFIX(frameIndex_tooLarge): return "Frame index is too large"; + case PREFIX(seekableIO): return "An I/O error occurred when reading/seeking"; + case PREFIX(dstBuffer_wrong): return "Destination buffer is wrong"; + case PREFIX(maxCode): + default: return notErrorCode; + } +#endif +} +/**** ended inlining common/error_private.c ****/ +/**** start inlining common/fse_decompress.c ****/ +/* ****************************************************************** + * FSE : Finite State Entropy decoder + * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy + * - Public forum : https://groups.google.com/forum/#!forum/lz4c + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + + +/* ************************************************************** +* Includes +****************************************************************/ +/**** skipping file: bitstream.h ****/ +/**** skipping file: compiler.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: fse.h ****/ +/**** skipping file: error_private.h ****/ + + +/* ************************************************************** +* Error Management +****************************************************************/ +#define FSE_isError ERR_isError +#define FSE_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c) /* use only *after* variable declarations */ + + +/* ************************************************************** +* Templates +****************************************************************/ +/* + designed to be included + for type-specific functions (template emulation in C) + Objective is to write these functions only once, for improved maintenance +*/ + +/* safety checks */ +#ifndef FSE_FUNCTION_EXTENSION +# error "FSE_FUNCTION_EXTENSION must be defined" +#endif +#ifndef FSE_FUNCTION_TYPE +# error "FSE_FUNCTION_TYPE must be defined" +#endif + +/* Function names */ +#define FSE_CAT(X,Y) X##Y +#define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y) +#define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y) + + +/* Function templates */ +FSE_DTable* FSE_createDTable (unsigned tableLog) +{ + if (tableLog > FSE_TABLELOG_ABSOLUTE_MAX) tableLog = FSE_TABLELOG_ABSOLUTE_MAX; + return (FSE_DTable*)malloc( FSE_DTABLE_SIZE_U32(tableLog) * sizeof (U32) ); +} + +void FSE_freeDTable (FSE_DTable* dt) +{ + free(dt); +} + +size_t FSE_buildDTable(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog) +{ + void* const tdPtr = dt+1; /* because *dt is unsigned, 32-bits aligned on 32-bits */ + FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*) (tdPtr); + U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1]; + + U32 const maxSV1 = maxSymbolValue + 1; + U32 const tableSize = 1 << tableLog; + U32 highThreshold = tableSize-1; + + /* Sanity Checks */ + if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge); + if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); + + /* Init, lay down lowprob symbols */ + { FSE_DTableHeader DTableH; + DTableH.tableLog = (U16)tableLog; + DTableH.fastMode = 1; + { S16 const largeLimit= (S16)(1 << (tableLog-1)); + U32 s; + for (s=0; s= largeLimit) DTableH.fastMode=0; + symbolNext[s] = normalizedCounter[s]; + } } } + memcpy(dt, &DTableH, sizeof(DTableH)); + } + + /* Spread symbols */ + { U32 const tableMask = tableSize-1; + U32 const step = FSE_TABLESTEP(tableSize); + U32 s, position = 0; + for (s=0; s highThreshold) position = (position + step) & tableMask; /* lowprob area */ + } } + if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */ + } + + /* Build Decoding table */ + { U32 u; + for (u=0; utableLog = 0; + DTableH->fastMode = 0; + + cell->newState = 0; + cell->symbol = symbolValue; + cell->nbBits = 0; + + return 0; +} + + +size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits) +{ + void* ptr = dt; + FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr; + void* dPtr = dt + 1; + FSE_decode_t* const dinfo = (FSE_decode_t*)dPtr; + const unsigned tableSize = 1 << nbBits; + const unsigned tableMask = tableSize - 1; + const unsigned maxSV1 = tableMask+1; + unsigned s; + + /* Sanity checks */ + if (nbBits < 1) return ERROR(GENERIC); /* min size */ + + /* Build Decoding Table */ + DTableH->tableLog = (U16)nbBits; + DTableH->fastMode = 1; + for (s=0; s sizeof(bitD.bitContainer)*8) /* This test must be static */ + BIT_reloadDStream(&bitD); + + op[1] = FSE_GETSYMBOL(&state2); + + if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */ + { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } } + + op[2] = FSE_GETSYMBOL(&state1); + + if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */ + BIT_reloadDStream(&bitD); + + op[3] = FSE_GETSYMBOL(&state2); + } + + /* tail */ + /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */ + while (1) { + if (op>(omax-2)) return ERROR(dstSize_tooSmall); + *op++ = FSE_GETSYMBOL(&state1); + if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) { + *op++ = FSE_GETSYMBOL(&state2); + break; + } + + if (op>(omax-2)) return ERROR(dstSize_tooSmall); + *op++ = FSE_GETSYMBOL(&state2); + if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) { + *op++ = FSE_GETSYMBOL(&state1); + break; + } } + + return op-ostart; +} + + +size_t FSE_decompress_usingDTable(void* dst, size_t originalSize, + const void* cSrc, size_t cSrcSize, + const FSE_DTable* dt) +{ + const void* ptr = dt; + const FSE_DTableHeader* DTableH = (const FSE_DTableHeader*)ptr; + const U32 fastMode = DTableH->fastMode; + + /* select fast mode (static) */ + if (fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1); + return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0); +} + + +size_t FSE_decompress_wksp(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, FSE_DTable* workSpace, unsigned maxLog) +{ + const BYTE* const istart = (const BYTE*)cSrc; + const BYTE* ip = istart; + short counting[FSE_MAX_SYMBOL_VALUE+1]; + unsigned tableLog; + unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE; + + /* normal FSE decoding mode */ + size_t const NCountLength = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize); + if (FSE_isError(NCountLength)) return NCountLength; + /* if (NCountLength >= cSrcSize) return ERROR(srcSize_wrong); */ /* too small input size; supposed to be already checked in NCountLength, only remaining case : NCountLength==cSrcSize */ + if (tableLog > maxLog) return ERROR(tableLog_tooLarge); + ip += NCountLength; + cSrcSize -= NCountLength; + + CHECK_F( FSE_buildDTable (workSpace, counting, maxSymbolValue, tableLog) ); + + return FSE_decompress_usingDTable (dst, dstCapacity, ip, cSrcSize, workSpace); /* always return, even if it is an error code */ +} + + +typedef FSE_DTable DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)]; + +size_t FSE_decompress(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize) +{ + DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */ + return FSE_decompress_wksp(dst, dstCapacity, cSrc, cSrcSize, dt, FSE_MAX_TABLELOG); +} + + + +#endif /* FSE_COMMONDEFS_ONLY */ +/**** ended inlining common/fse_decompress.c ****/ +/**** start inlining common/zstd_common.c ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + + +/*-************************************* +* Dependencies +***************************************/ +/**** skipping file: error_private.h ****/ +/**** start inlining zstd_internal.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_CCOMMON_H_MODULE +#define ZSTD_CCOMMON_H_MODULE + +/* this module contains definitions which must be identical + * across compression, decompression and dictBuilder. + * It also contains a few functions useful to at least 2 of them + * and which benefit from being inlined */ + +/*-************************************* +* Dependencies +***************************************/ +#ifdef __aarch64__ +#include +#endif +/**** skipping file: compiler.h ****/ +/**** skipping file: mem.h ****/ +/**** skipping file: debug.h ****/ +/**** skipping file: error_private.h ****/ +#define ZSTD_STATIC_LINKING_ONLY +/**** start inlining ../zstd.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ +#if defined (__cplusplus) +extern "C" { +#endif + +#ifndef ZSTD_H_235446 +#define ZSTD_H_235446 + +/* ====== Dependency ======*/ +#include /* INT_MAX */ +#include /* size_t */ + + +/* ===== ZSTDLIB_API : control library symbols visibility ===== */ +#ifndef ZSTDLIB_VISIBILITY +# if defined(__GNUC__) && (__GNUC__ >= 4) +# define ZSTDLIB_VISIBILITY __attribute__ ((visibility ("default"))) +# else +# define ZSTDLIB_VISIBILITY +# endif +#endif +#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) +# define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBILITY +#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) +# define ZSTDLIB_API __declspec(dllimport) ZSTDLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define ZSTDLIB_API ZSTDLIB_VISIBILITY +#endif + + +/******************************************************************************* + Introduction + + zstd, short for Zstandard, is a fast lossless compression algorithm, targeting + real-time compression scenarios at zlib-level and better compression ratios. + The zstd compression library provides in-memory compression and decompression + functions. + + The library supports regular compression levels from 1 up to ZSTD_maxCLevel(), + which is currently 22. Levels >= 20, labeled `--ultra`, should be used with + caution, as they require more memory. The library also offers negative + compression levels, which extend the range of speed vs. ratio preferences. + The lower the level, the faster the speed (at the cost of compression). + + Compression can be done in: + - a single step (described as Simple API) + - a single step, reusing a context (described as Explicit context) + - unbounded multiple steps (described as Streaming compression) + + The compression ratio achievable on small data can be highly improved using + a dictionary. Dictionary compression can be performed in: + - a single step (described as Simple dictionary API) + - a single step, reusing a dictionary (described as Bulk-processing + dictionary API) + + Advanced experimental functions can be accessed using + `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h. + + Advanced experimental APIs should never be used with a dynamically-linked + library. They are not "stable"; their definitions or signatures may change in + the future. Only static linking is allowed. +*******************************************************************************/ + +/*------ Version ------*/ +#define ZSTD_VERSION_MAJOR 1 +#define ZSTD_VERSION_MINOR 4 +#define ZSTD_VERSION_RELEASE 5 + +#define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) +ZSTDLIB_API unsigned ZSTD_versionNumber(void); /**< to check runtime library version */ + +#define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE +#define ZSTD_QUOTE(str) #str +#define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str) +#define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION) +ZSTDLIB_API const char* ZSTD_versionString(void); /* requires v1.3.0+ */ + +/* ************************************* + * Default constant + ***************************************/ +#ifndef ZSTD_CLEVEL_DEFAULT +# define ZSTD_CLEVEL_DEFAULT 3 +#endif + +/* ************************************* + * Constants + ***************************************/ + +/* All magic numbers are supposed read/written to/from files/memory using little-endian convention */ +#define ZSTD_MAGICNUMBER 0xFD2FB528 /* valid since v0.8.0 */ +#define ZSTD_MAGIC_DICTIONARY 0xEC30A437 /* valid since v0.7.0 */ +#define ZSTD_MAGIC_SKIPPABLE_START 0x184D2A50 /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */ +#define ZSTD_MAGIC_SKIPPABLE_MASK 0xFFFFFFF0 + +#define ZSTD_BLOCKSIZELOG_MAX 17 +#define ZSTD_BLOCKSIZE_MAX (1<= `ZSTD_compressBound(srcSize)`. + * @return : compressed size written into `dst` (<= `dstCapacity), + * or an error code if it fails (which can be tested using ZSTD_isError()). */ +ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + int compressionLevel); + +/*! ZSTD_decompress() : + * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames. + * `dstCapacity` is an upper bound of originalSize to regenerate. + * If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data. + * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + * or an errorCode if it fails (which can be tested using ZSTD_isError()). */ +ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity, + const void* src, size_t compressedSize); + +/*! ZSTD_getFrameContentSize() : requires v1.3.0+ + * `src` should point to the start of a ZSTD encoded frame. + * `srcSize` must be at least as large as the frame header. + * hint : any size >= `ZSTD_frameHeaderSize_max` is large enough. + * @return : - decompressed size of `src` frame content, if known + * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined + * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) + * note 1 : a 0 return value means the frame is valid but "empty". + * note 2 : decompressed size is an optional field, it may not be present, typically in streaming mode. + * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. + * In which case, it's necessary to use streaming mode to decompress data. + * Optionally, application can rely on some implicit limit, + * as ZSTD_decompress() only needs an upper bound of decompressed size. + * (For example, data could be necessarily cut into blocks <= 16 KB). + * note 3 : decompressed size is always present when compression is completed using single-pass functions, + * such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict(). + * note 4 : decompressed size can be very large (64-bits value), + * potentially larger than what local system can handle as a single memory segment. + * In which case, it's necessary to use streaming mode to decompress data. + * note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified. + * Always ensure return value fits within application's authorized limits. + * Each application can set its own limits. + * note 6 : This function replaces ZSTD_getDecompressedSize() */ +#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1) +#define ZSTD_CONTENTSIZE_ERROR (0ULL - 2) +ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize); + +/*! ZSTD_getDecompressedSize() : + * NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize(). + * Both functions work the same way, but ZSTD_getDecompressedSize() blends + * "empty", "unknown" and "error" results to the same return value (0), + * while ZSTD_getFrameContentSize() gives them separate return values. + * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */ +ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize); + +/*! ZSTD_findFrameCompressedSize() : + * `src` should point to the start of a ZSTD frame or skippable frame. + * `srcSize` must be >= first frame size + * @return : the compressed size of the first frame starting at `src`, + * suitable to pass as `srcSize` to `ZSTD_decompress` or similar, + * or an error code if input is invalid */ +ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize); + + +/*====== Helper functions ======*/ +#define ZSTD_COMPRESSBOUND(srcSize) ((srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0)) /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */ +ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */ +ZSTDLIB_API unsigned ZSTD_isError(size_t code); /*!< tells if a `size_t` function result is an error code */ +ZSTDLIB_API const char* ZSTD_getErrorName(size_t code); /*!< provides readable string from an error code */ +ZSTDLIB_API int ZSTD_minCLevel(void); /*!< minimum negative compression level allowed */ +ZSTDLIB_API int ZSTD_maxCLevel(void); /*!< maximum compression level available */ + + +/*************************************** +* Explicit context +***************************************/ +/*= Compression context + * When compressing many times, + * it is recommended to allocate a context just once, + * and re-use it for each successive compression operation. + * This will make workload friendlier for system's memory. + * Note : re-using context is just a speed / resource optimization. + * It doesn't change the compression ratio, which remains identical. + * Note 2 : In multi-threaded environments, + * use one different context per thread for parallel execution. + */ +typedef struct ZSTD_CCtx_s ZSTD_CCtx; +ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void); +ZSTDLIB_API size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx); + +/*! ZSTD_compressCCtx() : + * Same as ZSTD_compress(), using an explicit ZSTD_CCtx. + * Important : in order to behave similarly to `ZSTD_compress()`, + * this function compresses at requested compression level, + * __ignoring any other parameter__ . + * If any advanced parameter was set using the advanced API, + * they will all be reset. Only `compressionLevel` remains. + */ +ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + int compressionLevel); + +/*= Decompression context + * When decompressing many times, + * it is recommended to allocate a context only once, + * and re-use it for each successive compression operation. + * This will make workload friendlier for system's memory. + * Use one context per thread for parallel execution. */ +typedef struct ZSTD_DCtx_s ZSTD_DCtx; +ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void); +ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); + +/*! ZSTD_decompressDCtx() : + * Same as ZSTD_decompress(), + * requires an allocated ZSTD_DCtx. + * Compatible with sticky parameters. + */ +ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize); + + +/*************************************** +* Advanced compression API +***************************************/ + +/* API design : + * Parameters are pushed one by one into an existing context, + * using ZSTD_CCtx_set*() functions. + * Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame. + * "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` ! + * __They do not apply to "simple" one-shot variants such as ZSTD_compressCCtx()__ . + * + * It's possible to reset all parameters to "default" using ZSTD_CCtx_reset(). + * + * This API supercedes all other "advanced" API entry points in the experimental section. + * In the future, we expect to remove from experimental API entry points which are redundant with this API. + */ + + +/* Compression strategies, listed from fastest to strongest */ +typedef enum { ZSTD_fast=1, + ZSTD_dfast=2, + ZSTD_greedy=3, + ZSTD_lazy=4, + ZSTD_lazy2=5, + ZSTD_btlazy2=6, + ZSTD_btopt=7, + ZSTD_btultra=8, + ZSTD_btultra2=9 + /* note : new strategies _might_ be added in the future. + Only the order (from fast to strong) is guaranteed */ +} ZSTD_strategy; + + +typedef enum { + + /* compression parameters + * Note: When compressing with a ZSTD_CDict these parameters are superseded + * by the parameters used to construct the ZSTD_CDict. + * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */ + ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table. + * Note that exact compression parameters are dynamically determined, + * depending on both compression level and srcSize (when known). + * Default level is ZSTD_CLEVEL_DEFAULT==3. + * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT. + * Note 1 : it's possible to pass a negative compression level. + * Note 2 : setting a level does not automatically set all other compression parameters + * to default. Setting this will however eventually dynamically impact the compression + * parameters which have not been manually set. The manually set + * ones will 'stick'. */ + /* Advanced compression parameters : + * It's possible to pin down compression parameters to some specific values. + * In which case, these values are no longer dynamically selected by the compressor */ + ZSTD_c_windowLog=101, /* Maximum allowed back-reference distance, expressed as power of 2. + * This will set a memory budget for streaming decompression, + * with larger values requiring more memory + * and typically compressing more. + * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX. + * Special: value 0 means "use default windowLog". + * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT + * requires explicitly allowing such size at streaming decompression stage. */ + ZSTD_c_hashLog=102, /* Size of the initial probe table, as a power of 2. + * Resulting memory usage is (1 << (hashLog+2)). + * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX. + * Larger tables improve compression ratio of strategies <= dFast, + * and improve speed of strategies > dFast. + * Special: value 0 means "use default hashLog". */ + ZSTD_c_chainLog=103, /* Size of the multi-probe search table, as a power of 2. + * Resulting memory usage is (1 << (chainLog+2)). + * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX. + * Larger tables result in better and slower compression. + * This parameter is useless for "fast" strategy. + * It's still useful when using "dfast" strategy, + * in which case it defines a secondary probe table. + * Special: value 0 means "use default chainLog". */ + ZSTD_c_searchLog=104, /* Number of search attempts, as a power of 2. + * More attempts result in better and slower compression. + * This parameter is useless for "fast" and "dFast" strategies. + * Special: value 0 means "use default searchLog". */ + ZSTD_c_minMatch=105, /* Minimum size of searched matches. + * Note that Zstandard can still find matches of smaller size, + * it just tweaks its search algorithm to look for this size and larger. + * Larger values increase compression and decompression speed, but decrease ratio. + * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX. + * Note that currently, for all strategies < btopt, effective minimum is 4. + * , for all strategies > fast, effective maximum is 6. + * Special: value 0 means "use default minMatchLength". */ + ZSTD_c_targetLength=106, /* Impact of this field depends on strategy. + * For strategies btopt, btultra & btultra2: + * Length of Match considered "good enough" to stop search. + * Larger values make compression stronger, and slower. + * For strategy fast: + * Distance between match sampling. + * Larger values make compression faster, and weaker. + * Special: value 0 means "use default targetLength". */ + ZSTD_c_strategy=107, /* See ZSTD_strategy enum definition. + * The higher the value of selected strategy, the more complex it is, + * resulting in stronger and slower compression. + * Special: value 0 means "use default strategy". */ + + /* LDM mode parameters */ + ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching. + * This parameter is designed to improve compression ratio + * for large inputs, by finding large matches at long distance. + * It increases memory usage and window size. + * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB + * except when expressly set to a different value. */ + ZSTD_c_ldmHashLog=161, /* Size of the table for long distance matching, as a power of 2. + * Larger values increase memory usage and compression ratio, + * but decrease compression speed. + * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX + * default: windowlog - 7. + * Special: value 0 means "automatically determine hashlog". */ + ZSTD_c_ldmMinMatch=162, /* Minimum match size for long distance matcher. + * Larger/too small values usually decrease compression ratio. + * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX. + * Special: value 0 means "use default value" (default: 64). */ + ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution. + * Larger values improve collision resolution but decrease compression speed. + * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX. + * Special: value 0 means "use default value" (default: 3). */ + ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table. + * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN). + * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage. + * Larger values improve compression speed. + * Deviating far from default value will likely result in a compression ratio decrease. + * Special: value 0 means "automatically determine hashRateLog". */ + + /* frame parameters */ + ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1) + * Content size must be known at the beginning of compression. + * This is automatically the case when using ZSTD_compress2(), + * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */ + ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */ + ZSTD_c_dictIDFlag=202, /* When applicable, dictionary's ID is written into frame header (default:1) */ + + /* multi-threading parameters */ + /* These parameters are only useful if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD). + * They return an error otherwise. */ + ZSTD_c_nbWorkers=400, /* Select how many threads will be spawned to compress in parallel. + * When nbWorkers >= 1, triggers asynchronous mode when used with ZSTD_compressStream*() : + * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller, + * while compression work is performed in parallel, within worker threads. + * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end : + * in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call). + * More workers improve speed, but also increase memory usage. + * Default value is `0`, aka "single-threaded mode" : no worker is spawned, compression is performed inside Caller's thread, all invocations are blocking */ + ZSTD_c_jobSize=401, /* Size of a compression job. This value is enforced only when nbWorkers >= 1. + * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads. + * 0 means default, which is dynamically determined based on compression parameters. + * Job size must be a minimum of overlap size, or 1 MB, whichever is largest. + * The minimum size is automatically and transparently enforced. */ + ZSTD_c_overlapLog=402, /* Control the overlap size, as a fraction of window size. + * The overlap size is an amount of data reloaded from previous job at the beginning of a new job. + * It helps preserve compression ratio, while each job is compressed in parallel. + * This value is enforced only when nbWorkers >= 1. + * Larger values increase compression ratio, but decrease speed. + * Possible values range from 0 to 9 : + * - 0 means "default" : value will be determined by the library, depending on strategy + * - 1 means "no overlap" + * - 9 means "full overlap", using a full window size. + * Each intermediate rank increases/decreases load size by a factor 2 : + * 9: full window; 8: w/2; 7: w/4; 6: w/8; 5:w/16; 4: w/32; 3:w/64; 2:w/128; 1:no overlap; 0:default + * default value varies between 6 and 9, depending on strategy */ + + /* note : additional experimental parameters are also available + * within the experimental section of the API. + * At the time of this writing, they include : + * ZSTD_c_rsyncable + * ZSTD_c_format + * ZSTD_c_forceMaxWindow + * ZSTD_c_forceAttachDict + * ZSTD_c_literalCompressionMode + * ZSTD_c_targetCBlockSize + * ZSTD_c_srcSizeHint + * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. + * note : never ever use experimentalParam? names directly; + * also, the enums values themselves are unstable and can still change. + */ + ZSTD_c_experimentalParam1=500, + ZSTD_c_experimentalParam2=10, + ZSTD_c_experimentalParam3=1000, + ZSTD_c_experimentalParam4=1001, + ZSTD_c_experimentalParam5=1002, + ZSTD_c_experimentalParam6=1003, + ZSTD_c_experimentalParam7=1004 +} ZSTD_cParameter; + +typedef struct { + size_t error; + int lowerBound; + int upperBound; +} ZSTD_bounds; + +/*! ZSTD_cParam_getBounds() : + * All parameters must belong to an interval with lower and upper bounds, + * otherwise they will either trigger an error or be automatically clamped. + * @return : a structure, ZSTD_bounds, which contains + * - an error status field, which must be tested using ZSTD_isError() + * - lower and upper bounds, both inclusive + */ +ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam); + +/*! ZSTD_CCtx_setParameter() : + * Set one compression parameter, selected by enum ZSTD_cParameter. + * All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds(). + * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). + * Setting a parameter is generally only possible during frame initialization (before starting compression). + * Exception : when using multi-threading mode (nbWorkers >= 1), + * the following parameters can be updated _during_ compression (within same frame): + * => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy. + * new parameters will be active for next job only (after a flush()). + * @return : an error code (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value); + +/*! ZSTD_CCtx_setPledgedSrcSize() : + * Total input data size to be compressed as a single frame. + * Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag. + * This value will also be controlled at end of frame, and trigger an error if not respected. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame. + * In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN. + * ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame. + * Note 2 : pledgedSrcSize is only valid once, for the next frame. + * It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN. + * Note 3 : Whenever all input data is provided and consumed in a single round, + * for example with ZSTD_compress2(), + * or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end), + * this value is automatically overridden by srcSize instead. + */ +ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize); + +typedef enum { + ZSTD_reset_session_only = 1, + ZSTD_reset_parameters = 2, + ZSTD_reset_session_and_parameters = 3 +} ZSTD_ResetDirective; + +/*! ZSTD_CCtx_reset() : + * There are 2 different things that can be reset, independently or jointly : + * - The session : will stop compressing current frame, and make CCtx ready to start a new one. + * Useful after an error, or to interrupt any ongoing compression. + * Any internal data not yet flushed is cancelled. + * Compression parameters and dictionary remain unchanged. + * They will be used to compress next frame. + * Resetting session never fails. + * - The parameters : changes all parameters back to "default". + * This removes any reference to any dictionary too. + * Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing) + * otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError()) + * - Both : similar to resetting the session, followed by resetting parameters. + */ +ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset); + +/*! ZSTD_compress2() : + * Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API. + * ZSTD_compress2() always starts a new frame. + * Should cctx hold data from a previously unfinished frame, everything about it is forgotten. + * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() + * - The function is always blocking, returns when compression is completed. + * Hint : compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`. + * @return : compressed size written into `dst` (<= `dstCapacity), + * or an error code if it fails (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize); + + +/*************************************** +* Advanced decompression API +***************************************/ + +/* The advanced API pushes parameters one by one into an existing DCtx context. + * Parameters are sticky, and remain valid for all following frames + * using the same DCtx context. + * It's possible to reset parameters to default values using ZSTD_DCtx_reset(). + * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream(). + * Therefore, no new decompression function is necessary. + */ + +typedef enum { + + ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which + * the streaming API will refuse to allocate memory buffer + * in order to protect the host from unreasonable memory requirements. + * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. + * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT). + * Special: value 0 means "use default maximum windowLog". */ + + /* note : additional experimental parameters are also available + * within the experimental section of the API. + * At the time of this writing, they include : + * ZSTD_d_format + * ZSTD_d_stableOutBuffer + * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. + * note : never ever use experimentalParam? names directly + */ + ZSTD_d_experimentalParam1=1000, + ZSTD_d_experimentalParam2=1001 + +} ZSTD_dParameter; + +/*! ZSTD_dParam_getBounds() : + * All parameters must belong to an interval with lower and upper bounds, + * otherwise they will either trigger an error or be automatically clamped. + * @return : a structure, ZSTD_bounds, which contains + * - an error status field, which must be tested using ZSTD_isError() + * - both lower and upper bounds, inclusive + */ +ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam); + +/*! ZSTD_DCtx_setParameter() : + * Set one compression parameter, selected by enum ZSTD_dParameter. + * All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds(). + * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter). + * Setting a parameter is only possible during frame initialization (before starting decompression). + * @return : 0, or an error code (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value); + +/*! ZSTD_DCtx_reset() : + * Return a DCtx to clean state. + * Session and parameters can be reset jointly or separately. + * Parameters can only be reset when no active frame is being decompressed. + * @return : 0, or an error code, which can be tested with ZSTD_isError() + */ +ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset); + + +/**************************** +* Streaming +****************************/ + +typedef struct ZSTD_inBuffer_s { + const void* src; /**< start of input buffer */ + size_t size; /**< size of input buffer */ + size_t pos; /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */ +} ZSTD_inBuffer; + +typedef struct ZSTD_outBuffer_s { + void* dst; /**< start of output buffer */ + size_t size; /**< size of output buffer */ + size_t pos; /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */ +} ZSTD_outBuffer; + + + +/*-*********************************************************************** +* Streaming compression - HowTo +* +* A ZSTD_CStream object is required to track streaming operation. +* Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources. +* ZSTD_CStream objects can be reused multiple times on consecutive compression operations. +* It is recommended to re-use ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory. +* +* For parallel execution, use one separate ZSTD_CStream per thread. +* +* note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing. +* +* Parameters are sticky : when starting a new compression on the same context, +* it will re-use the same sticky parameters as previous compression session. +* When in doubt, it's recommended to fully initialize the context before usage. +* Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(), +* ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to +* set more specific parameters, the pledged source size, or load a dictionary. +* +* Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to +* consume input stream. The function will automatically update both `pos` +* fields within `input` and `output`. +* Note that the function may not consume the entire input, for example, because +* the output buffer is already full, in which case `input.pos < input.size`. +* The caller must check if input has been entirely consumed. +* If not, the caller must make some room to receive more compressed data, +* and then present again remaining input data. +* note: ZSTD_e_continue is guaranteed to make some forward progress when called, +* but doesn't guarantee maximal forward progress. This is especially relevant +* when compressing with multiple threads. The call won't block if it can +* consume some input, but if it can't it will wait for some, but not all, +* output to be flushed. +* @return : provides a minimum amount of data remaining to be flushed from internal buffers +* or an error code, which can be tested using ZSTD_isError(). +* +* At any moment, it's possible to flush whatever data might remain stuck within internal buffer, +* using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated. +* Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0). +* In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush. +* You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the +* operation. +* note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will +* block until the flush is complete or the output buffer is full. +* @return : 0 if internal buffers are entirely flushed, +* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size), +* or an error code, which can be tested using ZSTD_isError(). +* +* Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame. +* It will perform a flush and write frame epilogue. +* The epilogue is required for decoders to consider a frame completed. +* flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush. +* You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to +* start a new frame. +* note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will +* block until the flush is complete or the output buffer is full. +* @return : 0 if frame fully completed and fully flushed, +* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size), +* or an error code, which can be tested using ZSTD_isError(). +* +* *******************************************************************/ + +typedef ZSTD_CCtx ZSTD_CStream; /**< CCtx and CStream are now effectively same object (>= v1.3.0) */ + /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */ +/*===== ZSTD_CStream management functions =====*/ +ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void); +ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs); + +/*===== Streaming compression functions =====*/ +typedef enum { + ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */ + ZSTD_e_flush=1, /* flush any data provided so far, + * it creates (at least) one new block, that can be decoded immediately on reception; + * frame will continue: any future data can still reference previously compressed data, improving compression. + * note : multithreaded compression will block to flush as much output as possible. */ + ZSTD_e_end=2 /* flush any remaining data _and_ close current frame. + * note that frame is only closed after compressed data is fully flushed (return value == 0). + * After that point, any additional data starts a new frame. + * note : each frame is independent (does not reference any content from previous frame). + : note : multithreaded compression will block to flush as much output as possible. */ +} ZSTD_EndDirective; + +/*! ZSTD_compressStream2() : + * Behaves about the same as ZSTD_compressStream, with additional control on end directive. + * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() + * - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode) + * - output->pos must be <= dstCapacity, input->pos must be <= srcSize + * - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit. + * - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller. + * - When nbWorkers>=1, function is non-blocking : it just acquires a copy of input, and distributes jobs to internal worker threads, flush whatever is available, + * and then immediately returns, just indicating that there is some data remaining to be flushed. + * The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte. + * - Exception : if the first call requests a ZSTD_e_end directive and provides enough dstCapacity, the function delegates to ZSTD_compress2() which is always blocking. + * - @return provides a minimum amount of data remaining to be flushed from internal buffers + * or an error code, which can be tested using ZSTD_isError(). + * if @return != 0, flush is not fully completed, there is still some data left within internal buffers. + * This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers. + * For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed. + * - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0), + * only ZSTD_e_end or ZSTD_e_flush operations are allowed. + * Before starting a new compression job, or changing compression parameters, + * it is required to fully flush internal buffers. + */ +ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx, + ZSTD_outBuffer* output, + ZSTD_inBuffer* input, + ZSTD_EndDirective endOp); + + +/* These buffer sizes are softly recommended. + * They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output. + * Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(), + * reducing the amount of memory shuffling and buffering, resulting in minor performance savings. + * + * However, note that these recommendations are from the perspective of a C caller program. + * If the streaming interface is invoked from some other language, + * especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo, + * a major performance rule is to reduce crossing such interface to an absolute minimum. + * It's not rare that performance ends being spent more into the interface, rather than compression itself. + * In which cases, prefer using large buffers, as large as practical, + * for both input and output, to reduce the nb of roundtrips. + */ +ZSTDLIB_API size_t ZSTD_CStreamInSize(void); /**< recommended size for input buffer */ +ZSTDLIB_API size_t ZSTD_CStreamOutSize(void); /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */ + + +/* ***************************************************************************** + * This following is a legacy streaming API. + * It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2(). + * It is redundant, but remains fully supported. + * Advanced parameters and dictionary compression can only be used through the + * new API. + ******************************************************************************/ + +/*! + * Equivalent to: + * + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any) + * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); + */ +ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel); +/*! + * Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue). + * NOTE: The return value is different. ZSTD_compressStream() returns a hint for + * the next read size (if non-zero and not an error). ZSTD_compressStream2() + * returns the minimum nb of bytes left to flush (if non-zero and not an error). + */ +ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input); +/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */ +ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); +/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */ +ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); + + +/*-*************************************************************************** +* Streaming decompression - HowTo +* +* A ZSTD_DStream object is required to track streaming operations. +* Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources. +* ZSTD_DStream objects can be re-used multiple times. +* +* Use ZSTD_initDStream() to start a new decompression operation. +* @return : recommended first input size +* Alternatively, use advanced API to set specific properties. +* +* Use ZSTD_decompressStream() repetitively to consume your input. +* The function will update both `pos` fields. +* If `input.pos < input.size`, some input has not been consumed. +* It's up to the caller to present again remaining data. +* The function tries to flush all data decoded immediately, respecting output buffer size. +* If `output.pos < output.size`, decoder has flushed everything it could. +* But if `output.pos == output.size`, there might be some data left within internal buffers., +* In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer. +* Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX. +* @return : 0 when a frame is completely decoded and fully flushed, +* or an error code, which can be tested using ZSTD_isError(), +* or any other value > 0, which means there is still some decoding or flushing to do to complete current frame : +* the return value is a suggested next input size (just a hint for better latency) +* that will never request more than the remaining frame size. +* *******************************************************************************/ + +typedef ZSTD_DCtx ZSTD_DStream; /**< DCtx and DStream are now effectively same object (>= v1.3.0) */ + /* For compatibility with versions <= v1.2.0, prefer differentiating them. */ +/*===== ZSTD_DStream management functions =====*/ +ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void); +ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds); + +/*===== Streaming decompression functions =====*/ + +/* This function is redundant with the advanced API and equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * ZSTD_DCtx_refDDict(zds, NULL); + */ +ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); + +ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); + +ZSTDLIB_API size_t ZSTD_DStreamInSize(void); /*!< recommended size for input buffer */ +ZSTDLIB_API size_t ZSTD_DStreamOutSize(void); /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */ + + +/************************** +* Simple dictionary API +***************************/ +/*! ZSTD_compress_usingDict() : + * Compression at an explicit compression level using a Dictionary. + * A dictionary can be any arbitrary data segment (also called a prefix), + * or a buffer with specified information (see dictBuilder/zdict.h). + * Note : This function loads the dictionary, resulting in significant startup delay. + * It's intended for a dictionary used only once. + * Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */ +ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize, + int compressionLevel); + +/*! ZSTD_decompress_usingDict() : + * Decompression using a known Dictionary. + * Dictionary must be identical to the one used during compression. + * Note : This function loads the dictionary, resulting in significant startup delay. + * It's intended for a dictionary used only once. + * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */ +ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize); + + +/*********************************** + * Bulk processing dictionary API + **********************************/ +typedef struct ZSTD_CDict_s ZSTD_CDict; + +/*! ZSTD_createCDict() : + * When compressing multiple messages or blocks using the same dictionary, + * it's recommended to digest the dictionary only once, since it's a costly operation. + * ZSTD_createCDict() will create a state from digesting a dictionary. + * The resulting state can be used for future compression operations with very limited startup cost. + * ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. + * @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict. + * Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content. + * Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer, + * in which case the only thing that it transports is the @compressionLevel. + * This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively, + * expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */ +ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize, + int compressionLevel); + +/*! ZSTD_freeCDict() : + * Function frees memory allocated by ZSTD_createCDict(). */ +ZSTDLIB_API size_t ZSTD_freeCDict(ZSTD_CDict* CDict); + +/*! ZSTD_compress_usingCDict() : + * Compression using a digested Dictionary. + * Recommended when same dictionary is used multiple times. + * Note : compression level is _decided at dictionary creation time_, + * and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */ +ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_CDict* cdict); + + +typedef struct ZSTD_DDict_s ZSTD_DDict; + +/*! ZSTD_createDDict() : + * Create a digested dictionary, ready to start decompression operation without startup delay. + * dictBuffer can be released after DDict creation, as its content is copied inside DDict. */ +ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize); + +/*! ZSTD_freeDDict() : + * Function frees memory allocated with ZSTD_createDDict() */ +ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict); + +/*! ZSTD_decompress_usingDDict() : + * Decompression using a digested Dictionary. + * Recommended when same dictionary is used multiple times. */ +ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_DDict* ddict); + + +/******************************** + * Dictionary helper functions + *******************************/ + +/*! ZSTD_getDictID_fromDict() : + * Provides the dictID stored within dictionary. + * if @return == 0, the dictionary is not conformant with Zstandard specification. + * It can still be loaded, but as a content-only dictionary. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize); + +/*! ZSTD_getDictID_fromDDict() : + * Provides the dictID of the dictionary loaded into `ddict`. + * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. + * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict); + +/*! ZSTD_getDictID_fromFrame() : + * Provides the dictID required to decompressed the frame stored within `src`. + * If @return == 0, the dictID could not be decoded. + * This could for one of the following reasons : + * - The frame does not require a dictionary to be decoded (most common case). + * - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden information. + * Note : this use case also happens when using a non-conformant dictionary. + * - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`). + * - This is not a Zstandard frame. + * When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */ +ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize); + + +/******************************************************************************* + * Advanced dictionary and prefix API + * + * This API allows dictionaries to be used with ZSTD_compress2(), + * ZSTD_compressStream2(), and ZSTD_decompress(). Dictionaries are sticky, and + * only reset with the context is reset with ZSTD_reset_parameters or + * ZSTD_reset_session_and_parameters. Prefixes are single-use. + ******************************************************************************/ + + +/*! ZSTD_CCtx_loadDictionary() : + * Create an internal CDict from `dict` buffer. + * Decompression will have to use same dictionary. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary, + * meaning "return to no-dictionary mode". + * Note 1 : Dictionary is sticky, it will be used for all future compressed frames. + * To return to "no-dictionary" situation, load a NULL dictionary (or reset parameters). + * Note 2 : Loading a dictionary involves building tables. + * It's also a CPU consuming operation, with non-negligible impact on latency. + * Tables are dependent on compression parameters, and for this reason, + * compression parameters can no longer be changed after loading a dictionary. + * Note 3 :`dict` content will be copied internally. + * Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead. + * In such a case, dictionary buffer must outlive its users. + * Note 4 : Use ZSTD_CCtx_loadDictionary_advanced() + * to precisely select how dictionary content must be interpreted. */ +ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); + +/*! ZSTD_CCtx_refCDict() : + * Reference a prepared dictionary, to be used for all next compressed frames. + * Note that compression parameters are enforced from within CDict, + * and supersede any compression parameter previously set within CCtx. + * The parameters ignored are labled as "superseded-by-cdict" in the ZSTD_cParameter enum docs. + * The ignored parameters will be used again if the CCtx is returned to no-dictionary mode. + * The dictionary will remain valid for future compressed frames using same CCtx. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special : Referencing a NULL CDict means "return to no-dictionary mode". + * Note 1 : Currently, only one dictionary can be managed. + * Referencing a new dictionary effectively "discards" any previous one. + * Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */ +ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); + +/*! ZSTD_CCtx_refPrefix() : + * Reference a prefix (single-usage dictionary) for next compressed frame. + * A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end). + * Decompression will need same prefix to properly regenerate data. + * Compressing with a prefix is similar in outcome as performing a diff and compressing it, + * but performs much faster, especially during decompression (compression speed is tunable with compression level). + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary + * Note 1 : Prefix buffer is referenced. It **must** outlive compression. + * Its content must remain unmodified during compression. + * Note 2 : If the intention is to diff some large src data blob with some prior version of itself, + * ensure that the window size is large enough to contain the entire source. + * See ZSTD_c_windowLog. + * Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters. + * It's a CPU consuming operation, with non-negligible impact on latency. + * If there is a need to use the same prefix multiple times, consider loadDictionary instead. + * Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent). + * Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */ +ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, + const void* prefix, size_t prefixSize); + +/*! ZSTD_DCtx_loadDictionary() : + * Create an internal DDict from dict buffer, + * to be used to decompress next frames. + * The dictionary remains valid for all future frames, until explicitly invalidated. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary, + * meaning "return to no-dictionary mode". + * Note 1 : Loading a dictionary involves building tables, + * which has a non-negligible impact on CPU usage and latency. + * It's recommended to "load once, use many times", to amortize the cost + * Note 2 :`dict` content will be copied internally, so `dict` can be released after loading. + * Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead. + * Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of + * how dictionary content is loaded and interpreted. + */ +ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); + +/*! ZSTD_DCtx_refDDict() : + * Reference a prepared dictionary, to be used to decompress next frames. + * The dictionary remains active for decompression of future frames using same DCtx. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Note 1 : Currently, only one dictionary can be managed. + * Referencing a new dictionary effectively "discards" any previous one. + * Special: referencing a NULL DDict means "return to no-dictionary mode". + * Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx. + */ +ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); + +/*! ZSTD_DCtx_refPrefix() : + * Reference a prefix (single-usage dictionary) to decompress next frame. + * This is the reverse operation of ZSTD_CCtx_refPrefix(), + * and must use the same prefix as the one used during compression. + * Prefix is **only used once**. Reference is discarded at end of frame. + * End of frame is reached when ZSTD_decompressStream() returns 0. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + * Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary + * Note 2 : Prefix buffer is referenced. It **must** outlive decompression. + * Prefix buffer must remain unmodified up to the end of frame, + * reached when ZSTD_decompressStream() returns 0. + * Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent). + * Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section) + * Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost. + * A full dictionary is more costly, as it requires building tables. + */ +ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, + const void* prefix, size_t prefixSize); + +/* === Memory management === */ + +/*! ZSTD_sizeof_*() : + * These functions give the _current_ memory usage of selected object. + * Note that object memory usage can evolve (increase or decrease) over time. */ +ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx); +ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx); +ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs); +ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds); +ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict); +ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); + +#endif /* ZSTD_H_235446 */ + + +/* ************************************************************************************** + * ADVANCED AND EXPERIMENTAL FUNCTIONS + **************************************************************************************** + * The definitions in the following section are considered experimental. + * They are provided for advanced scenarios. + * They should never be used with a dynamic library, as prototypes may change in the future. + * Use them only in association with static linking. + * ***************************************************************************************/ + +#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY) +#define ZSTD_H_ZSTD_STATIC_LINKING_ONLY + +/**************************************************************************************** + * experimental API (static linking only) + **************************************************************************************** + * The following symbols and constants + * are not planned to join "stable API" status in the near future. + * They can still change in future versions. + * Some of them are planned to remain in the static_only section indefinitely. + * Some of them might be removed in the future (especially when redundant with existing stable functions) + * ***************************************************************************************/ + +#define ZSTD_FRAMEHEADERSIZE_PREFIX(format) ((format) == ZSTD_f_zstd1 ? 5 : 1) /* minimum input size required to query frame header size */ +#define ZSTD_FRAMEHEADERSIZE_MIN(format) ((format) == ZSTD_f_zstd1 ? 6 : 2) +#define ZSTD_FRAMEHEADERSIZE_MAX 18 /* can be useful for static allocation */ +#define ZSTD_SKIPPABLEHEADERSIZE 8 + +/* compression parameter bounds */ +#define ZSTD_WINDOWLOG_MAX_32 30 +#define ZSTD_WINDOWLOG_MAX_64 31 +#define ZSTD_WINDOWLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64)) +#define ZSTD_WINDOWLOG_MIN 10 +#define ZSTD_HASHLOG_MAX ((ZSTD_WINDOWLOG_MAX < 30) ? ZSTD_WINDOWLOG_MAX : 30) +#define ZSTD_HASHLOG_MIN 6 +#define ZSTD_CHAINLOG_MAX_32 29 +#define ZSTD_CHAINLOG_MAX_64 30 +#define ZSTD_CHAINLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_CHAINLOG_MAX_32 : ZSTD_CHAINLOG_MAX_64)) +#define ZSTD_CHAINLOG_MIN ZSTD_HASHLOG_MIN +#define ZSTD_SEARCHLOG_MAX (ZSTD_WINDOWLOG_MAX-1) +#define ZSTD_SEARCHLOG_MIN 1 +#define ZSTD_MINMATCH_MAX 7 /* only for ZSTD_fast, other strategies are limited to 6 */ +#define ZSTD_MINMATCH_MIN 3 /* only for ZSTD_btopt+, faster strategies are limited to 4 */ +#define ZSTD_TARGETLENGTH_MAX ZSTD_BLOCKSIZE_MAX +#define ZSTD_TARGETLENGTH_MIN 0 /* note : comparing this constant to an unsigned results in a tautological test */ +#define ZSTD_STRATEGY_MIN ZSTD_fast +#define ZSTD_STRATEGY_MAX ZSTD_btultra2 + + +#define ZSTD_OVERLAPLOG_MIN 0 +#define ZSTD_OVERLAPLOG_MAX 9 + +#define ZSTD_WINDOWLOG_LIMIT_DEFAULT 27 /* by default, the streaming decoder will refuse any frame + * requiring larger than (1< 3, then this is seqDef.offset - 3 + * If seqDef.offset < 3, then this is the corresponding repeat offset + * But if seqDef.offset < 3 and litLength == 0, this is the + * repeat offset before the corresponding repeat offset + * And if seqDef.offset == 3 and litLength == 0, this is the + * most recent repeat offset - 1 + */ + unsigned int offset; + unsigned int litLength; /* Literal length */ + unsigned int matchLength; /* Match length */ + /* 0 when seq not rep and seqDef.offset otherwise + * when litLength == 0 this will be <= 4, otherwise <= 3 like normal + */ + unsigned int rep; +} ZSTD_Sequence; + +typedef struct { + unsigned windowLog; /**< largest match distance : larger == more compression, more memory needed during decompression */ + unsigned chainLog; /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */ + unsigned hashLog; /**< dispatch table : larger == faster, more memory */ + unsigned searchLog; /**< nb of searches : larger == more compression, slower */ + unsigned minMatch; /**< match length searched : larger == faster decompression, sometimes less compression */ + unsigned targetLength; /**< acceptable match size for optimal parser (only) : larger == more compression, slower */ + ZSTD_strategy strategy; /**< see ZSTD_strategy definition above */ +} ZSTD_compressionParameters; + +typedef struct { + int contentSizeFlag; /**< 1: content size will be in frame header (when known) */ + int checksumFlag; /**< 1: generate a 32-bits checksum using XXH64 algorithm at end of frame, for error detection */ + int noDictIDFlag; /**< 1: no dictID will be saved into frame header (dictID is only useful for dictionary compression) */ +} ZSTD_frameParameters; + +typedef struct { + ZSTD_compressionParameters cParams; + ZSTD_frameParameters fParams; +} ZSTD_parameters; + +typedef enum { + ZSTD_dct_auto = 0, /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */ + ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */ + ZSTD_dct_fullDict = 2 /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */ +} ZSTD_dictContentType_e; + +typedef enum { + ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */ + ZSTD_dlm_byRef = 1 /**< Reference dictionary content -- the dictionary buffer must outlive its users. */ +} ZSTD_dictLoadMethod_e; + +typedef enum { + ZSTD_f_zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */ + ZSTD_f_zstd1_magicless = 1 /* Variant of zstd frame format, without initial 4-bytes magic number. + * Useful to save 4 bytes per generated frame. + * Decoder cannot recognise automatically this format, requiring this instruction. */ +} ZSTD_format_e; + +typedef enum { + /* Note: this enum and the behavior it controls are effectively internal + * implementation details of the compressor. They are expected to continue + * to evolve and should be considered only in the context of extremely + * advanced performance tuning. + * + * Zstd currently supports the use of a CDict in three ways: + * + * - The contents of the CDict can be copied into the working context. This + * means that the compression can search both the dictionary and input + * while operating on a single set of internal tables. This makes + * the compression faster per-byte of input. However, the initial copy of + * the CDict's tables incurs a fixed cost at the beginning of the + * compression. For small compressions (< 8 KB), that copy can dominate + * the cost of the compression. + * + * - The CDict's tables can be used in-place. In this model, compression is + * slower per input byte, because the compressor has to search two sets of + * tables. However, this model incurs no start-up cost (as long as the + * working context's tables can be reused). For small inputs, this can be + * faster than copying the CDict's tables. + * + * - The CDict's tables are not used at all, and instead we use the working + * context alone to reload the dictionary and use params based on the source + * size. See ZSTD_compress_insertDictionary() and ZSTD_compress_usingDict(). + * This method is effective when the dictionary sizes are very small relative + * to the input size, and the input size is fairly large to begin with. + * + * Zstd has a simple internal heuristic that selects which strategy to use + * at the beginning of a compression. However, if experimentation shows that + * Zstd is making poor choices, it is possible to override that choice with + * this enum. + */ + ZSTD_dictDefaultAttach = 0, /* Use the default heuristic. */ + ZSTD_dictForceAttach = 1, /* Never copy the dictionary. */ + ZSTD_dictForceCopy = 2, /* Always copy the dictionary. */ + ZSTD_dictForceLoad = 3 /* Always reload the dictionary */ +} ZSTD_dictAttachPref_e; + +typedef enum { + ZSTD_lcm_auto = 0, /**< Automatically determine the compression mode based on the compression level. + * Negative compression levels will be uncompressed, and positive compression + * levels will be compressed. */ + ZSTD_lcm_huffman = 1, /**< Always attempt Huffman compression. Uncompressed literals will still be + * emitted if Huffman compression is not profitable. */ + ZSTD_lcm_uncompressed = 2 /**< Always emit uncompressed literals. */ +} ZSTD_literalCompressionMode_e; + + +/*************************************** +* Frame size functions +***************************************/ + +/*! ZSTD_findDecompressedSize() : + * `src` should point to the start of a series of ZSTD encoded and/or skippable frames + * `srcSize` must be the _exact_ size of this series + * (i.e. there should be a frame boundary at `src + srcSize`) + * @return : - decompressed size of all data in all successive frames + * - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN + * - if an error occurred: ZSTD_CONTENTSIZE_ERROR + * + * note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode. + * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. + * In which case, it's necessary to use streaming mode to decompress data. + * note 2 : decompressed size is always present when compression is done with ZSTD_compress() + * note 3 : decompressed size can be very large (64-bits value), + * potentially larger than what local system can handle as a single memory segment. + * In which case, it's necessary to use streaming mode to decompress data. + * note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified. + * Always ensure result fits within application's authorized limits. + * Each application can set its own limits. + * note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to + * read each contained frame header. This is fast as most of the data is skipped, + * however it does mean that all frame data must be present and valid. */ +ZSTDLIB_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize); + +/*! ZSTD_decompressBound() : + * `src` should point to the start of a series of ZSTD encoded and/or skippable frames + * `srcSize` must be the _exact_ size of this series + * (i.e. there should be a frame boundary at `src + srcSize`) + * @return : - upper-bound for the decompressed size of all data in all successive frames + * - if an error occured: ZSTD_CONTENTSIZE_ERROR + * + * note 1 : an error can occur if `src` contains an invalid or incorrectly formatted frame. + * note 2 : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of `src`. + * in this case, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value. + * note 3 : when the decompressed size field isn't available, the upper-bound for that frame is calculated by: + * upper-bound = # blocks * min(128 KB, Window_Size) + */ +ZSTDLIB_API unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize); + +/*! ZSTD_frameHeaderSize() : + * srcSize must be >= ZSTD_FRAMEHEADERSIZE_PREFIX. + * @return : size of the Frame Header, + * or an error code (if srcSize is too small) */ +ZSTDLIB_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize); + +/*! ZSTD_getSequences() : + * Extract sequences from the sequence store + * zc can be used to insert custom compression params. + * This function invokes ZSTD_compress2 + * @return : number of sequences extracted + */ +ZSTDLIB_API size_t ZSTD_getSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs, + size_t outSeqsSize, const void* src, size_t srcSize); + + +/*************************************** +* Memory management +***************************************/ + +/*! ZSTD_estimate*() : + * These functions make it possible to estimate memory usage + * of a future {D,C}Ctx, before its creation. + * + * ZSTD_estimateCCtxSize() will provide a memory budget large enough + * for any compression level up to selected one. + * Note : Unlike ZSTD_estimateCStreamSize*(), this estimate + * does not include space for a window buffer. + * Therefore, the estimation is only guaranteed for single-shot compressions, not streaming. + * The estimate will assume the input may be arbitrarily large, + * which is the worst case. + * + * When srcSize can be bound by a known and rather "small" value, + * this fact can be used to provide a tighter estimation + * because the CCtx compression context will need less memory. + * This tighter estimation can be provided by more advanced functions + * ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(), + * and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter(). + * Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits. + * + * Note 2 : only single-threaded compression is supported. + * ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. + */ +ZSTDLIB_API size_t ZSTD_estimateCCtxSize(int compressionLevel); +ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams); +ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params); +ZSTDLIB_API size_t ZSTD_estimateDCtxSize(void); + +/*! ZSTD_estimateCStreamSize() : + * ZSTD_estimateCStreamSize() will provide a budget large enough for any compression level up to selected one. + * It will also consider src size to be arbitrarily "large", which is worst case. + * If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation. + * ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel. + * ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParams_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1. + * Note : CStream size estimation is only correct for single-threaded compression. + * ZSTD_DStream memory budget depends on window Size. + * This information can be passed manually, using ZSTD_estimateDStreamSize, + * or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame(); + * Note : if streaming is init with function ZSTD_init?Stream_usingDict(), + * an internal ?Dict will be created, which additional size is not estimated here. + * In this case, get total size by adding ZSTD_estimate?DictSize */ +ZSTDLIB_API size_t ZSTD_estimateCStreamSize(int compressionLevel); +ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams); +ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params); +ZSTDLIB_API size_t ZSTD_estimateDStreamSize(size_t windowSize); +ZSTDLIB_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize); + +/*! ZSTD_estimate?DictSize() : + * ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict(). + * ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced(). + * Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller. + */ +ZSTDLIB_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel); +ZSTDLIB_API size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, ZSTD_dictLoadMethod_e dictLoadMethod); +ZSTDLIB_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod); + +/*! ZSTD_initStatic*() : + * Initialize an object using a pre-allocated fixed-size buffer. + * workspace: The memory area to emplace the object into. + * Provided pointer *must be 8-bytes aligned*. + * Buffer must outlive object. + * workspaceSize: Use ZSTD_estimate*Size() to determine + * how large workspace must be to support target scenario. + * @return : pointer to object (same address as workspace, just different type), + * or NULL if error (size too small, incorrect alignment, etc.) + * Note : zstd will never resize nor malloc() when using a static buffer. + * If the object requires more memory than available, + * zstd will just error out (typically ZSTD_error_memory_allocation). + * Note 2 : there is no corresponding "free" function. + * Since workspace is allocated externally, it must be freed externally too. + * Note 3 : cParams : use ZSTD_getCParams() to convert a compression level + * into its associated cParams. + * Limitation 1 : currently not compatible with internal dictionary creation, triggered by + * ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict(). + * Limitation 2 : static cctx currently not compatible with multi-threading. + * Limitation 3 : static dctx is incompatible with legacy support. + */ +ZSTDLIB_API ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize); +ZSTDLIB_API ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticCCtx() */ + +ZSTDLIB_API ZSTD_DCtx* ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize); +ZSTDLIB_API ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticDCtx() */ + +ZSTDLIB_API const ZSTD_CDict* ZSTD_initStaticCDict( + void* workspace, size_t workspaceSize, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_compressionParameters cParams); + +ZSTDLIB_API const ZSTD_DDict* ZSTD_initStaticDDict( + void* workspace, size_t workspaceSize, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType); + + +/*! Custom memory allocation : + * These prototypes make it possible to pass your own allocation/free functions. + * ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below. + * All allocation/free operations will be completed using these custom variants instead of regular ones. + */ +typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size); +typedef void (*ZSTD_freeFunction) (void* opaque, void* address); +typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem; +static ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL }; /**< this constant defers to stdlib's functions */ + +ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem); +ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem); +ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem); +ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem); + +ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_compressionParameters cParams, + ZSTD_customMem customMem); + +ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_customMem customMem); + + + +/*************************************** +* Advanced compression functions +***************************************/ + +/*! ZSTD_createCDict_byReference() : + * Create a digested dictionary for compression + * Dictionary content is just referenced, not duplicated. + * As a consequence, `dictBuffer` **must** outlive CDict, + * and its content must remain unmodified throughout the lifetime of CDict. + * note: equivalent to ZSTD_createCDict_advanced(), with dictLoadMethod==ZSTD_dlm_byRef */ +ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel); + +/*! ZSTD_getCParams() : + * @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize. + * `estimatedSrcSize` value is optional, select 0 if not known */ +ZSTDLIB_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize); + +/*! ZSTD_getParams() : + * same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`. + * All fields of `ZSTD_frameParameters` are set to default : contentSize=1, checksum=0, noDictID=0 */ +ZSTDLIB_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize); + +/*! ZSTD_checkCParams() : + * Ensure param values remain within authorized range. + * @return 0 on success, or an error code (can be checked with ZSTD_isError()) */ +ZSTDLIB_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params); + +/*! ZSTD_adjustCParams() : + * optimize params for a given `srcSize` and `dictSize`. + * `srcSize` can be unknown, in which case use ZSTD_CONTENTSIZE_UNKNOWN. + * `dictSize` must be `0` when there is no dictionary. + * cPar can be invalid : all parameters will be clamped within valid range in the @return struct. + * This function never fails (wide contract) */ +ZSTDLIB_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize); + +/*! ZSTD_compress_advanced() : + * Note : this function is now DEPRECATED. + * It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_setParameter() and other parameter setters. + * This prototype will be marked as deprecated and generate compilation warning on reaching v1.5.x */ +ZSTDLIB_API size_t ZSTD_compress_advanced(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize, + ZSTD_parameters params); + +/*! ZSTD_compress_usingCDict_advanced() : + * Note : this function is now REDUNDANT. + * It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_loadDictionary() and other parameter setters. + * This prototype will be marked as deprecated and generate compilation warning in some future version */ +ZSTDLIB_API size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_CDict* cdict, + ZSTD_frameParameters fParams); + + +/*! ZSTD_CCtx_loadDictionary_byReference() : + * Same as ZSTD_CCtx_loadDictionary(), but dictionary content is referenced, instead of being copied into CCtx. + * It saves some memory, but also requires that `dict` outlives its usage within `cctx` */ +ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); + +/*! ZSTD_CCtx_loadDictionary_advanced() : + * Same as ZSTD_CCtx_loadDictionary(), but gives finer control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?) */ +ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + +/*! ZSTD_CCtx_refPrefix_advanced() : + * Same as ZSTD_CCtx_refPrefix(), but gives finer control over + * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ +ZSTDLIB_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType); + +/* === experimental parameters === */ +/* these parameters can be used with ZSTD_setParameter() + * they are not guaranteed to remain supported in the future */ + + /* Enables rsyncable mode, + * which makes compressed files more rsync friendly + * by adding periodic synchronization points to the compressed data. + * The target average block size is ZSTD_c_jobSize / 2. + * It's possible to modify the job size to increase or decrease + * the granularity of the synchronization point. + * Once the jobSize is smaller than the window size, + * it will result in compression ratio degradation. + * NOTE 1: rsyncable mode only works when multithreading is enabled. + * NOTE 2: rsyncable performs poorly in combination with long range mode, + * since it will decrease the effectiveness of synchronization points, + * though mileage may vary. + * NOTE 3: Rsyncable mode limits maximum compression speed to ~400 MB/s. + * If the selected compression level is already running significantly slower, + * the overall speed won't be significantly impacted. + */ + #define ZSTD_c_rsyncable ZSTD_c_experimentalParam1 + +/* Select a compression format. + * The value must be of type ZSTD_format_e. + * See ZSTD_format_e enum definition for details */ +#define ZSTD_c_format ZSTD_c_experimentalParam2 + +/* Force back-reference distances to remain < windowSize, + * even when referencing into Dictionary content (default:0) */ +#define ZSTD_c_forceMaxWindow ZSTD_c_experimentalParam3 + +/* Controls whether the contents of a CDict + * are used in place, or copied into the working context. + * Accepts values from the ZSTD_dictAttachPref_e enum. + * See the comments on that enum for an explanation of the feature. */ +#define ZSTD_c_forceAttachDict ZSTD_c_experimentalParam4 + +/* Controls how the literals are compressed (default is auto). + * The value must be of type ZSTD_literalCompressionMode_e. + * See ZSTD_literalCompressionMode_t enum definition for details. + */ +#define ZSTD_c_literalCompressionMode ZSTD_c_experimentalParam5 + +/* Tries to fit compressed block size to be around targetCBlockSize. + * No target when targetCBlockSize == 0. + * There is no guarantee on compressed block size (default:0) */ +#define ZSTD_c_targetCBlockSize ZSTD_c_experimentalParam6 + +/* User's best guess of source size. + * Hint is not valid when srcSizeHint == 0. + * There is no guarantee that hint is close to actual source size, + * but compression ratio may regress significantly if guess considerably underestimates */ +#define ZSTD_c_srcSizeHint ZSTD_c_experimentalParam7 + +/*! ZSTD_CCtx_getParameter() : + * Get the requested compression parameter value, selected by enum ZSTD_cParameter, + * and store it into int* value. + * @return : 0, or an error code (which can be tested with ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_CCtx_getParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value); + + +/*! ZSTD_CCtx_params : + * Quick howto : + * - ZSTD_createCCtxParams() : Create a ZSTD_CCtx_params structure + * - ZSTD_CCtxParams_setParameter() : Push parameters one by one into + * an existing ZSTD_CCtx_params structure. + * This is similar to + * ZSTD_CCtx_setParameter(). + * - ZSTD_CCtx_setParametersUsingCCtxParams() : Apply parameters to + * an existing CCtx. + * These parameters will be applied to + * all subsequent frames. + * - ZSTD_compressStream2() : Do compression using the CCtx. + * - ZSTD_freeCCtxParams() : Free the memory. + * + * This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams() + * for static allocation of CCtx for single-threaded compression. + */ +ZSTDLIB_API ZSTD_CCtx_params* ZSTD_createCCtxParams(void); +ZSTDLIB_API size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params); + +/*! ZSTD_CCtxParams_reset() : + * Reset params to default values. + */ +ZSTDLIB_API size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params); + +/*! ZSTD_CCtxParams_init() : + * Initializes the compression parameters of cctxParams according to + * compression level. All other parameters are reset to their default values. + */ +ZSTDLIB_API size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel); + +/*! ZSTD_CCtxParams_init_advanced() : + * Initializes the compression and frame parameters of cctxParams according to + * params. All other parameters are reset to their default values. + */ +ZSTDLIB_API size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params); + +/*! ZSTD_CCtxParams_setParameter() : + * Similar to ZSTD_CCtx_setParameter. + * Set one compression parameter, selected by enum ZSTD_cParameter. + * Parameters must be applied to a ZSTD_CCtx using ZSTD_CCtx_setParametersUsingCCtxParams(). + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int value); + +/*! ZSTD_CCtxParams_getParameter() : + * Similar to ZSTD_CCtx_getParameter. + * Get the requested value of one compression parameter, selected by enum ZSTD_cParameter. + * @result : 0, or an error code (which can be tested with ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_CCtxParams_getParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int* value); + +/*! ZSTD_CCtx_setParametersUsingCCtxParams() : + * Apply a set of ZSTD_CCtx_params to the compression context. + * This can be done even after compression is started, + * if nbWorkers==0, this will have no impact until a new compression is started. + * if nbWorkers>=1, new parameters will be picked up at next job, + * with a few restrictions (windowLog, pledgedSrcSize, nbWorkers, jobSize, and overlapLog are not updated). + */ +ZSTDLIB_API size_t ZSTD_CCtx_setParametersUsingCCtxParams( + ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params); + +/*! ZSTD_compressStream2_simpleArgs() : + * Same as ZSTD_compressStream2(), + * but using only integral types as arguments. + * This variant might be helpful for binders from dynamic languages + * which have troubles handling structures containing memory pointers. + */ +ZSTDLIB_API size_t ZSTD_compressStream2_simpleArgs ( + ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, size_t* dstPos, + const void* src, size_t srcSize, size_t* srcPos, + ZSTD_EndDirective endOp); + + +/*************************************** +* Advanced decompression functions +***************************************/ + +/*! ZSTD_isFrame() : + * Tells if the content of `buffer` starts with a valid Frame Identifier. + * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. + * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. + * Note 3 : Skippable Frame Identifiers are considered valid. */ +ZSTDLIB_API unsigned ZSTD_isFrame(const void* buffer, size_t size); + +/*! ZSTD_createDDict_byReference() : + * Create a digested dictionary, ready to start decompression operation without startup delay. + * Dictionary content is referenced, and therefore stays in dictBuffer. + * It is important that dictBuffer outlives DDict, + * it must remain read accessible throughout the lifetime of DDict */ +ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize); + +/*! ZSTD_DCtx_loadDictionary_byReference() : + * Same as ZSTD_DCtx_loadDictionary(), + * but references `dict` content instead of copying it into `dctx`. + * This saves memory if `dict` remains around., + * However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */ +ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); + +/*! ZSTD_DCtx_loadDictionary_advanced() : + * Same as ZSTD_DCtx_loadDictionary(), + * but gives direct control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?). */ +ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + +/*! ZSTD_DCtx_refPrefix_advanced() : + * Same as ZSTD_DCtx_refPrefix(), but gives finer control over + * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ +ZSTDLIB_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType); + +/*! ZSTD_DCtx_setMaxWindowSize() : + * Refuses allocating internal buffers for frames requiring a window size larger than provided limit. + * This protects a decoder context from reserving too much memory for itself (potential attack scenario). + * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode. + * By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + * @return : 0, or an error code (which can be tested using ZSTD_isError()). + */ +ZSTDLIB_API size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize); + +/* ZSTD_d_format + * experimental parameter, + * allowing selection between ZSTD_format_e input compression formats + */ +#define ZSTD_d_format ZSTD_d_experimentalParam1 +/* ZSTD_d_stableOutBuffer + * Experimental parameter. + * Default is 0 == disabled. Set to 1 to enable. + * + * Tells the decompressor that the ZSTD_outBuffer will ALWAYS be the same + * between calls, except for the modifications that zstd makes to pos (the + * caller must not modify pos). This is checked by the decompressor, and + * decompression will fail if it ever changes. Therefore the ZSTD_outBuffer + * MUST be large enough to fit the entire decompressed frame. This will be + * checked when the frame content size is known. The data in the ZSTD_outBuffer + * in the range [dst, dst + pos) MUST not be modified during decompression + * or you will get data corruption. + * + * When this flags is enabled zstd won't allocate an output buffer, because + * it can write directly to the ZSTD_outBuffer, but it will still allocate + * an input buffer large enough to fit any compressed block. This will also + * avoid the memcpy() from the internal output buffer to the ZSTD_outBuffer. + * If you need to avoid the input buffer allocation use the buffer-less + * streaming API. + * + * NOTE: So long as the ZSTD_outBuffer always points to valid memory, using + * this flag is ALWAYS memory safe, and will never access out-of-bounds + * memory. However, decompression WILL fail if you violate the preconditions. + * + * WARNING: The data in the ZSTD_outBuffer in the range [dst, dst + pos) MUST + * not be modified during decompression or you will get data corruption. This + * is because zstd needs to reference data in the ZSTD_outBuffer to regenerate + * matches. Normally zstd maintains its own buffer for this purpose, but passing + * this flag tells zstd to use the user provided buffer. + */ +#define ZSTD_d_stableOutBuffer ZSTD_d_experimentalParam2 + +/*! ZSTD_DCtx_setFormat() : + * Instruct the decoder context about what kind of data to decode next. + * This instruction is mandatory to decode data without a fully-formed header, + * such ZSTD_f_zstd1_magicless for example. + * @return : 0, or an error code (which can be tested using ZSTD_isError()). */ +ZSTDLIB_API size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format); + +/*! ZSTD_decompressStream_simpleArgs() : + * Same as ZSTD_decompressStream(), + * but using only integral types as arguments. + * This can be helpful for binders from dynamic languages + * which have troubles handling structures containing memory pointers. + */ +ZSTDLIB_API size_t ZSTD_decompressStream_simpleArgs ( + ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, size_t* dstPos, + const void* src, size_t srcSize, size_t* srcPos); + + +/******************************************************************** +* Advanced streaming functions +* Warning : most of these functions are now redundant with the Advanced API. +* Once Advanced API reaches "stable" status, +* redundant functions will be deprecated, and then at some point removed. +********************************************************************/ + +/*===== Advanced Streaming compression functions =====*/ +/**! ZSTD_initCStream_srcSize() : + * This function is deprecated, and equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any) + * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * + * pledgedSrcSize must be correct. If it is not known at init time, use + * ZSTD_CONTENTSIZE_UNKNOWN. Note that, for compatibility with older programs, + * "0" also disables frame content size field. It may be enabled in the future. + * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x + */ +ZSTDLIB_API size_t +ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, + int compressionLevel, + unsigned long long pledgedSrcSize); + +/**! ZSTD_initCStream_usingDict() : + * This function is deprecated, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel); + * ZSTD_CCtx_loadDictionary(zcs, dict, dictSize); + * + * Creates of an internal CDict (incompatible with static CCtx), except if + * dict == NULL or dictSize < 8, in which case no dict is used. + * Note: dict is loaded with ZSTD_dct_auto (treated as a full zstd dictionary if + * it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy. + * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x + */ +ZSTDLIB_API size_t +ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, + const void* dict, size_t dictSize, + int compressionLevel); + +/**! ZSTD_initCStream_advanced() : + * This function is deprecated, and is approximately equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * // Pseudocode: Set each zstd parameter and leave the rest as-is. + * for ((param, value) : params) { + * ZSTD_CCtx_setParameter(zcs, param, value); + * } + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * ZSTD_CCtx_loadDictionary(zcs, dict, dictSize); + * + * dict is loaded with ZSTD_dct_auto and ZSTD_dlm_byCopy. + * pledgedSrcSize must be correct. + * If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN. + * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x + */ +ZSTDLIB_API size_t +ZSTD_initCStream_advanced(ZSTD_CStream* zcs, + const void* dict, size_t dictSize, + ZSTD_parameters params, + unsigned long long pledgedSrcSize); + +/**! ZSTD_initCStream_usingCDict() : + * This function is deprecated, and equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_refCDict(zcs, cdict); + * + * note : cdict will just be referenced, and must outlive compression session + * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x + */ +ZSTDLIB_API size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict); + +/**! ZSTD_initCStream_usingCDict_advanced() : + * This function is DEPRECATED, and is approximately equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * // Pseudocode: Set each zstd frame parameter and leave the rest as-is. + * for ((fParam, value) : fParams) { + * ZSTD_CCtx_setParameter(zcs, fParam, value); + * } + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * ZSTD_CCtx_refCDict(zcs, cdict); + * + * same as ZSTD_initCStream_usingCDict(), with control over frame parameters. + * pledgedSrcSize must be correct. If srcSize is not known at init time, use + * value ZSTD_CONTENTSIZE_UNKNOWN. + * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x + */ +ZSTDLIB_API size_t +ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs, + const ZSTD_CDict* cdict, + ZSTD_frameParameters fParams, + unsigned long long pledgedSrcSize); + +/*! ZSTD_resetCStream() : + * This function is deprecated, and is equivalent to: + * ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only); + * ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize); + * + * start a new frame, using same parameters from previous frame. + * This is typically useful to skip dictionary loading stage, since it will re-use it in-place. + * Note that zcs must be init at least once before using ZSTD_resetCStream(). + * If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN. + * If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end. + * For the time being, pledgedSrcSize==0 is interpreted as "srcSize unknown" for compatibility with older programs, + * but it will change to mean "empty" in future version, so use macro ZSTD_CONTENTSIZE_UNKNOWN instead. + * @return : 0, or an error code (which can be tested using ZSTD_isError()) + * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x + */ +ZSTDLIB_API size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize); + + +typedef struct { + unsigned long long ingested; /* nb input bytes read and buffered */ + unsigned long long consumed; /* nb input bytes actually compressed */ + unsigned long long produced; /* nb of compressed bytes generated and buffered */ + unsigned long long flushed; /* nb of compressed bytes flushed : not provided; can be tracked from caller side */ + unsigned currentJobID; /* MT only : latest started job nb */ + unsigned nbActiveWorkers; /* MT only : nb of workers actively compressing at probe time */ +} ZSTD_frameProgression; + +/* ZSTD_getFrameProgression() : + * tells how much data has been ingested (read from input) + * consumed (input actually compressed) and produced (output) for current frame. + * Note : (ingested - consumed) is amount of input data buffered internally, not yet compressed. + * Aggregates progression inside active worker threads. + */ +ZSTDLIB_API ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx); + +/*! ZSTD_toFlushNow() : + * Tell how many bytes are ready to be flushed immediately. + * Useful for multithreading scenarios (nbWorkers >= 1). + * Probe the oldest active job, defined as oldest job not yet entirely flushed, + * and check its output buffer. + * @return : amount of data stored in oldest job and ready to be flushed immediately. + * if @return == 0, it means either : + * + there is no active job (could be checked with ZSTD_frameProgression()), or + * + oldest job is still actively compressing data, + * but everything it has produced has also been flushed so far, + * therefore flush speed is limited by production speed of oldest job + * irrespective of the speed of concurrent (and newer) jobs. + */ +ZSTDLIB_API size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx); + + +/*===== Advanced Streaming decompression functions =====*/ +/** + * This function is deprecated, and is equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * ZSTD_DCtx_loadDictionary(zds, dict, dictSize); + * + * note: no dictionary will be used if dict == NULL or dictSize < 8 + * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x + */ +ZSTDLIB_API size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize); + +/** + * This function is deprecated, and is equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * ZSTD_DCtx_refDDict(zds, ddict); + * + * note : ddict is referenced, it must outlive decompression session + * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x + */ +ZSTDLIB_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict); + +/** + * This function is deprecated, and is equivalent to: + * + * ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); + * + * re-use decompression parameters from previous init; saves dictionary loading + * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x + */ +ZSTDLIB_API size_t ZSTD_resetDStream(ZSTD_DStream* zds); + + +/********************************************************************* +* Buffer-less and synchronous inner streaming functions +* +* This is an advanced API, giving full control over buffer management, for users which need direct control over memory. +* But it's also a complex one, with several restrictions, documented below. +* Prefer normal streaming API for an easier experience. +********************************************************************* */ + +/** + Buffer-less streaming compression (synchronous mode) + + A ZSTD_CCtx object is required to track streaming operations. + Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource. + ZSTD_CCtx object can be re-used multiple times within successive compression operations. + + Start by initializing a context. + Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression, + or ZSTD_compressBegin_advanced(), for finer parameter control. + It's also possible to duplicate a reference context which has already been initialized, using ZSTD_copyCCtx() + + Then, consume your input using ZSTD_compressContinue(). + There are some important considerations to keep in mind when using this advanced function : + - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only. + - Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks. + - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario. + Worst case evaluation is provided by ZSTD_compressBound(). + ZSTD_compressContinue() doesn't guarantee recover after a failed compression. + - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog). + It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks) + - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps. + In which case, it will "discard" the relevant memory section from its history. + + Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum. + It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame. + Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders. + + `ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress again. +*/ + +/*===== Buffer-less streaming compression functions =====*/ +ZSTDLIB_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel); +ZSTDLIB_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel); +ZSTDLIB_API size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize : If srcSize is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN */ +ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */ +ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict, ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize); /* compression parameters are already set within cdict. pledgedSrcSize must be correct. If srcSize is not known, use macro ZSTD_CONTENTSIZE_UNKNOWN */ +ZSTDLIB_API size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */ + +ZSTDLIB_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); +ZSTDLIB_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + +/*- + Buffer-less streaming decompression (synchronous mode) + + A ZSTD_DCtx object is required to track streaming operations. + Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it. + A ZSTD_DCtx object can be re-used multiple times. + + First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader(). + Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough. + Data fragment must be large enough to ensure successful decoding. + `ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough. + @result : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled. + >0 : `srcSize` is too small, please provide at least @result bytes on next attempt. + errorCode, which can be tested using ZSTD_isError(). + + It fills a ZSTD_frameHeader structure with important information to correctly decode the frame, + such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`). + Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information. + As a consequence, check that values remain within valid application range. + For example, do not allocate memory blindly, check that `windowSize` is within expectation. + Each application can set its own limits, depending on local restrictions. + For extended interoperability, it is recommended to support `windowSize` of at least 8 MB. + + ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize` bytes. + ZSTD_decompressContinue() is very sensitive to contiguity, + if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place, + or that previous contiguous segment is large enough to properly handle maximum back-reference distance. + There are multiple ways to guarantee this condition. + + The most memory efficient way is to use a round buffer of sufficient size. + Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(), + which can @return an error code if required value is too large for current system (in 32-bits mode). + In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one, + up to the moment there is not enough room left in the buffer to guarantee decoding another full block, + which maximum size is provided in `ZSTD_frameHeader` structure, field `blockSizeMax`. + At which point, decoding can resume from the beginning of the buffer. + Note that already decoded data stored in the buffer should be flushed before being overwritten. + + There are alternatives possible, for example using two or more buffers of size `windowSize` each, though they consume more memory. + + Finally, if you control the compression process, you can also ignore all buffer size rules, + as long as the encoder and decoder progress in "lock-step", + aka use exactly the same buffer sizes, break contiguity at the same place, etc. + + Once buffers are setup, start decompression, with ZSTD_decompressBegin(). + If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict(). + + Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively. + ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail. + + @result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity). + It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item. + It can also be an error code, which can be tested with ZSTD_isError(). + + A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero. + Context can then be reset to start a new decompression. + + Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType(). + This information is not required to properly decode a frame. + + == Special case : skippable frames == + + Skippable frames allow integration of user-defined data into a flow of concatenated frames. + Skippable frames will be ignored (skipped) by decompressor. + The format of skippable frames is as follows : + a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F + b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits + c) Frame Content - any content (User Data) of length equal to Frame Size + For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame. + For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content. +*/ + +/*===== Buffer-less streaming decompression functions =====*/ +typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_frameType_e; +typedef struct { + unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */ + unsigned long long windowSize; /* can be very large, up to <= frameContentSize */ + unsigned blockSizeMax; + ZSTD_frameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ + unsigned headerSize; + unsigned dictID; + unsigned checksumFlag; +} ZSTD_frameHeader; + +/*! ZSTD_getFrameHeader() : + * decode Frame Header, or requires larger `srcSize`. + * @return : 0, `zfhPtr` is correctly filled, + * >0, `srcSize` is too small, value is wanted `srcSize` amount, + * or an error code, which can be tested using ZSTD_isError() */ +ZSTDLIB_API size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize); /**< doesn't consume input */ +/*! ZSTD_getFrameHeader_advanced() : + * same as ZSTD_getFrameHeader(), + * with added capability to select a format (like ZSTD_f_zstd1_magicless) */ +ZSTDLIB_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format); +ZSTDLIB_API size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize); /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */ + +ZSTDLIB_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx); +ZSTDLIB_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); +ZSTDLIB_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); + +ZSTDLIB_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx); +ZSTDLIB_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + +/* misc */ +ZSTDLIB_API void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx); +typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e; +ZSTDLIB_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx); + + + + +/* ============================ */ +/** Block level API */ +/* ============================ */ + +/*! + Block functions produce and decode raw zstd blocks, without frame metadata. + Frame metadata cost is typically ~12 bytes, which can be non-negligible for very small blocks (< 100 bytes). + But users will have to take in charge needed metadata to regenerate data, such as compressed and content sizes. + + A few rules to respect : + - Compressing and decompressing require a context structure + + Use ZSTD_createCCtx() and ZSTD_createDCtx() + - It is necessary to init context before starting + + compression : any ZSTD_compressBegin*() variant, including with dictionary + + decompression : any ZSTD_decompressBegin*() variant, including with dictionary + + copyCCtx() and copyDCtx() can be used too + - Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB + + If input is larger than a block size, it's necessary to split input data into multiple blocks + + For inputs larger than a single block, consider using regular ZSTD_compress() instead. + Frame metadata is not that costly, and quickly becomes negligible as source size grows larger than a block. + - When a block is considered not compressible enough, ZSTD_compressBlock() result will be 0 (zero) ! + ===> In which case, nothing is produced into `dst` ! + + User __must__ test for such outcome and deal directly with uncompressed data + + A block cannot be declared incompressible if ZSTD_compressBlock() return value was != 0. + Doing so would mess up with statistics history, leading to potential data corruption. + + ZSTD_decompressBlock() _doesn't accept uncompressed data as input_ !! + + In case of multiple successive blocks, should some of them be uncompressed, + decoder must be informed of their existence in order to follow proper history. + Use ZSTD_insertBlock() for such a case. +*/ + +/*===== Raw zstd block functions =====*/ +ZSTDLIB_API size_t ZSTD_getBlockSize (const ZSTD_CCtx* cctx); +ZSTDLIB_API size_t ZSTD_compressBlock (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); +ZSTDLIB_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); +ZSTDLIB_API size_t ZSTD_insertBlock (ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize); /**< insert uncompressed block into `dctx` history. Useful for multi-blocks decompression. */ + + +#endif /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */ + +#if defined (__cplusplus) +} +#endif +/**** ended inlining ../zstd.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: fse.h ****/ +#define HUF_STATIC_LINKING_ONLY +/**** skipping file: huf.h ****/ +#ifndef XXH_STATIC_LINKING_ONLY +# define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */ +#endif +/**** start inlining xxhash.h ****/ +/* + * xxHash - Extremely Fast Hash algorithm + * Header File + * Copyright (c) 2012-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - xxHash source repository : https://github.com/Cyan4973/xxHash + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +*/ + +/* Notice extracted from xxHash homepage : + +xxHash is an extremely fast Hash algorithm, running at RAM speed limits. +It also successfully passes all tests from the SMHasher suite. + +Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz) + +Name Speed Q.Score Author +xxHash 5.4 GB/s 10 +CrapWow 3.2 GB/s 2 Andrew +MumurHash 3a 2.7 GB/s 10 Austin Appleby +SpookyHash 2.0 GB/s 10 Bob Jenkins +SBox 1.4 GB/s 9 Bret Mulvey +Lookup3 1.2 GB/s 9 Bob Jenkins +SuperFastHash 1.2 GB/s 1 Paul Hsieh +CityHash64 1.05 GB/s 10 Pike & Alakuijala +FNV 0.55 GB/s 5 Fowler, Noll, Vo +CRC32 0.43 GB/s 9 +MD5-32 0.33 GB/s 10 Ronald L. Rivest +SHA1-32 0.28 GB/s 10 + +Q.Score is a measure of quality of the hash function. +It depends on successfully passing SMHasher test set. +10 is a perfect score. + +A 64-bits version, named XXH64, is available since r35. +It offers much better speed, but for 64-bits applications only. +Name Speed on 64 bits Speed on 32 bits +XXH64 13.8 GB/s 1.9 GB/s +XXH32 6.8 GB/s 6.0 GB/s +*/ + +#if defined (__cplusplus) +extern "C" { +#endif + +#ifndef XXHASH_H_5627135585666179 +#define XXHASH_H_5627135585666179 1 + + +/* **************************** +* Definitions +******************************/ +#include /* size_t */ +typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode; + + +/* **************************** +* API modifier +******************************/ +/** XXH_PRIVATE_API +* This is useful if you want to include xxhash functions in `static` mode +* in order to inline them, and remove their symbol from the public list. +* Methodology : +* #define XXH_PRIVATE_API +* #include "xxhash.h" +* `xxhash.c` is automatically included. +* It's not useful to compile and link it as a separate module anymore. +*/ +#ifdef XXH_PRIVATE_API +# ifndef XXH_STATIC_LINKING_ONLY +# define XXH_STATIC_LINKING_ONLY +# endif +# if defined(__GNUC__) +# define XXH_PUBLIC_API static __inline __attribute__((unused)) +# elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define XXH_PUBLIC_API static inline +# elif defined(_MSC_VER) +# define XXH_PUBLIC_API static __inline +# else +# define XXH_PUBLIC_API static /* this version may generate warnings for unused static functions; disable the relevant warning */ +# endif +#else +# define XXH_PUBLIC_API /* do nothing */ +#endif /* XXH_PRIVATE_API */ + +/*!XXH_NAMESPACE, aka Namespace Emulation : + +If you want to include _and expose_ xxHash functions from within your own library, +but also want to avoid symbol collisions with another library which also includes xxHash, + +you can use XXH_NAMESPACE, to automatically prefix any public symbol from xxhash library +with the value of XXH_NAMESPACE (so avoid to keep it NULL and avoid numeric values). + +Note that no change is required within the calling program as long as it includes `xxhash.h` : +regular symbol name will be automatically translated by this header. +*/ +#ifdef XXH_NAMESPACE +# define XXH_CAT(A,B) A##B +# define XXH_NAME2(A,B) XXH_CAT(A,B) +# define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32) +# define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64) +# define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber) +# define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState) +# define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState) +# define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState) +# define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState) +# define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset) +# define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset) +# define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update) +# define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update) +# define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest) +# define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest) +# define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState) +# define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState) +# define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash) +# define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash) +# define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical) +# define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical) +#endif + + +/* ************************************* +* Version +***************************************/ +#define XXH_VERSION_MAJOR 0 +#define XXH_VERSION_MINOR 6 +#define XXH_VERSION_RELEASE 2 +#define XXH_VERSION_NUMBER (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE) +XXH_PUBLIC_API unsigned XXH_versionNumber (void); + + +/* **************************** +* Simple Hash Functions +******************************/ +typedef unsigned int XXH32_hash_t; +typedef unsigned long long XXH64_hash_t; + +XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, unsigned int seed); +XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t length, unsigned long long seed); + +/*! +XXH32() : + Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input". + The memory between input & input+length must be valid (allocated and read-accessible). + "seed" can be used to alter the result predictably. + Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s +XXH64() : + Calculate the 64-bits hash of sequence of length "len" stored at memory address "input". + "seed" can be used to alter the result predictably. + This function runs 2x faster on 64-bits systems, but slower on 32-bits systems (see benchmark). +*/ + + +/* **************************** +* Streaming Hash Functions +******************************/ +typedef struct XXH32_state_s XXH32_state_t; /* incomplete type */ +typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */ + +/*! State allocation, compatible with dynamic libraries */ + +XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void); +XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr); + +XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void); +XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr); + + +/* hash streaming */ + +XXH_PUBLIC_API XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, unsigned int seed); +XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length); +XXH_PUBLIC_API XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr); + +XXH_PUBLIC_API XXH_errorcode XXH64_reset (XXH64_state_t* statePtr, unsigned long long seed); +XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length); +XXH_PUBLIC_API XXH64_hash_t XXH64_digest (const XXH64_state_t* statePtr); + +/* +These functions generate the xxHash of an input provided in multiple segments. +Note that, for small input, they are slower than single-call functions, due to state management. +For small input, prefer `XXH32()` and `XXH64()` . + +XXH state must first be allocated, using XXH*_createState() . + +Start a new hash by initializing state with a seed, using XXH*_reset(). + +Then, feed the hash state by calling XXH*_update() as many times as necessary. +Obviously, input must be allocated and read accessible. +The function returns an error code, with 0 meaning OK, and any other value meaning there is an error. + +Finally, a hash value can be produced anytime, by using XXH*_digest(). +This function returns the nn-bits hash as an int or long long. + +It's still possible to continue inserting input into the hash state after a digest, +and generate some new hashes later on, by calling again XXH*_digest(). + +When done, free XXH state space if it was allocated dynamically. +*/ + + +/* ************************** +* Utils +****************************/ +#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) /* ! C99 */ +# define restrict /* disable restrict */ +#endif + +XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* restrict dst_state, const XXH32_state_t* restrict src_state); +XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* restrict dst_state, const XXH64_state_t* restrict src_state); + + +/* ************************** +* Canonical representation +****************************/ +/* Default result type for XXH functions are primitive unsigned 32 and 64 bits. +* The canonical representation uses human-readable write convention, aka big-endian (large digits first). +* These functions allow transformation of hash result into and from its canonical format. +* This way, hash values can be written into a file / memory, and remain comparable on different systems and programs. +*/ +typedef struct { unsigned char digest[4]; } XXH32_canonical_t; +typedef struct { unsigned char digest[8]; } XXH64_canonical_t; + +XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash); +XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash); + +XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src); +XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src); + +#endif /* XXHASH_H_5627135585666179 */ + + + +/* ================================================================================================ + This section contains definitions which are not guaranteed to remain stable. + They may change in future versions, becoming incompatible with a different version of the library. + They shall only be used with static linking. + Never use these definitions in association with dynamic linking ! +=================================================================================================== */ +#if defined(XXH_STATIC_LINKING_ONLY) && !defined(XXH_STATIC_H_3543687687345) +#define XXH_STATIC_H_3543687687345 + +/* These definitions are only meant to allow allocation of XXH state + statically, on stack, or in a struct for example. + Do not use members directly. */ + + struct XXH32_state_s { + unsigned total_len_32; + unsigned large_len; + unsigned v1; + unsigned v2; + unsigned v3; + unsigned v4; + unsigned mem32[4]; /* buffer defined as U32 for alignment */ + unsigned memsize; + unsigned reserved; /* never read nor write, will be removed in a future version */ + }; /* typedef'd to XXH32_state_t */ + + struct XXH64_state_s { + unsigned long long total_len; + unsigned long long v1; + unsigned long long v2; + unsigned long long v3; + unsigned long long v4; + unsigned long long mem64[4]; /* buffer defined as U64 for alignment */ + unsigned memsize; + unsigned reserved[2]; /* never read nor write, will be removed in a future version */ + }; /* typedef'd to XXH64_state_t */ + + +# ifdef XXH_PRIVATE_API +/**** start inlining xxhash.c ****/ +/* + * xxHash - Fast Hash algorithm + * Copyright (c) 2012-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - xxHash homepage: http://www.xxhash.com + * - xxHash source repository : https://github.com/Cyan4973/xxHash + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +*/ + + +/* ************************************* +* Tuning parameters +***************************************/ +/*!XXH_FORCE_MEMORY_ACCESS : + * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. + * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. + * The below switch allow to select different access method for improved performance. + * Method 0 (default) : use `memcpy()`. Safe and portable. + * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). + * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. + * Method 2 : direct access. This method doesn't depend on compiler but violate C standard. + * It can generate buggy code on targets which do not support unaligned memory accesses. + * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) + * See http://stackoverflow.com/a/32095106/646947 for details. + * Prefer these methods in priority order (0 > 1 > 2) + */ +#ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ +# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) +# define XXH_FORCE_MEMORY_ACCESS 2 +# elif (defined(__INTEL_COMPILER) && !defined(WIN32)) || \ + (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) )) || \ + defined(__ICCARM__) +# define XXH_FORCE_MEMORY_ACCESS 1 +# endif +#endif + +/*!XXH_ACCEPT_NULL_INPUT_POINTER : + * If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer. + * When this option is enabled, xxHash output for null input pointers will be the same as a null-length input. + * By default, this option is disabled. To enable it, uncomment below define : + */ +/* #define XXH_ACCEPT_NULL_INPUT_POINTER 1 */ + +/*!XXH_FORCE_NATIVE_FORMAT : + * By default, xxHash library provides endian-independent Hash values, based on little-endian convention. + * Results are therefore identical for little-endian and big-endian CPU. + * This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format. + * Should endian-independence be of no importance for your application, you may set the #define below to 1, + * to improve speed for Big-endian CPU. + * This option has no impact on Little_Endian CPU. + */ +#ifndef XXH_FORCE_NATIVE_FORMAT /* can be defined externally */ +# define XXH_FORCE_NATIVE_FORMAT 0 +#endif + +/*!XXH_FORCE_ALIGN_CHECK : + * This is a minor performance trick, only useful with lots of very small keys. + * It means : check for aligned/unaligned input. + * The check costs one initial branch per hash; set to 0 when the input data + * is guaranteed to be aligned. + */ +#ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */ +# if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) +# define XXH_FORCE_ALIGN_CHECK 0 +# else +# define XXH_FORCE_ALIGN_CHECK 1 +# endif +#endif + + +/* ************************************* +* Includes & Memory related functions +***************************************/ +/* Modify the local functions below should you wish to use some other memory routines */ +/* for malloc(), free() */ +#include /* size_t */ +static void* XXH_malloc(size_t s) { return malloc(s); } +static void XXH_free (void* p) { free(p); } +/* for memcpy() */ +static void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); } + +#ifndef XXH_STATIC_LINKING_ONLY +# define XXH_STATIC_LINKING_ONLY +#endif +/**** skipping file: xxhash.h ****/ + + +/* ************************************* +* Compiler Specific Options +***************************************/ +#if (defined(__GNUC__) && !defined(__STRICT_ANSI__)) || defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ +# define INLINE_KEYWORD inline +#else +# define INLINE_KEYWORD +#endif + +#if defined(__GNUC__) || defined(__ICCARM__) +# define FORCE_INLINE_ATTR __attribute__((always_inline)) +#elif defined(_MSC_VER) +# define FORCE_INLINE_ATTR __forceinline +#else +# define FORCE_INLINE_ATTR +#endif + +#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR + + +#ifdef _MSC_VER +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +#endif + + +/* ************************************* +* Basic Types +***************************************/ +#ifndef MEM_MODULE +# define MEM_MODULE +# if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# include + typedef uint8_t BYTE; + typedef uint16_t U16; + typedef uint32_t U32; + typedef int32_t S32; + typedef uint64_t U64; +# else + typedef unsigned char BYTE; + typedef unsigned short U16; + typedef unsigned int U32; + typedef signed int S32; + typedef unsigned long long U64; /* if your compiler doesn't support unsigned long long, replace by another 64-bit type here. Note that xxhash.h will also need to be updated. */ +# endif +#endif + + +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) + +/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ +static U32 XXH_read32(const void* memPtr) { return *(const U32*) memPtr; } +static U64 XXH_read64(const void* memPtr) { return *(const U64*) memPtr; } + +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) + +/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ +/* currently only defined for gcc and icc */ +typedef union { U32 u32; U64 u64; } __attribute__((packed)) unalign; + +static U32 XXH_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } +static U64 XXH_read64(const void* ptr) { return ((const unalign*)ptr)->u64; } + +#else + +/* portable and safe solution. Generally efficient. + * see : http://stackoverflow.com/a/32095106/646947 + */ + +static U32 XXH_read32(const void* memPtr) +{ + U32 val; + memcpy(&val, memPtr, sizeof(val)); + return val; +} + +static U64 XXH_read64(const void* memPtr) +{ + U64 val; + memcpy(&val, memPtr, sizeof(val)); + return val; +} + +#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ + + +/* **************************************** +* Compiler-specific Functions and Macros +******************************************/ +#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) + +/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */ +#if defined(_MSC_VER) +# define XXH_rotl32(x,r) _rotl(x,r) +# define XXH_rotl64(x,r) _rotl64(x,r) +#else +#if defined(__ICCARM__) +# include +# define XXH_rotl32(x,r) __ROR(x,(32 - r)) +#else +# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) +#endif +# define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r))) +#endif + +#if defined(_MSC_VER) /* Visual Studio */ +# define XXH_swap32 _byteswap_ulong +# define XXH_swap64 _byteswap_uint64 +#elif GCC_VERSION >= 403 +# define XXH_swap32 __builtin_bswap32 +# define XXH_swap64 __builtin_bswap64 +#else +static U32 XXH_swap32 (U32 x) +{ + return ((x << 24) & 0xff000000 ) | + ((x << 8) & 0x00ff0000 ) | + ((x >> 8) & 0x0000ff00 ) | + ((x >> 24) & 0x000000ff ); +} +static U64 XXH_swap64 (U64 x) +{ + return ((x << 56) & 0xff00000000000000ULL) | + ((x << 40) & 0x00ff000000000000ULL) | + ((x << 24) & 0x0000ff0000000000ULL) | + ((x << 8) & 0x000000ff00000000ULL) | + ((x >> 8) & 0x00000000ff000000ULL) | + ((x >> 24) & 0x0000000000ff0000ULL) | + ((x >> 40) & 0x000000000000ff00ULL) | + ((x >> 56) & 0x00000000000000ffULL); +} +#endif + + +/* ************************************* +* Architecture Macros +***************************************/ +typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess; + +/* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */ +#ifndef XXH_CPU_LITTLE_ENDIAN + static const int g_one = 1; +# define XXH_CPU_LITTLE_ENDIAN (*(const char*)(&g_one)) +#endif + + +/* *************************** +* Memory reads +*****************************/ +typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; + +FORCE_INLINE_TEMPLATE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align) +{ + if (align==XXH_unaligned) + return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr)); + else + return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr); +} + +FORCE_INLINE_TEMPLATE U32 XXH_readLE32(const void* ptr, XXH_endianess endian) +{ + return XXH_readLE32_align(ptr, endian, XXH_unaligned); +} + +static U32 XXH_readBE32(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr); +} + +FORCE_INLINE_TEMPLATE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align) +{ + if (align==XXH_unaligned) + return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr)); + else + return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr); +} + +FORCE_INLINE_TEMPLATE U64 XXH_readLE64(const void* ptr, XXH_endianess endian) +{ + return XXH_readLE64_align(ptr, endian, XXH_unaligned); +} + +static U64 XXH_readBE64(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr); +} + + +/* ************************************* +* Macros +***************************************/ +#define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ + + +/* ************************************* +* Constants +***************************************/ +static const U32 PRIME32_1 = 2654435761U; +static const U32 PRIME32_2 = 2246822519U; +static const U32 PRIME32_3 = 3266489917U; +static const U32 PRIME32_4 = 668265263U; +static const U32 PRIME32_5 = 374761393U; + +static const U64 PRIME64_1 = 11400714785074694791ULL; +static const U64 PRIME64_2 = 14029467366897019727ULL; +static const U64 PRIME64_3 = 1609587929392839161ULL; +static const U64 PRIME64_4 = 9650029242287828579ULL; +static const U64 PRIME64_5 = 2870177450012600261ULL; + +XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; } + + +/* ************************** +* Utils +****************************/ +XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* restrict dstState, const XXH32_state_t* restrict srcState) +{ + memcpy(dstState, srcState, sizeof(*dstState)); +} + +XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* restrict dstState, const XXH64_state_t* restrict srcState) +{ + memcpy(dstState, srcState, sizeof(*dstState)); +} + + +/* *************************** +* Simple Hash Functions +*****************************/ + +static U32 XXH32_round(U32 seed, U32 input) +{ + seed += input * PRIME32_2; + seed = XXH_rotl32(seed, 13); + seed *= PRIME32_1; + return seed; +} + +FORCE_INLINE_TEMPLATE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* bEnd = p + len; + U32 h32; +#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align) + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (p==NULL) { + len=0; + bEnd=p=(const BYTE*)(size_t)16; + } +#endif + + if (len>=16) { + const BYTE* const limit = bEnd - 16; + U32 v1 = seed + PRIME32_1 + PRIME32_2; + U32 v2 = seed + PRIME32_2; + U32 v3 = seed + 0; + U32 v4 = seed - PRIME32_1; + + do { + v1 = XXH32_round(v1, XXH_get32bits(p)); p+=4; + v2 = XXH32_round(v2, XXH_get32bits(p)); p+=4; + v3 = XXH32_round(v3, XXH_get32bits(p)); p+=4; + v4 = XXH32_round(v4, XXH_get32bits(p)); p+=4; + } while (p<=limit); + + h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); + } else { + h32 = seed + PRIME32_5; + } + + h32 += (U32) len; + + while (p+4<=bEnd) { + h32 += XXH_get32bits(p) * PRIME32_3; + h32 = XXH_rotl32(h32, 17) * PRIME32_4 ; + p+=4; + } + + while (p> 15; + h32 *= PRIME32_2; + h32 ^= h32 >> 13; + h32 *= PRIME32_3; + h32 ^= h32 >> 16; + + return h32; +} + + +XXH_PUBLIC_API unsigned int XXH32 (const void* input, size_t len, unsigned int seed) +{ +#if 0 + /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ + XXH32_CREATESTATE_STATIC(state); + XXH32_reset(state, seed); + XXH32_update(state, input, len); + return XXH32_digest(state); +#else + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if (XXH_FORCE_ALIGN_CHECK) { + if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */ + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); + else + return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); + } } + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); + else + return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); +#endif +} + + +static U64 XXH64_round(U64 acc, U64 input) +{ + acc += input * PRIME64_2; + acc = XXH_rotl64(acc, 31); + acc *= PRIME64_1; + return acc; +} + +static U64 XXH64_mergeRound(U64 acc, U64 val) +{ + val = XXH64_round(0, val); + acc ^= val; + acc = acc * PRIME64_1 + PRIME64_4; + return acc; +} + +FORCE_INLINE_TEMPLATE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* const bEnd = p + len; + U64 h64; +#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align) + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (p==NULL) { + len=0; + bEnd=p=(const BYTE*)(size_t)32; + } +#endif + + if (len>=32) { + const BYTE* const limit = bEnd - 32; + U64 v1 = seed + PRIME64_1 + PRIME64_2; + U64 v2 = seed + PRIME64_2; + U64 v3 = seed + 0; + U64 v4 = seed - PRIME64_1; + + do { + v1 = XXH64_round(v1, XXH_get64bits(p)); p+=8; + v2 = XXH64_round(v2, XXH_get64bits(p)); p+=8; + v3 = XXH64_round(v3, XXH_get64bits(p)); p+=8; + v4 = XXH64_round(v4, XXH_get64bits(p)); p+=8; + } while (p<=limit); + + h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); + h64 = XXH64_mergeRound(h64, v1); + h64 = XXH64_mergeRound(h64, v2); + h64 = XXH64_mergeRound(h64, v3); + h64 = XXH64_mergeRound(h64, v4); + + } else { + h64 = seed + PRIME64_5; + } + + h64 += (U64) len; + + while (p+8<=bEnd) { + U64 const k1 = XXH64_round(0, XXH_get64bits(p)); + h64 ^= k1; + h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; + p+=8; + } + + if (p+4<=bEnd) { + h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1; + h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; + p+=4; + } + + while (p> 33; + h64 *= PRIME64_2; + h64 ^= h64 >> 29; + h64 *= PRIME64_3; + h64 ^= h64 >> 32; + + return h64; +} + + +XXH_PUBLIC_API unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed) +{ +#if 0 + /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ + XXH64_CREATESTATE_STATIC(state); + XXH64_reset(state, seed); + XXH64_update(state, input, len); + return XXH64_digest(state); +#else + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if (XXH_FORCE_ALIGN_CHECK) { + if ((((size_t)input) & 7)==0) { /* Input is aligned, let's leverage the speed advantage */ + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); + else + return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); + } } + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); + else + return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); +#endif +} + + +/* ************************************************** +* Advanced Hash Functions +****************************************************/ + +XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void) +{ + return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t)); +} +XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr) +{ + XXH_free(statePtr); + return XXH_OK; +} + +XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void) +{ + return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t)); +} +XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr) +{ + XXH_free(statePtr); + return XXH_OK; +} + + +/*** Hash feed ***/ + +XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int seed) +{ + XXH32_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ + memset(&state, 0, sizeof(state)-4); /* do not write into reserved, for future removal */ + state.v1 = seed + PRIME32_1 + PRIME32_2; + state.v2 = seed + PRIME32_2; + state.v3 = seed + 0; + state.v4 = seed - PRIME32_1; + memcpy(statePtr, &state, sizeof(state)); + return XXH_OK; +} + + +XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long long seed) +{ + XXH64_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ + memset(&state, 0, sizeof(state)-8); /* do not write into reserved, for future removal */ + state.v1 = seed + PRIME64_1 + PRIME64_2; + state.v2 = seed + PRIME64_2; + state.v3 = seed + 0; + state.v4 = seed - PRIME64_1; + memcpy(statePtr, &state, sizeof(state)); + return XXH_OK; +} + + +FORCE_INLINE_TEMPLATE XXH_errorcode XXH32_update_endian (XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* const bEnd = p + len; + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (input==NULL) return XXH_ERROR; +#endif + + state->total_len_32 += (unsigned)len; + state->large_len |= (len>=16) | (state->total_len_32>=16); + + if (state->memsize + len < 16) { /* fill in tmp buffer */ + XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len); + state->memsize += (unsigned)len; + return XXH_OK; + } + + if (state->memsize) { /* some data left from previous update */ + XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize); + { const U32* p32 = state->mem32; + state->v1 = XXH32_round(state->v1, XXH_readLE32(p32, endian)); p32++; + state->v2 = XXH32_round(state->v2, XXH_readLE32(p32, endian)); p32++; + state->v3 = XXH32_round(state->v3, XXH_readLE32(p32, endian)); p32++; + state->v4 = XXH32_round(state->v4, XXH_readLE32(p32, endian)); p32++; + } + p += 16-state->memsize; + state->memsize = 0; + } + + if (p <= bEnd-16) { + const BYTE* const limit = bEnd - 16; + U32 v1 = state->v1; + U32 v2 = state->v2; + U32 v3 = state->v3; + U32 v4 = state->v4; + + do { + v1 = XXH32_round(v1, XXH_readLE32(p, endian)); p+=4; + v2 = XXH32_round(v2, XXH_readLE32(p, endian)); p+=4; + v3 = XXH32_round(v3, XXH_readLE32(p, endian)); p+=4; + v4 = XXH32_round(v4, XXH_readLE32(p, endian)); p+=4; + } while (p<=limit); + + state->v1 = v1; + state->v2 = v2; + state->v3 = v3; + state->v4 = v4; + } + + if (p < bEnd) { + XXH_memcpy(state->mem32, p, (size_t)(bEnd-p)); + state->memsize = (unsigned)(bEnd-p); + } + + return XXH_OK; +} + +XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_update_endian(state_in, input, len, XXH_littleEndian); + else + return XXH32_update_endian(state_in, input, len, XXH_bigEndian); +} + + + +FORCE_INLINE_TEMPLATE U32 XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian) +{ + const BYTE * p = (const BYTE*)state->mem32; + const BYTE* const bEnd = (const BYTE*)(state->mem32) + state->memsize; + U32 h32; + + if (state->large_len) { + h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18); + } else { + h32 = state->v3 /* == seed */ + PRIME32_5; + } + + h32 += state->total_len_32; + + while (p+4<=bEnd) { + h32 += XXH_readLE32(p, endian) * PRIME32_3; + h32 = XXH_rotl32(h32, 17) * PRIME32_4; + p+=4; + } + + while (p> 15; + h32 *= PRIME32_2; + h32 ^= h32 >> 13; + h32 *= PRIME32_3; + h32 ^= h32 >> 16; + + return h32; +} + + +XXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_digest_endian(state_in, XXH_littleEndian); + else + return XXH32_digest_endian(state_in, XXH_bigEndian); +} + + + +/* **** XXH64 **** */ + +FORCE_INLINE_TEMPLATE XXH_errorcode XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* const bEnd = p + len; + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (input==NULL) return XXH_ERROR; +#endif + + state->total_len += len; + + if (state->memsize + len < 32) { /* fill in tmp buffer */ + if (input != NULL) { + XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len); + } + state->memsize += (U32)len; + return XXH_OK; + } + + if (state->memsize) { /* tmp buffer is full */ + XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize); + state->v1 = XXH64_round(state->v1, XXH_readLE64(state->mem64+0, endian)); + state->v2 = XXH64_round(state->v2, XXH_readLE64(state->mem64+1, endian)); + state->v3 = XXH64_round(state->v3, XXH_readLE64(state->mem64+2, endian)); + state->v4 = XXH64_round(state->v4, XXH_readLE64(state->mem64+3, endian)); + p += 32-state->memsize; + state->memsize = 0; + } + + if (p+32 <= bEnd) { + const BYTE* const limit = bEnd - 32; + U64 v1 = state->v1; + U64 v2 = state->v2; + U64 v3 = state->v3; + U64 v4 = state->v4; + + do { + v1 = XXH64_round(v1, XXH_readLE64(p, endian)); p+=8; + v2 = XXH64_round(v2, XXH_readLE64(p, endian)); p+=8; + v3 = XXH64_round(v3, XXH_readLE64(p, endian)); p+=8; + v4 = XXH64_round(v4, XXH_readLE64(p, endian)); p+=8; + } while (p<=limit); + + state->v1 = v1; + state->v2 = v2; + state->v3 = v3; + state->v4 = v4; + } + + if (p < bEnd) { + XXH_memcpy(state->mem64, p, (size_t)(bEnd-p)); + state->memsize = (unsigned)(bEnd-p); + } + + return XXH_OK; +} + +XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH64_update_endian(state_in, input, len, XXH_littleEndian); + else + return XXH64_update_endian(state_in, input, len, XXH_bigEndian); +} + + + +FORCE_INLINE_TEMPLATE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian) +{ + const BYTE * p = (const BYTE*)state->mem64; + const BYTE* const bEnd = (const BYTE*)state->mem64 + state->memsize; + U64 h64; + + if (state->total_len >= 32) { + U64 const v1 = state->v1; + U64 const v2 = state->v2; + U64 const v3 = state->v3; + U64 const v4 = state->v4; + + h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); + h64 = XXH64_mergeRound(h64, v1); + h64 = XXH64_mergeRound(h64, v2); + h64 = XXH64_mergeRound(h64, v3); + h64 = XXH64_mergeRound(h64, v4); + } else { + h64 = state->v3 + PRIME64_5; + } + + h64 += (U64) state->total_len; + + while (p+8<=bEnd) { + U64 const k1 = XXH64_round(0, XXH_readLE64(p, endian)); + h64 ^= k1; + h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; + p+=8; + } + + if (p+4<=bEnd) { + h64 ^= (U64)(XXH_readLE32(p, endian)) * PRIME64_1; + h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; + p+=4; + } + + while (p> 33; + h64 *= PRIME64_2; + h64 ^= h64 >> 29; + h64 *= PRIME64_3; + h64 ^= h64 >> 32; + + return h64; +} + + +XXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH64_digest_endian(state_in, XXH_littleEndian); + else + return XXH64_digest_endian(state_in, XXH_bigEndian); +} + + +/* ************************** +* Canonical representation +****************************/ + +/*! Default XXH result types are basic unsigned 32 and 64 bits. +* The canonical representation follows human-readable write convention, aka big-endian (large digits first). +* These functions allow transformation of hash result into and from its canonical format. +* This way, hash values can be written into a file or buffer, and remain comparable across different systems and programs. +*/ + +XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash); + memcpy(dst, &hash, sizeof(*dst)); +} + +XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash); + memcpy(dst, &hash, sizeof(*dst)); +} + +XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src) +{ + return XXH_readBE32(src); +} + +XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src) +{ + return XXH_readBE64(src); +} +/**** ended inlining xxhash.c ****/ +# endif + +#endif /* XXH_STATIC_LINKING_ONLY && XXH_STATIC_H_3543687687345 */ + + +#if defined (__cplusplus) +} +#endif +/**** ended inlining xxhash.h ****/ + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ---- static assert (debug) --- */ +#define ZSTD_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c) +#define ZSTD_isError ERR_isError /* for inlining */ +#define FSE_isError ERR_isError +#define HUF_isError ERR_isError + + +/*-************************************* +* shared macros +***************************************/ +#undef MIN +#undef MAX +#define MIN(a,b) ((a)<(b) ? (a) : (b)) +#define MAX(a,b) ((a)>(b) ? (a) : (b)) + +/** + * Ignore: this is an internal helper. + * + * This is a helper function to help force C99-correctness during compilation. + * Under strict compilation modes, variadic macro arguments can't be empty. + * However, variadic function arguments can be. Using a function therefore lets + * us statically check that at least one (string) argument was passed, + * independent of the compilation flags. + */ +static INLINE_KEYWORD UNUSED_ATTR +void _force_has_format_string(const char *format, ...) { + (void)format; +} + +/** + * Ignore: this is an internal helper. + * + * We want to force this function invocation to be syntactically correct, but + * we don't want to force runtime evaluation of its arguments. + */ +#define _FORCE_HAS_FORMAT_STRING(...) \ + if (0) { \ + _force_has_format_string(__VA_ARGS__); \ + } + +/** + * Return the specified error if the condition evaluates to true. + * + * In debug modes, prints additional information. + * In order to do that (particularly, printing the conditional that failed), + * this can't just wrap RETURN_ERROR(). + */ +#define RETURN_ERROR_IF(cond, err, ...) \ + if (cond) { \ + RAWLOG(3, "%s:%d: ERROR!: check %s failed, returning %s", \ + __FILE__, __LINE__, ZSTD_QUOTE(cond), ZSTD_QUOTE(ERROR(err))); \ + _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \ + RAWLOG(3, ": " __VA_ARGS__); \ + RAWLOG(3, "\n"); \ + return ERROR(err); \ + } + +/** + * Unconditionally return the specified error. + * + * In debug modes, prints additional information. + */ +#define RETURN_ERROR(err, ...) \ + do { \ + RAWLOG(3, "%s:%d: ERROR!: unconditional check failed, returning %s", \ + __FILE__, __LINE__, ZSTD_QUOTE(ERROR(err))); \ + _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \ + RAWLOG(3, ": " __VA_ARGS__); \ + RAWLOG(3, "\n"); \ + return ERROR(err); \ + } while(0); + +/** + * If the provided expression evaluates to an error code, returns that error code. + * + * In debug modes, prints additional information. + */ +#define FORWARD_IF_ERROR(err, ...) \ + do { \ + size_t const err_code = (err); \ + if (ERR_isError(err_code)) { \ + RAWLOG(3, "%s:%d: ERROR!: forwarding error in %s: %s", \ + __FILE__, __LINE__, ZSTD_QUOTE(err), ERR_getErrorName(err_code)); \ + _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \ + RAWLOG(3, ": " __VA_ARGS__); \ + RAWLOG(3, "\n"); \ + return err_code; \ + } \ + } while(0); + + +/*-************************************* +* Common constants +***************************************/ +#define ZSTD_OPT_NUM (1<<12) + +#define ZSTD_REP_NUM 3 /* number of repcodes */ +#define ZSTD_REP_MOVE (ZSTD_REP_NUM-1) +static const U32 repStartValue[ZSTD_REP_NUM] = { 1, 4, 8 }; + +#define KB *(1 <<10) +#define MB *(1 <<20) +#define GB *(1U<<30) + +#define BIT7 128 +#define BIT6 64 +#define BIT5 32 +#define BIT4 16 +#define BIT1 2 +#define BIT0 1 + +#define ZSTD_WINDOWLOG_ABSOLUTEMIN 10 +static const size_t ZSTD_fcs_fieldSize[4] = { 0, 2, 4, 8 }; +static const size_t ZSTD_did_fieldSize[4] = { 0, 1, 2, 4 }; + +#define ZSTD_FRAMEIDSIZE 4 /* magic number size */ + +#define ZSTD_BLOCKHEADERSIZE 3 /* C standard doesn't allow `static const` variable to be init using another `static const` variable */ +static const size_t ZSTD_blockHeaderSize = ZSTD_BLOCKHEADERSIZE; +typedef enum { bt_raw, bt_rle, bt_compressed, bt_reserved } blockType_e; + +#define ZSTD_FRAMECHECKSUMSIZE 4 + +#define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */ +#define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */ + MIN_SEQUENCES_SIZE /* nbSeq==0 */) /* for a non-null block */ + +#define HufLog 12 +typedef enum { set_basic, set_rle, set_compressed, set_repeat } symbolEncodingType_e; + +#define LONGNBSEQ 0x7F00 + +#define MINMATCH 3 + +#define Litbits 8 +#define MaxLit ((1<= 8 || (ovtype == ZSTD_no_overlap && diff <= -WILDCOPY_VECLEN)); + + if (ovtype == ZSTD_overlap_src_before_dst && diff < WILDCOPY_VECLEN) { + /* Handle short offset copies. */ + do { + COPY8(op, ip) + } while (op < oend); + } else { + assert(diff >= WILDCOPY_VECLEN || diff <= -WILDCOPY_VECLEN); + /* Separate out the first COPY16() call because the copy length is + * almost certain to be short, so the branches have different + * probabilities. Since it is almost certain to be short, only do + * one COPY16() in the first call. Then, do two calls per loop since + * at that point it is more likely to have a high trip count. + */ +#ifndef __aarch64__ + do { + COPY16(op, ip); + } + while (op < oend); +#else + COPY16(op, ip); + if (op >= oend) return; + do { + COPY16(op, ip); + COPY16(op, ip); + } + while (op < oend); +#endif + } +} + +MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize) +{ + size_t const length = MIN(dstCapacity, srcSize); + if (length > 0) { + memcpy(dst, src, length); + } + return length; +} + +/* define "workspace is too large" as this number of times larger than needed */ +#define ZSTD_WORKSPACETOOLARGE_FACTOR 3 + +/* when workspace is continuously too large + * during at least this number of times, + * context's memory usage is considered wasteful, + * because it's sized to handle a worst case scenario which rarely happens. + * In which case, resize it down to free some memory */ +#define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128 + + +/*-******************************************* +* Private declarations +*********************************************/ +typedef struct seqDef_s { + U32 offset; + U16 litLength; + U16 matchLength; +} seqDef; + +typedef struct { + seqDef* sequencesStart; + seqDef* sequences; + BYTE* litStart; + BYTE* lit; + BYTE* llCode; + BYTE* mlCode; + BYTE* ofCode; + size_t maxNbSeq; + size_t maxNbLit; + U32 longLengthID; /* 0 == no longLength; 1 == Lit.longLength; 2 == Match.longLength; */ + U32 longLengthPos; +} seqStore_t; + +typedef struct { + U32 litLength; + U32 matchLength; +} ZSTD_sequenceLength; + +/** + * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences + * indicated by longLengthPos and longLengthID, and adds MINMATCH back to matchLength. + */ +MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, seqDef const* seq) +{ + ZSTD_sequenceLength seqLen; + seqLen.litLength = seq->litLength; + seqLen.matchLength = seq->matchLength + MINMATCH; + if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) { + if (seqStore->longLengthID == 1) { + seqLen.litLength += 0xFFFF; + } + if (seqStore->longLengthID == 2) { + seqLen.matchLength += 0xFFFF; + } + } + return seqLen; +} + +/** + * Contains the compressed frame size and an upper-bound for the decompressed frame size. + * Note: before using `compressedSize`, check for errors using ZSTD_isError(). + * similarly, before using `decompressedBound`, check for errors using: + * `decompressedBound != ZSTD_CONTENTSIZE_ERROR` + */ +typedef struct { + size_t compressedSize; + unsigned long long decompressedBound; +} ZSTD_frameSizeInfo; /* decompress & legacy */ + +const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx); /* compress & dictBuilder */ +void ZSTD_seqToCodes(const seqStore_t* seqStorePtr); /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */ + +/* custom memory allocation functions */ +void* ZSTD_malloc(size_t size, ZSTD_customMem customMem); +void* ZSTD_calloc(size_t size, ZSTD_customMem customMem); +void ZSTD_free(void* ptr, ZSTD_customMem customMem); + + +MEM_STATIC U32 ZSTD_highbit32(U32 val) /* compress, dictBuilder, decodeCorpus */ +{ + assert(val != 0); + { +# if defined(_MSC_VER) /* Visual */ + unsigned long r=0; + return _BitScanReverse(&r, val) ? (unsigned)r : 0; +# elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */ + return __builtin_clz (val) ^ 31; +# elif defined(__ICCARM__) /* IAR Intrinsic */ + return 31 - __CLZ(val); +# else /* Software version */ + static const U32 DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; + U32 v = val; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + return DeBruijnClz[(v * 0x07C4ACDDU) >> 27]; +# endif + } +} + + +/* ZSTD_invalidateRepCodes() : + * ensures next compression will not use repcodes from previous block. + * Note : only works with regular variant; + * do not use with extDict variant ! */ +void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx); /* zstdmt, adaptive_compression (shouldn't get this definition from here) */ + + +typedef struct { + blockType_e blockType; + U32 lastBlock; + U32 origSize; +} blockProperties_t; /* declared here for decompress and fullbench */ + +/*! ZSTD_getcBlockSize() : + * Provides the size of compressed block from block header `src` */ +/* Used by: decompress, fullbench (does not get its definition from here) */ +size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, + blockProperties_t* bpPtr); + +/*! ZSTD_decodeSeqHeaders() : + * decode sequence header from src */ +/* Used by: decompress, fullbench (does not get its definition from here) */ +size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, + const void* src, size_t srcSize); + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_CCOMMON_H_MODULE */ +/**** ended inlining zstd_internal.h ****/ + + +/*-**************************************** +* Version +******************************************/ +unsigned ZSTD_versionNumber(void) { return ZSTD_VERSION_NUMBER; } + +const char* ZSTD_versionString(void) { return ZSTD_VERSION_STRING; } + + +/*-**************************************** +* ZSTD Error Management +******************************************/ +#undef ZSTD_isError /* defined within zstd_internal.h */ +/*! ZSTD_isError() : + * tells if a return value is an error code + * symbol is required for external callers */ +unsigned ZSTD_isError(size_t code) { return ERR_isError(code); } + +/*! ZSTD_getErrorName() : + * provides error code string from function result (useful for debugging) */ +const char* ZSTD_getErrorName(size_t code) { return ERR_getErrorName(code); } + +/*! ZSTD_getError() : + * convert a `size_t` function result into a proper ZSTD_errorCode enum */ +ZSTD_ErrorCode ZSTD_getErrorCode(size_t code) { return ERR_getErrorCode(code); } + +/*! ZSTD_getErrorString() : + * provides error code string from enum */ +const char* ZSTD_getErrorString(ZSTD_ErrorCode code) { return ERR_getErrorString(code); } + + + +/*=************************************************************** +* Custom allocator +****************************************************************/ +void* ZSTD_malloc(size_t size, ZSTD_customMem customMem) +{ + if (customMem.customAlloc) + return customMem.customAlloc(customMem.opaque, size); + return malloc(size); +} + +void* ZSTD_calloc(size_t size, ZSTD_customMem customMem) +{ + if (customMem.customAlloc) { + /* calloc implemented as malloc+memset; + * not as efficient as calloc, but next best guess for custom malloc */ + void* const ptr = customMem.customAlloc(customMem.opaque, size); + memset(ptr, 0, size); + return ptr; + } + return calloc(1, size); +} + +void ZSTD_free(void* ptr, ZSTD_customMem customMem) +{ + if (ptr!=NULL) { + if (customMem.customFree) + customMem.customFree(customMem.opaque, ptr); + else + free(ptr); + } +} +/**** ended inlining common/zstd_common.c ****/ + +/**** start inlining decompress/huf_decompress.c ****/ +/* ****************************************************************** + * huff0 huffman decoder, + * part of Finite State Entropy library + * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc. + * + * You can contact the author at : + * - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. +****************************************************************** */ + +/* ************************************************************** +* Dependencies +****************************************************************/ +/**** skipping file: ../common/compiler.h ****/ +/**** skipping file: ../common/bitstream.h ****/ +/**** skipping file: ../common/fse.h ****/ +#define HUF_STATIC_LINKING_ONLY +/**** skipping file: ../common/huf.h ****/ +/**** skipping file: ../common/error_private.h ****/ + +/* ************************************************************** +* Macros +****************************************************************/ + +/* These two optional macros force the use one way or another of the two + * Huffman decompression implementations. You can't force in both directions + * at the same time. + */ +#if defined(HUF_FORCE_DECOMPRESS_X1) && \ + defined(HUF_FORCE_DECOMPRESS_X2) +#error "Cannot force the use of the X1 and X2 decoders at the same time!" +#endif + + +/* ************************************************************** +* Error Management +****************************************************************/ +#define HUF_isError ERR_isError + + +/* ************************************************************** +* Byte alignment for workSpace management +****************************************************************/ +#define HUF_ALIGN(x, a) HUF_ALIGN_MASK((x), (a) - 1) +#define HUF_ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask)) + + +/* ************************************************************** +* BMI2 Variant Wrappers +****************************************************************/ +#if DYNAMIC_BMI2 + +#define HUF_DGEN(fn) \ + \ + static size_t fn##_default( \ + void* dst, size_t dstSize, \ + const void* cSrc, size_t cSrcSize, \ + const HUF_DTable* DTable) \ + { \ + return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \ + } \ + \ + static TARGET_ATTRIBUTE("bmi2") size_t fn##_bmi2( \ + void* dst, size_t dstSize, \ + const void* cSrc, size_t cSrcSize, \ + const HUF_DTable* DTable) \ + { \ + return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \ + } \ + \ + static size_t fn(void* dst, size_t dstSize, void const* cSrc, \ + size_t cSrcSize, HUF_DTable const* DTable, int bmi2) \ + { \ + if (bmi2) { \ + return fn##_bmi2(dst, dstSize, cSrc, cSrcSize, DTable); \ + } \ + return fn##_default(dst, dstSize, cSrc, cSrcSize, DTable); \ + } + +#else + +#define HUF_DGEN(fn) \ + static size_t fn(void* dst, size_t dstSize, void const* cSrc, \ + size_t cSrcSize, HUF_DTable const* DTable, int bmi2) \ + { \ + (void)bmi2; \ + return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \ + } + +#endif + + +/*-***************************/ +/* generic DTableDesc */ +/*-***************************/ +typedef struct { BYTE maxTableLog; BYTE tableType; BYTE tableLog; BYTE reserved; } DTableDesc; + +static DTableDesc HUF_getDTableDesc(const HUF_DTable* table) +{ + DTableDesc dtd; + memcpy(&dtd, table, sizeof(dtd)); + return dtd; +} + + +#ifndef HUF_FORCE_DECOMPRESS_X2 + +/*-***************************/ +/* single-symbol decoding */ +/*-***************************/ +typedef struct { BYTE byte; BYTE nbBits; } HUF_DEltX1; /* single-symbol decoding */ + +size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize) +{ + U32 tableLog = 0; + U32 nbSymbols = 0; + size_t iSize; + void* const dtPtr = DTable + 1; + HUF_DEltX1* const dt = (HUF_DEltX1*)dtPtr; + + U32* rankVal; + BYTE* huffWeight; + size_t spaceUsed32 = 0; + + rankVal = (U32 *)workSpace + spaceUsed32; + spaceUsed32 += HUF_TABLELOG_ABSOLUTEMAX + 1; + huffWeight = (BYTE *)((U32 *)workSpace + spaceUsed32); + spaceUsed32 += HUF_ALIGN(HUF_SYMBOLVALUE_MAX + 1, sizeof(U32)) >> 2; + + if ((spaceUsed32 << 2) > wkspSize) return ERROR(tableLog_tooLarge); + + DEBUG_STATIC_ASSERT(sizeof(DTableDesc) == sizeof(HUF_DTable)); + /* memset(huffWeight, 0, sizeof(huffWeight)); */ /* is not necessary, even though some analyzer complain ... */ + + iSize = HUF_readStats(huffWeight, HUF_SYMBOLVALUE_MAX + 1, rankVal, &nbSymbols, &tableLog, src, srcSize); + if (HUF_isError(iSize)) return iSize; + + /* Table header */ + { DTableDesc dtd = HUF_getDTableDesc(DTable); + if (tableLog > (U32)(dtd.maxTableLog+1)) return ERROR(tableLog_tooLarge); /* DTable too small, Huffman tree cannot fit in */ + dtd.tableType = 0; + dtd.tableLog = (BYTE)tableLog; + memcpy(DTable, &dtd, sizeof(dtd)); + } + + /* Calculate starting value for each rank */ + { U32 n, nextRankStart = 0; + for (n=1; n> 1; + size_t const uStart = rankVal[w]; + size_t const uEnd = uStart + length; + size_t u; + HUF_DEltX1 D; + D.byte = (BYTE)n; + D.nbBits = (BYTE)(tableLog + 1 - w); + rankVal[w] = (U32)uEnd; + if (length < 4) { + /* Use length in the loop bound so the compiler knows it is short. */ + for (u = 0; u < length; ++u) + dt[uStart + u] = D; + } else { + /* Unroll the loop 4 times, we know it is a power of 2. */ + for (u = uStart; u < uEnd; u += 4) { + dt[u + 0] = D; + dt[u + 1] = D; + dt[u + 2] = D; + dt[u + 3] = D; + } } } } + return iSize; +} + +size_t HUF_readDTableX1(HUF_DTable* DTable, const void* src, size_t srcSize) +{ + U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; + return HUF_readDTableX1_wksp(DTable, src, srcSize, + workSpace, sizeof(workSpace)); +} + +FORCE_INLINE_TEMPLATE BYTE +HUF_decodeSymbolX1(BIT_DStream_t* Dstream, const HUF_DEltX1* dt, const U32 dtLog) +{ + size_t const val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */ + BYTE const c = dt[val].byte; + BIT_skipBits(Dstream, dt[val].nbBits); + return c; +} + +#define HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr) \ + *ptr++ = HUF_decodeSymbolX1(DStreamPtr, dt, dtLog) + +#define HUF_DECODE_SYMBOLX1_1(ptr, DStreamPtr) \ + if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \ + HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr) + +#define HUF_DECODE_SYMBOLX1_2(ptr, DStreamPtr) \ + if (MEM_64bits()) \ + HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr) + +HINT_INLINE size_t +HUF_decodeStreamX1(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX1* const dt, const U32 dtLog) +{ + BYTE* const pStart = p; + + /* up to 4 symbols at a time */ + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-3)) { + HUF_DECODE_SYMBOLX1_2(p, bitDPtr); + HUF_DECODE_SYMBOLX1_1(p, bitDPtr); + HUF_DECODE_SYMBOLX1_2(p, bitDPtr); + HUF_DECODE_SYMBOLX1_0(p, bitDPtr); + } + + /* [0-3] symbols remaining */ + if (MEM_32bits()) + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd)) + HUF_DECODE_SYMBOLX1_0(p, bitDPtr); + + /* no more data to retrieve from bitstream, no need to reload */ + while (p < pEnd) + HUF_DECODE_SYMBOLX1_0(p, bitDPtr); + + return pEnd-pStart; +} + +FORCE_INLINE_TEMPLATE size_t +HUF_decompress1X1_usingDTable_internal_body( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + BYTE* op = (BYTE*)dst; + BYTE* const oend = op + dstSize; + const void* dtPtr = DTable + 1; + const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr; + BIT_DStream_t bitD; + DTableDesc const dtd = HUF_getDTableDesc(DTable); + U32 const dtLog = dtd.tableLog; + + CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) ); + + HUF_decodeStreamX1(op, &bitD, oend, dt, dtLog); + + if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected); + + return dstSize; +} + +FORCE_INLINE_TEMPLATE size_t +HUF_decompress4X1_usingDTable_internal_body( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + /* Check */ + if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */ + + { const BYTE* const istart = (const BYTE*) cSrc; + BYTE* const ostart = (BYTE*) dst; + BYTE* const oend = ostart + dstSize; + BYTE* const olimit = oend - 3; + const void* const dtPtr = DTable + 1; + const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr; + + /* Init */ + BIT_DStream_t bitD1; + BIT_DStream_t bitD2; + BIT_DStream_t bitD3; + BIT_DStream_t bitD4; + size_t const length1 = MEM_readLE16(istart); + size_t const length2 = MEM_readLE16(istart+2); + size_t const length3 = MEM_readLE16(istart+4); + size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6); + const BYTE* const istart1 = istart + 6; /* jumpTable */ + const BYTE* const istart2 = istart1 + length1; + const BYTE* const istart3 = istart2 + length2; + const BYTE* const istart4 = istart3 + length3; + const size_t segmentSize = (dstSize+3) / 4; + BYTE* const opStart2 = ostart + segmentSize; + BYTE* const opStart3 = opStart2 + segmentSize; + BYTE* const opStart4 = opStart3 + segmentSize; + BYTE* op1 = ostart; + BYTE* op2 = opStart2; + BYTE* op3 = opStart3; + BYTE* op4 = opStart4; + DTableDesc const dtd = HUF_getDTableDesc(DTable); + U32 const dtLog = dtd.tableLog; + U32 endSignal = 1; + + if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */ + CHECK_F( BIT_initDStream(&bitD1, istart1, length1) ); + CHECK_F( BIT_initDStream(&bitD2, istart2, length2) ); + CHECK_F( BIT_initDStream(&bitD3, istart3, length3) ); + CHECK_F( BIT_initDStream(&bitD4, istart4, length4) ); + + /* up to 16 symbols per loop (4 symbols per stream) in 64-bit mode */ + for ( ; (endSignal) & (op4 < olimit) ; ) { + HUF_DECODE_SYMBOLX1_2(op1, &bitD1); + HUF_DECODE_SYMBOLX1_2(op2, &bitD2); + HUF_DECODE_SYMBOLX1_2(op3, &bitD3); + HUF_DECODE_SYMBOLX1_2(op4, &bitD4); + HUF_DECODE_SYMBOLX1_1(op1, &bitD1); + HUF_DECODE_SYMBOLX1_1(op2, &bitD2); + HUF_DECODE_SYMBOLX1_1(op3, &bitD3); + HUF_DECODE_SYMBOLX1_1(op4, &bitD4); + HUF_DECODE_SYMBOLX1_2(op1, &bitD1); + HUF_DECODE_SYMBOLX1_2(op2, &bitD2); + HUF_DECODE_SYMBOLX1_2(op3, &bitD3); + HUF_DECODE_SYMBOLX1_2(op4, &bitD4); + HUF_DECODE_SYMBOLX1_0(op1, &bitD1); + HUF_DECODE_SYMBOLX1_0(op2, &bitD2); + HUF_DECODE_SYMBOLX1_0(op3, &bitD3); + HUF_DECODE_SYMBOLX1_0(op4, &bitD4); + endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished; + } + + /* check corruption */ + /* note : should not be necessary : op# advance in lock step, and we control op4. + * but curiously, binary generated by gcc 7.2 & 7.3 with -mbmi2 runs faster when >=1 test is present */ + if (op1 > opStart2) return ERROR(corruption_detected); + if (op2 > opStart3) return ERROR(corruption_detected); + if (op3 > opStart4) return ERROR(corruption_detected); + /* note : op4 supposed already verified within main loop */ + + /* finish bitStreams one by one */ + HUF_decodeStreamX1(op1, &bitD1, opStart2, dt, dtLog); + HUF_decodeStreamX1(op2, &bitD2, opStart3, dt, dtLog); + HUF_decodeStreamX1(op3, &bitD3, opStart4, dt, dtLog); + HUF_decodeStreamX1(op4, &bitD4, oend, dt, dtLog); + + /* check */ + { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4); + if (!endCheck) return ERROR(corruption_detected); } + + /* decoded size */ + return dstSize; + } +} + + +typedef size_t (*HUF_decompress_usingDTable_t)(void *dst, size_t dstSize, + const void *cSrc, + size_t cSrcSize, + const HUF_DTable *DTable); + +HUF_DGEN(HUF_decompress1X1_usingDTable_internal) +HUF_DGEN(HUF_decompress4X1_usingDTable_internal) + + + +size_t HUF_decompress1X1_usingDTable( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + DTableDesc dtd = HUF_getDTableDesc(DTable); + if (dtd.tableType != 0) return ERROR(GENERIC); + return HUF_decompress1X1_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +} + +size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* DCtx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize) +{ + const BYTE* ip = (const BYTE*) cSrc; + + size_t const hSize = HUF_readDTableX1_wksp(DCtx, cSrc, cSrcSize, workSpace, wkspSize); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; cSrcSize -= hSize; + + return HUF_decompress1X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, DCtx, /* bmi2 */ 0); +} + + +size_t HUF_decompress1X1_DCtx(HUF_DTable* DCtx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize) +{ + U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; + return HUF_decompress1X1_DCtx_wksp(DCtx, dst, dstSize, cSrc, cSrcSize, + workSpace, sizeof(workSpace)); +} + +size_t HUF_decompress1X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ + HUF_CREATE_STATIC_DTABLEX1(DTable, HUF_TABLELOG_MAX); + return HUF_decompress1X1_DCtx (DTable, dst, dstSize, cSrc, cSrcSize); +} + +size_t HUF_decompress4X1_usingDTable( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + DTableDesc dtd = HUF_getDTableDesc(DTable); + if (dtd.tableType != 0) return ERROR(GENERIC); + return HUF_decompress4X1_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +} + +static size_t HUF_decompress4X1_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize, int bmi2) +{ + const BYTE* ip = (const BYTE*) cSrc; + + size_t const hSize = HUF_readDTableX1_wksp (dctx, cSrc, cSrcSize, + workSpace, wkspSize); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; cSrcSize -= hSize; + + return HUF_decompress4X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, bmi2); +} + +size_t HUF_decompress4X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize) +{ + return HUF_decompress4X1_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, 0); +} + + +size_t HUF_decompress4X1_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ + U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; + return HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, + workSpace, sizeof(workSpace)); +} +size_t HUF_decompress4X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ + HUF_CREATE_STATIC_DTABLEX1(DTable, HUF_TABLELOG_MAX); + return HUF_decompress4X1_DCtx(DTable, dst, dstSize, cSrc, cSrcSize); +} + +#endif /* HUF_FORCE_DECOMPRESS_X2 */ + + +#ifndef HUF_FORCE_DECOMPRESS_X1 + +/* *************************/ +/* double-symbols decoding */ +/* *************************/ + +typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX2; /* double-symbols decoding */ +typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t; +typedef U32 rankValCol_t[HUF_TABLELOG_MAX + 1]; +typedef rankValCol_t rankVal_t[HUF_TABLELOG_MAX]; + + +/* HUF_fillDTableX2Level2() : + * `rankValOrigin` must be a table of at least (HUF_TABLELOG_MAX + 1) U32 */ +static void HUF_fillDTableX2Level2(HUF_DEltX2* DTable, U32 sizeLog, const U32 consumed, + const U32* rankValOrigin, const int minWeight, + const sortedSymbol_t* sortedSymbols, const U32 sortedListSize, + U32 nbBitsBaseline, U16 baseSeq) +{ + HUF_DEltX2 DElt; + U32 rankVal[HUF_TABLELOG_MAX + 1]; + + /* get pre-calculated rankVal */ + memcpy(rankVal, rankValOrigin, sizeof(rankVal)); + + /* fill skipped values */ + if (minWeight>1) { + U32 i, skipSize = rankVal[minWeight]; + MEM_writeLE16(&(DElt.sequence), baseSeq); + DElt.nbBits = (BYTE)(consumed); + DElt.length = 1; + for (i = 0; i < skipSize; i++) + DTable[i] = DElt; + } + + /* fill DTable */ + { U32 s; for (s=0; s= 1 */ + + rankVal[weight] += length; + } } +} + + +static void HUF_fillDTableX2(HUF_DEltX2* DTable, const U32 targetLog, + const sortedSymbol_t* sortedList, const U32 sortedListSize, + const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight, + const U32 nbBitsBaseline) +{ + U32 rankVal[HUF_TABLELOG_MAX + 1]; + const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */ + const U32 minBits = nbBitsBaseline - maxWeight; + U32 s; + + memcpy(rankVal, rankValOrigin, sizeof(rankVal)); + + /* fill DTable */ + for (s=0; s= minBits) { /* enough room for a second symbol */ + U32 sortedRank; + int minWeight = nbBits + scaleLog; + if (minWeight < 1) minWeight = 1; + sortedRank = rankStart[minWeight]; + HUF_fillDTableX2Level2(DTable+start, targetLog-nbBits, nbBits, + rankValOrigin[nbBits], minWeight, + sortedList+sortedRank, sortedListSize-sortedRank, + nbBitsBaseline, symbol); + } else { + HUF_DEltX2 DElt; + MEM_writeLE16(&(DElt.sequence), symbol); + DElt.nbBits = (BYTE)(nbBits); + DElt.length = 1; + { U32 const end = start + length; + U32 u; + for (u = start; u < end; u++) DTable[u] = DElt; + } } + rankVal[weight] += length; + } +} + +size_t HUF_readDTableX2_wksp(HUF_DTable* DTable, + const void* src, size_t srcSize, + void* workSpace, size_t wkspSize) +{ + U32 tableLog, maxW, sizeOfSort, nbSymbols; + DTableDesc dtd = HUF_getDTableDesc(DTable); + U32 const maxTableLog = dtd.maxTableLog; + size_t iSize; + void* dtPtr = DTable+1; /* force compiler to avoid strict-aliasing */ + HUF_DEltX2* const dt = (HUF_DEltX2*)dtPtr; + U32 *rankStart; + + rankValCol_t* rankVal; + U32* rankStats; + U32* rankStart0; + sortedSymbol_t* sortedSymbol; + BYTE* weightList; + size_t spaceUsed32 = 0; + + rankVal = (rankValCol_t *)((U32 *)workSpace + spaceUsed32); + spaceUsed32 += (sizeof(rankValCol_t) * HUF_TABLELOG_MAX) >> 2; + rankStats = (U32 *)workSpace + spaceUsed32; + spaceUsed32 += HUF_TABLELOG_MAX + 1; + rankStart0 = (U32 *)workSpace + spaceUsed32; + spaceUsed32 += HUF_TABLELOG_MAX + 2; + sortedSymbol = (sortedSymbol_t *)workSpace + (spaceUsed32 * sizeof(U32)) / sizeof(sortedSymbol_t); + spaceUsed32 += HUF_ALIGN(sizeof(sortedSymbol_t) * (HUF_SYMBOLVALUE_MAX + 1), sizeof(U32)) >> 2; + weightList = (BYTE *)((U32 *)workSpace + spaceUsed32); + spaceUsed32 += HUF_ALIGN(HUF_SYMBOLVALUE_MAX + 1, sizeof(U32)) >> 2; + + if ((spaceUsed32 << 2) > wkspSize) return ERROR(tableLog_tooLarge); + + rankStart = rankStart0 + 1; + memset(rankStats, 0, sizeof(U32) * (2 * HUF_TABLELOG_MAX + 2 + 1)); + + DEBUG_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(HUF_DTable)); /* if compiler fails here, assertion is wrong */ + if (maxTableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge); + /* memset(weightList, 0, sizeof(weightList)); */ /* is not necessary, even though some analyzer complain ... */ + + iSize = HUF_readStats(weightList, HUF_SYMBOLVALUE_MAX + 1, rankStats, &nbSymbols, &tableLog, src, srcSize); + if (HUF_isError(iSize)) return iSize; + + /* check result */ + if (tableLog > maxTableLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */ + + /* find maxWeight */ + for (maxW = tableLog; rankStats[maxW]==0; maxW--) {} /* necessarily finds a solution before 0 */ + + /* Get start index of each weight */ + { U32 w, nextRankStart = 0; + for (w=1; w> consumed; + } } } } + + HUF_fillDTableX2(dt, maxTableLog, + sortedSymbol, sizeOfSort, + rankStart0, rankVal, maxW, + tableLog+1); + + dtd.tableLog = (BYTE)maxTableLog; + dtd.tableType = 1; + memcpy(DTable, &dtd, sizeof(dtd)); + return iSize; +} + +size_t HUF_readDTableX2(HUF_DTable* DTable, const void* src, size_t srcSize) +{ + U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; + return HUF_readDTableX2_wksp(DTable, src, srcSize, + workSpace, sizeof(workSpace)); +} + + +FORCE_INLINE_TEMPLATE U32 +HUF_decodeSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog) +{ + size_t const val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */ + memcpy(op, dt+val, 2); + BIT_skipBits(DStream, dt[val].nbBits); + return dt[val].length; +} + +FORCE_INLINE_TEMPLATE U32 +HUF_decodeLastSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog) +{ + size_t const val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */ + memcpy(op, dt+val, 1); + if (dt[val].length==1) BIT_skipBits(DStream, dt[val].nbBits); + else { + if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) { + BIT_skipBits(DStream, dt[val].nbBits); + if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8)) + /* ugly hack; works only because it's the last symbol. Note : can't easily extract nbBits from just this symbol */ + DStream->bitsConsumed = (sizeof(DStream->bitContainer)*8); + } } + return 1; +} + +#define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \ + ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog) + +#define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \ + if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \ + ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog) + +#define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \ + if (MEM_64bits()) \ + ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog) + +HINT_INLINE size_t +HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd, + const HUF_DEltX2* const dt, const U32 dtLog) +{ + BYTE* const pStart = p; + + /* up to 8 symbols at a time */ + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-(sizeof(bitDPtr->bitContainer)-1))) { + HUF_DECODE_SYMBOLX2_2(p, bitDPtr); + HUF_DECODE_SYMBOLX2_1(p, bitDPtr); + HUF_DECODE_SYMBOLX2_2(p, bitDPtr); + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + } + + /* closer to end : up to 2 symbols at a time */ + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p <= pEnd-2)) + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + + while (p <= pEnd-2) + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); /* no need to reload : reached the end of DStream */ + + if (p < pEnd) + p += HUF_decodeLastSymbolX2(p, bitDPtr, dt, dtLog); + + return p-pStart; +} + +FORCE_INLINE_TEMPLATE size_t +HUF_decompress1X2_usingDTable_internal_body( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + BIT_DStream_t bitD; + + /* Init */ + CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) ); + + /* decode */ + { BYTE* const ostart = (BYTE*) dst; + BYTE* const oend = ostart + dstSize; + const void* const dtPtr = DTable+1; /* force compiler to not use strict-aliasing */ + const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr; + DTableDesc const dtd = HUF_getDTableDesc(DTable); + HUF_decodeStreamX2(ostart, &bitD, oend, dt, dtd.tableLog); + } + + /* check */ + if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected); + + /* decoded size */ + return dstSize; +} + +FORCE_INLINE_TEMPLATE size_t +HUF_decompress4X2_usingDTable_internal_body( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */ + + { const BYTE* const istart = (const BYTE*) cSrc; + BYTE* const ostart = (BYTE*) dst; + BYTE* const oend = ostart + dstSize; + BYTE* const olimit = oend - (sizeof(size_t)-1); + const void* const dtPtr = DTable+1; + const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr; + + /* Init */ + BIT_DStream_t bitD1; + BIT_DStream_t bitD2; + BIT_DStream_t bitD3; + BIT_DStream_t bitD4; + size_t const length1 = MEM_readLE16(istart); + size_t const length2 = MEM_readLE16(istart+2); + size_t const length3 = MEM_readLE16(istart+4); + size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6); + const BYTE* const istart1 = istart + 6; /* jumpTable */ + const BYTE* const istart2 = istart1 + length1; + const BYTE* const istart3 = istart2 + length2; + const BYTE* const istart4 = istart3 + length3; + size_t const segmentSize = (dstSize+3) / 4; + BYTE* const opStart2 = ostart + segmentSize; + BYTE* const opStart3 = opStart2 + segmentSize; + BYTE* const opStart4 = opStart3 + segmentSize; + BYTE* op1 = ostart; + BYTE* op2 = opStart2; + BYTE* op3 = opStart3; + BYTE* op4 = opStart4; + U32 endSignal = 1; + DTableDesc const dtd = HUF_getDTableDesc(DTable); + U32 const dtLog = dtd.tableLog; + + if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */ + CHECK_F( BIT_initDStream(&bitD1, istart1, length1) ); + CHECK_F( BIT_initDStream(&bitD2, istart2, length2) ); + CHECK_F( BIT_initDStream(&bitD3, istart3, length3) ); + CHECK_F( BIT_initDStream(&bitD4, istart4, length4) ); + + /* 16-32 symbols per loop (4-8 symbols per stream) */ + for ( ; (endSignal) & (op4 < olimit); ) { +#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__)) + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_1(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_0(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_1(op2, &bitD2); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_0(op2, &bitD2); + endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished; + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_1(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_0(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_1(op4, &bitD4); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_0(op4, &bitD4); + endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished; + endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished; +#else + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_1(op1, &bitD1); + HUF_DECODE_SYMBOLX2_1(op2, &bitD2); + HUF_DECODE_SYMBOLX2_1(op3, &bitD3); + HUF_DECODE_SYMBOLX2_1(op4, &bitD4); + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_0(op1, &bitD1); + HUF_DECODE_SYMBOLX2_0(op2, &bitD2); + HUF_DECODE_SYMBOLX2_0(op3, &bitD3); + HUF_DECODE_SYMBOLX2_0(op4, &bitD4); + endSignal = (U32)LIKELY( + (BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished) + & (BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished) + & (BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished) + & (BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished)); +#endif + } + + /* check corruption */ + if (op1 > opStart2) return ERROR(corruption_detected); + if (op2 > opStart3) return ERROR(corruption_detected); + if (op3 > opStart4) return ERROR(corruption_detected); + /* note : op4 already verified within main loop */ + + /* finish bitStreams one by one */ + HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog); + HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog); + HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog); + HUF_decodeStreamX2(op4, &bitD4, oend, dt, dtLog); + + /* check */ + { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4); + if (!endCheck) return ERROR(corruption_detected); } + + /* decoded size */ + return dstSize; + } +} + +HUF_DGEN(HUF_decompress1X2_usingDTable_internal) +HUF_DGEN(HUF_decompress4X2_usingDTable_internal) + +size_t HUF_decompress1X2_usingDTable( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + DTableDesc dtd = HUF_getDTableDesc(DTable); + if (dtd.tableType != 1) return ERROR(GENERIC); + return HUF_decompress1X2_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +} + +size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* DCtx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize) +{ + const BYTE* ip = (const BYTE*) cSrc; + + size_t const hSize = HUF_readDTableX2_wksp(DCtx, cSrc, cSrcSize, + workSpace, wkspSize); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; cSrcSize -= hSize; + + return HUF_decompress1X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, DCtx, /* bmi2 */ 0); +} + + +size_t HUF_decompress1X2_DCtx(HUF_DTable* DCtx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize) +{ + U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; + return HUF_decompress1X2_DCtx_wksp(DCtx, dst, dstSize, cSrc, cSrcSize, + workSpace, sizeof(workSpace)); +} + +size_t HUF_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ + HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_TABLELOG_MAX); + return HUF_decompress1X2_DCtx(DTable, dst, dstSize, cSrc, cSrcSize); +} + +size_t HUF_decompress4X2_usingDTable( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + DTableDesc dtd = HUF_getDTableDesc(DTable); + if (dtd.tableType != 1) return ERROR(GENERIC); + return HUF_decompress4X2_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +} + +static size_t HUF_decompress4X2_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize, int bmi2) +{ + const BYTE* ip = (const BYTE*) cSrc; + + size_t hSize = HUF_readDTableX2_wksp(dctx, cSrc, cSrcSize, + workSpace, wkspSize); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; cSrcSize -= hSize; + + return HUF_decompress4X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, bmi2); +} + +size_t HUF_decompress4X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize) +{ + return HUF_decompress4X2_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, /* bmi2 */ 0); +} + + +size_t HUF_decompress4X2_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize) +{ + U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; + return HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, + workSpace, sizeof(workSpace)); +} + +size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ + HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_TABLELOG_MAX); + return HUF_decompress4X2_DCtx(DTable, dst, dstSize, cSrc, cSrcSize); +} + +#endif /* HUF_FORCE_DECOMPRESS_X1 */ + + +/* ***********************************/ +/* Universal decompression selectors */ +/* ***********************************/ + +size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + DTableDesc const dtd = HUF_getDTableDesc(DTable); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)dtd; + assert(dtd.tableType == 0); + return HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)dtd; + assert(dtd.tableType == 1); + return HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +#else + return dtd.tableType ? HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0) : + HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +#endif +} + +size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize, + const void* cSrc, size_t cSrcSize, + const HUF_DTable* DTable) +{ + DTableDesc const dtd = HUF_getDTableDesc(DTable); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)dtd; + assert(dtd.tableType == 0); + return HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)dtd; + assert(dtd.tableType == 1); + return HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +#else + return dtd.tableType ? HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0) : + HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0); +#endif +} + + +#if !defined(HUF_FORCE_DECOMPRESS_X1) && !defined(HUF_FORCE_DECOMPRESS_X2) +typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t; +static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] = +{ + /* single, double, quad */ + {{0,0}, {1,1}, {2,2}}, /* Q==0 : impossible */ + {{0,0}, {1,1}, {2,2}}, /* Q==1 : impossible */ + {{ 38,130}, {1313, 74}, {2151, 38}}, /* Q == 2 : 12-18% */ + {{ 448,128}, {1353, 74}, {2238, 41}}, /* Q == 3 : 18-25% */ + {{ 556,128}, {1353, 74}, {2238, 47}}, /* Q == 4 : 25-32% */ + {{ 714,128}, {1418, 74}, {2436, 53}}, /* Q == 5 : 32-38% */ + {{ 883,128}, {1437, 74}, {2464, 61}}, /* Q == 6 : 38-44% */ + {{ 897,128}, {1515, 75}, {2622, 68}}, /* Q == 7 : 44-50% */ + {{ 926,128}, {1613, 75}, {2730, 75}}, /* Q == 8 : 50-56% */ + {{ 947,128}, {1729, 77}, {3359, 77}}, /* Q == 9 : 56-62% */ + {{1107,128}, {2083, 81}, {4006, 84}}, /* Q ==10 : 62-69% */ + {{1177,128}, {2379, 87}, {4785, 88}}, /* Q ==11 : 69-75% */ + {{1242,128}, {2415, 93}, {5155, 84}}, /* Q ==12 : 75-81% */ + {{1349,128}, {2644,106}, {5260,106}}, /* Q ==13 : 81-87% */ + {{1455,128}, {2422,124}, {4174,124}}, /* Q ==14 : 87-93% */ + {{ 722,128}, {1891,145}, {1936,146}}, /* Q ==15 : 93-99% */ +}; +#endif + +/** HUF_selectDecoder() : + * Tells which decoder is likely to decode faster, + * based on a set of pre-computed metrics. + * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 . + * Assumption : 0 < dstSize <= 128 KB */ +U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize) +{ + assert(dstSize > 0); + assert(dstSize <= 128*1024); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)dstSize; + (void)cSrcSize; + return 0; +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)dstSize; + (void)cSrcSize; + return 1; +#else + /* decoder timing evaluation */ + { U32 const Q = (cSrcSize >= dstSize) ? 15 : (U32)(cSrcSize * 16 / dstSize); /* Q < 16 */ + U32 const D256 = (U32)(dstSize >> 8); + U32 const DTime0 = algoTime[Q][0].tableTime + (algoTime[Q][0].decode256Time * D256); + U32 DTime1 = algoTime[Q][1].tableTime + (algoTime[Q][1].decode256Time * D256); + DTime1 += DTime1 >> 3; /* advantage to algorithm using less memory, to reduce cache eviction */ + return DTime1 < DTime0; + } +#endif +} + + +typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); + +size_t HUF_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ +#if !defined(HUF_FORCE_DECOMPRESS_X1) && !defined(HUF_FORCE_DECOMPRESS_X2) + static const decompressionAlgo decompress[2] = { HUF_decompress4X1, HUF_decompress4X2 }; +#endif + + /* validation checks */ + if (dstSize == 0) return ERROR(dstSize_tooSmall); + if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */ + if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */ + if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */ + + { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)algoNb; + assert(algoNb == 0); + return HUF_decompress4X1(dst, dstSize, cSrc, cSrcSize); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)algoNb; + assert(algoNb == 1); + return HUF_decompress4X2(dst, dstSize, cSrc, cSrcSize); +#else + return decompress[algoNb](dst, dstSize, cSrc, cSrcSize); +#endif + } +} + +size_t HUF_decompress4X_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ + /* validation checks */ + if (dstSize == 0) return ERROR(dstSize_tooSmall); + if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */ + if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */ + if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */ + + { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)algoNb; + assert(algoNb == 0); + return HUF_decompress4X1_DCtx(dctx, dst, dstSize, cSrc, cSrcSize); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)algoNb; + assert(algoNb == 1); + return HUF_decompress4X2_DCtx(dctx, dst, dstSize, cSrc, cSrcSize); +#else + return algoNb ? HUF_decompress4X2_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) : + HUF_decompress4X1_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) ; +#endif + } +} + +size_t HUF_decompress4X_hufOnly(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ + U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; + return HUF_decompress4X_hufOnly_wksp(dctx, dst, dstSize, cSrc, cSrcSize, + workSpace, sizeof(workSpace)); +} + + +size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst, + size_t dstSize, const void* cSrc, + size_t cSrcSize, void* workSpace, + size_t wkspSize) +{ + /* validation checks */ + if (dstSize == 0) return ERROR(dstSize_tooSmall); + if (cSrcSize == 0) return ERROR(corruption_detected); + + { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)algoNb; + assert(algoNb == 0); + return HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)algoNb; + assert(algoNb == 1); + return HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize); +#else + return algoNb ? HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, + cSrcSize, workSpace, wkspSize): + HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize); +#endif + } +} + +size_t HUF_decompress1X_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + void* workSpace, size_t wkspSize) +{ + /* validation checks */ + if (dstSize == 0) return ERROR(dstSize_tooSmall); + if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */ + if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */ + if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */ + + { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)algoNb; + assert(algoNb == 0); + return HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc, + cSrcSize, workSpace, wkspSize); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)algoNb; + assert(algoNb == 1); + return HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc, + cSrcSize, workSpace, wkspSize); +#else + return algoNb ? HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc, + cSrcSize, workSpace, wkspSize): + HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc, + cSrcSize, workSpace, wkspSize); +#endif + } +} + +size_t HUF_decompress1X_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize) +{ + U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; + return HUF_decompress1X_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, + workSpace, sizeof(workSpace)); +} + + +size_t HUF_decompress1X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2) +{ + DTableDesc const dtd = HUF_getDTableDesc(DTable); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)dtd; + assert(dtd.tableType == 0); + return HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)dtd; + assert(dtd.tableType == 1); + return HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2); +#else + return dtd.tableType ? HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2) : + HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2); +#endif +} + +#ifndef HUF_FORCE_DECOMPRESS_X2 +size_t HUF_decompress1X1_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2) +{ + const BYTE* ip = (const BYTE*) cSrc; + + size_t const hSize = HUF_readDTableX1_wksp(dctx, cSrc, cSrcSize, workSpace, wkspSize); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; cSrcSize -= hSize; + + return HUF_decompress1X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, bmi2); +} +#endif + +size_t HUF_decompress4X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2) +{ + DTableDesc const dtd = HUF_getDTableDesc(DTable); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)dtd; + assert(dtd.tableType == 0); + return HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)dtd; + assert(dtd.tableType == 1); + return HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2); +#else + return dtd.tableType ? HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2) : + HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2); +#endif +} + +size_t HUF_decompress4X_hufOnly_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2) +{ + /* validation checks */ + if (dstSize == 0) return ERROR(dstSize_tooSmall); + if (cSrcSize == 0) return ERROR(corruption_detected); + + { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize); +#if defined(HUF_FORCE_DECOMPRESS_X1) + (void)algoNb; + assert(algoNb == 0); + return HUF_decompress4X1_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2); +#elif defined(HUF_FORCE_DECOMPRESS_X2) + (void)algoNb; + assert(algoNb == 1); + return HUF_decompress4X2_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2); +#else + return algoNb ? HUF_decompress4X2_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2) : + HUF_decompress4X1_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2); +#endif + } +} +/**** ended inlining decompress/huf_decompress.c ****/ +/**** start inlining decompress/zstd_ddict.c ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* zstd_ddict.c : + * concentrates all logic that needs to know the internals of ZSTD_DDict object */ + +/*-******************************************************* +* Dependencies +*********************************************************/ +/**** start inlining ../common/cpu.h ****/ +/* + * Copyright (c) 2018-2020, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_COMMON_CPU_H +#define ZSTD_COMMON_CPU_H + +/** + * Implementation taken from folly/CpuId.h + * https://github.com/facebook/folly/blob/master/folly/CpuId.h + */ + + +/**** skipping file: mem.h ****/ + +#ifdef _MSC_VER +#include +#endif + +typedef struct { + U32 f1c; + U32 f1d; + U32 f7b; + U32 f7c; +} ZSTD_cpuid_t; + +MEM_STATIC ZSTD_cpuid_t ZSTD_cpuid(void) { + U32 f1c = 0; + U32 f1d = 0; + U32 f7b = 0; + U32 f7c = 0; +#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) + int reg[4]; + __cpuid((int*)reg, 0); + { + int const n = reg[0]; + if (n >= 1) { + __cpuid((int*)reg, 1); + f1c = (U32)reg[2]; + f1d = (U32)reg[3]; + } + if (n >= 7) { + __cpuidex((int*)reg, 7, 0); + f7b = (U32)reg[1]; + f7c = (U32)reg[2]; + } + } +#elif defined(__i386__) && defined(__PIC__) && !defined(__clang__) && defined(__GNUC__) + /* The following block like the normal cpuid branch below, but gcc + * reserves ebx for use of its pic register so we must specially + * handle the save and restore to avoid clobbering the register + */ + U32 n; + __asm__( + "pushl %%ebx\n\t" + "cpuid\n\t" + "popl %%ebx\n\t" + : "=a"(n) + : "a"(0) + : "ecx", "edx"); + if (n >= 1) { + U32 f1a; + __asm__( + "pushl %%ebx\n\t" + "cpuid\n\t" + "popl %%ebx\n\t" + : "=a"(f1a), "=c"(f1c), "=d"(f1d) + : "a"(1)); + } + if (n >= 7) { + __asm__( + "pushl %%ebx\n\t" + "cpuid\n\t" + "movl %%ebx, %%eax\n\t" + "popl %%ebx" + : "=a"(f7b), "=c"(f7c) + : "a"(7), "c"(0) + : "edx"); + } +#elif defined(__x86_64__) || defined(_M_X64) || defined(__i386__) + U32 n; + __asm__("cpuid" : "=a"(n) : "a"(0) : "ebx", "ecx", "edx"); + if (n >= 1) { + U32 f1a; + __asm__("cpuid" : "=a"(f1a), "=c"(f1c), "=d"(f1d) : "a"(1) : "ebx"); + } + if (n >= 7) { + U32 f7a; + __asm__("cpuid" + : "=a"(f7a), "=b"(f7b), "=c"(f7c) + : "a"(7), "c"(0) + : "edx"); + } +#endif + { + ZSTD_cpuid_t cpuid; + cpuid.f1c = f1c; + cpuid.f1d = f1d; + cpuid.f7b = f7b; + cpuid.f7c = f7c; + return cpuid; + } +} + +#define X(name, r, bit) \ + MEM_STATIC int ZSTD_cpuid_##name(ZSTD_cpuid_t const cpuid) { \ + return ((cpuid.r) & (1U << bit)) != 0; \ + } + +/* cpuid(1): Processor Info and Feature Bits. */ +#define C(name, bit) X(name, f1c, bit) + C(sse3, 0) + C(pclmuldq, 1) + C(dtes64, 2) + C(monitor, 3) + C(dscpl, 4) + C(vmx, 5) + C(smx, 6) + C(eist, 7) + C(tm2, 8) + C(ssse3, 9) + C(cnxtid, 10) + C(fma, 12) + C(cx16, 13) + C(xtpr, 14) + C(pdcm, 15) + C(pcid, 17) + C(dca, 18) + C(sse41, 19) + C(sse42, 20) + C(x2apic, 21) + C(movbe, 22) + C(popcnt, 23) + C(tscdeadline, 24) + C(aes, 25) + C(xsave, 26) + C(osxsave, 27) + C(avx, 28) + C(f16c, 29) + C(rdrand, 30) +#undef C +#define D(name, bit) X(name, f1d, bit) + D(fpu, 0) + D(vme, 1) + D(de, 2) + D(pse, 3) + D(tsc, 4) + D(msr, 5) + D(pae, 6) + D(mce, 7) + D(cx8, 8) + D(apic, 9) + D(sep, 11) + D(mtrr, 12) + D(pge, 13) + D(mca, 14) + D(cmov, 15) + D(pat, 16) + D(pse36, 17) + D(psn, 18) + D(clfsh, 19) + D(ds, 21) + D(acpi, 22) + D(mmx, 23) + D(fxsr, 24) + D(sse, 25) + D(sse2, 26) + D(ss, 27) + D(htt, 28) + D(tm, 29) + D(pbe, 31) +#undef D + +/* cpuid(7): Extended Features. */ +#define B(name, bit) X(name, f7b, bit) + B(bmi1, 3) + B(hle, 4) + B(avx2, 5) + B(smep, 7) + B(bmi2, 8) + B(erms, 9) + B(invpcid, 10) + B(rtm, 11) + B(mpx, 14) + B(avx512f, 16) + B(avx512dq, 17) + B(rdseed, 18) + B(adx, 19) + B(smap, 20) + B(avx512ifma, 21) + B(pcommit, 22) + B(clflushopt, 23) + B(clwb, 24) + B(avx512pf, 26) + B(avx512er, 27) + B(avx512cd, 28) + B(sha, 29) + B(avx512bw, 30) + B(avx512vl, 31) +#undef B +#define C(name, bit) X(name, f7c, bit) + C(prefetchwt1, 0) + C(avx512vbmi, 1) +#undef C + +#undef X + +#endif /* ZSTD_COMMON_CPU_H */ +/**** ended inlining ../common/cpu.h ****/ +/**** skipping file: ../common/mem.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: ../common/fse.h ****/ +#define HUF_STATIC_LINKING_ONLY +/**** skipping file: ../common/huf.h ****/ +/**** start inlining zstd_decompress_internal.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + +/* zstd_decompress_internal: + * objects and definitions shared within lib/decompress modules */ + + #ifndef ZSTD_DECOMPRESS_INTERNAL_H + #define ZSTD_DECOMPRESS_INTERNAL_H + + +/*-******************************************************* + * Dependencies + *********************************************************/ +/**** skipping file: ../common/mem.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ + + + +/*-******************************************************* + * Constants + *********************************************************/ +static const U32 LL_base[MaxLL+1] = { + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 18, 20, 22, 24, 28, 32, 40, + 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, + 0x2000, 0x4000, 0x8000, 0x10000 }; + +static const U32 OF_base[MaxOff+1] = { + 0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D, + 0xFD, 0x1FD, 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD, + 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD, + 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD, 0x1FFFFFFD, 0x3FFFFFFD, 0x7FFFFFFD }; + +static const U32 OF_bits[MaxOff+1] = { + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31 }; + +static const U32 ML_base[MaxML+1] = { + 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 30, 31, 32, 33, 34, + 35, 37, 39, 41, 43, 47, 51, 59, + 67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803, + 0x1003, 0x2003, 0x4003, 0x8003, 0x10003 }; + + +/*-******************************************************* + * Decompression types + *********************************************************/ + typedef struct { + U32 fastMode; + U32 tableLog; + } ZSTD_seqSymbol_header; + + typedef struct { + U16 nextState; + BYTE nbAdditionalBits; + BYTE nbBits; + U32 baseValue; + } ZSTD_seqSymbol; + + #define SEQSYMBOL_TABLE_SIZE(log) (1 + (1 << (log))) + +typedef struct { + ZSTD_seqSymbol LLTable[SEQSYMBOL_TABLE_SIZE(LLFSELog)]; /* Note : Space reserved for FSE Tables */ + ZSTD_seqSymbol OFTable[SEQSYMBOL_TABLE_SIZE(OffFSELog)]; /* is also used as temporary workspace while building hufTable during DDict creation */ + ZSTD_seqSymbol MLTable[SEQSYMBOL_TABLE_SIZE(MLFSELog)]; /* and therefore must be at least HUF_DECOMPRESS_WORKSPACE_SIZE large */ + HUF_DTable hufTable[HUF_DTABLE_SIZE(HufLog)]; /* can accommodate HUF_decompress4X */ + U32 rep[ZSTD_REP_NUM]; +} ZSTD_entropyDTables_t; + +typedef enum { ZSTDds_getFrameHeaderSize, ZSTDds_decodeFrameHeader, + ZSTDds_decodeBlockHeader, ZSTDds_decompressBlock, + ZSTDds_decompressLastBlock, ZSTDds_checkChecksum, + ZSTDds_decodeSkippableHeader, ZSTDds_skipFrame } ZSTD_dStage; + +typedef enum { zdss_init=0, zdss_loadHeader, + zdss_read, zdss_load, zdss_flush } ZSTD_dStreamStage; + +typedef enum { + ZSTD_use_indefinitely = -1, /* Use the dictionary indefinitely */ + ZSTD_dont_use = 0, /* Do not use the dictionary (if one exists free it) */ + ZSTD_use_once = 1 /* Use the dictionary once and set to ZSTD_dont_use */ +} ZSTD_dictUses_e; + +typedef enum { + ZSTD_obm_buffered = 0, /* Buffer the output */ + ZSTD_obm_stable = 1 /* ZSTD_outBuffer is stable */ +} ZSTD_outBufferMode_e; + +struct ZSTD_DCtx_s +{ + const ZSTD_seqSymbol* LLTptr; + const ZSTD_seqSymbol* MLTptr; + const ZSTD_seqSymbol* OFTptr; + const HUF_DTable* HUFptr; + ZSTD_entropyDTables_t entropy; + U32 workspace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; /* space needed when building huffman tables */ + const void* previousDstEnd; /* detect continuity */ + const void* prefixStart; /* start of current segment */ + const void* virtualStart; /* virtual start of previous segment if it was just before current one */ + const void* dictEnd; /* end of previous segment */ + size_t expected; + ZSTD_frameHeader fParams; + U64 decodedSize; + blockType_e bType; /* used in ZSTD_decompressContinue(), store blockType between block header decoding and block decompression stages */ + ZSTD_dStage stage; + U32 litEntropy; + U32 fseEntropy; + XXH64_state_t xxhState; + size_t headerSize; + ZSTD_format_e format; + const BYTE* litPtr; + ZSTD_customMem customMem; + size_t litSize; + size_t rleSize; + size_t staticSize; + int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */ + + /* dictionary */ + ZSTD_DDict* ddictLocal; + const ZSTD_DDict* ddict; /* set by ZSTD_initDStream_usingDDict(), or ZSTD_DCtx_refDDict() */ + U32 dictID; + int ddictIsCold; /* if == 1 : dictionary is "new" for working context, and presumed "cold" (not in cpu cache) */ + ZSTD_dictUses_e dictUses; + + /* streaming */ + ZSTD_dStreamStage streamStage; + char* inBuff; + size_t inBuffSize; + size_t inPos; + size_t maxWindowSize; + char* outBuff; + size_t outBuffSize; + size_t outStart; + size_t outEnd; + size_t lhSize; + void* legacyContext; + U32 previousLegacyVersion; + U32 legacyVersion; + U32 hostageByte; + int noForwardProgress; + ZSTD_outBufferMode_e outBufferMode; + ZSTD_outBuffer expectedOutBuffer; + + /* workspace */ + BYTE litBuffer[ZSTD_BLOCKSIZE_MAX + WILDCOPY_OVERLENGTH]; + BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX]; + + size_t oversizedDuration; + +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + void const* dictContentBeginForFuzzing; + void const* dictContentEndForFuzzing; +#endif +}; /* typedef'd to ZSTD_DCtx within "zstd.h" */ + + +/*-******************************************************* + * Shared internal functions + *********************************************************/ + +/*! ZSTD_loadDEntropy() : + * dict : must point at beginning of a valid zstd dictionary. + * @return : size of dictionary header (size of magic number + dict ID + entropy tables) */ +size_t ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy, + const void* const dict, size_t const dictSize); + +/*! ZSTD_checkContinuity() : + * check if next `dst` follows previous position, where decompression ended. + * If yes, do nothing (continue on current segment). + * If not, classify previous segment as "external dictionary", and start a new segment. + * This function cannot fail. */ +void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst); + + +#endif /* ZSTD_DECOMPRESS_INTERNAL_H */ +/**** ended inlining zstd_decompress_internal.h ****/ +/**** start inlining zstd_ddict.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + +#ifndef ZSTD_DDICT_H +#define ZSTD_DDICT_H + +/*-******************************************************* + * Dependencies + *********************************************************/ +#include /* size_t */ +/**** skipping file: ../zstd.h ****/ + + +/*-******************************************************* + * Interface + *********************************************************/ + +/* note: several prototypes are already published in `zstd.h` : + * ZSTD_createDDict() + * ZSTD_createDDict_byReference() + * ZSTD_createDDict_advanced() + * ZSTD_freeDDict() + * ZSTD_initStaticDDict() + * ZSTD_sizeof_DDict() + * ZSTD_estimateDDictSize() + * ZSTD_getDictID_fromDict() + */ + +const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict); +size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict); + +void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); + + + +#endif /* ZSTD_DDICT_H */ +/**** ended inlining zstd_ddict.h ****/ + +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) +/**** start inlining ../legacy/zstd_legacy.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_LEGACY_H +#define ZSTD_LEGACY_H + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +/**** skipping file: ../common/mem.h ****/ +/**** skipping file: ../common/error_private.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ + +#if !defined (ZSTD_LEGACY_SUPPORT) || (ZSTD_LEGACY_SUPPORT == 0) +# undef ZSTD_LEGACY_SUPPORT +# define ZSTD_LEGACY_SUPPORT 8 +#endif + +#if (ZSTD_LEGACY_SUPPORT <= 1) +/**** start inlining zstd_v01.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_V01_H_28739879432 +#define ZSTD_V01_H_28739879432 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include /* size_t */ + + +/* ************************************* +* Simple one-step function +***************************************/ +/** +ZSTDv01_decompress() : decompress ZSTD frames compliant with v0.1.x format + compressedSize : is the exact source size + maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. + It must be equal or larger than originalSize, otherwise decompression will fail. + return : the number of bytes decompressed into destination buffer (originalSize) + or an errorCode if it fails (which can be tested using ZSTDv01_isError()) +*/ +size_t ZSTDv01_decompress( void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + /** + ZSTDv01_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.1.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ +void ZSTDv01_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/** +ZSTDv01_isError() : tells if the result of ZSTDv01_decompress() is an error +*/ +unsigned ZSTDv01_isError(size_t code); + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTDv01_Dctx_s ZSTDv01_Dctx; +ZSTDv01_Dctx* ZSTDv01_createDCtx(void); +size_t ZSTDv01_freeDCtx(ZSTDv01_Dctx* dctx); + +size_t ZSTDv01_decompressDCtx(void* ctx, + void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + +/* ************************************* +* Streaming functions +***************************************/ +size_t ZSTDv01_resetDCtx(ZSTDv01_Dctx* dctx); + +size_t ZSTDv01_nextSrcSizeToDecompress(ZSTDv01_Dctx* dctx); +size_t ZSTDv01_decompressContinue(ZSTDv01_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +/** + Use above functions alternatively. + ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. + Result is the number of bytes regenerated within 'dst'. + It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. +*/ + +/* ************************************* +* Prefix - version detection +***************************************/ +#define ZSTDv01_magicNumber 0xFD2FB51E /* Big Endian version */ +#define ZSTDv01_magicNumberLE 0x1EB52FFD /* Little Endian version */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_V01_H_28739879432 */ +/**** ended inlining zstd_v01.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 2) +/**** start inlining zstd_v02.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_V02_H_4174539423 +#define ZSTD_V02_H_4174539423 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include /* size_t */ + + +/* ************************************* +* Simple one-step function +***************************************/ +/** +ZSTDv02_decompress() : decompress ZSTD frames compliant with v0.2.x format + compressedSize : is the exact source size + maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. + It must be equal or larger than originalSize, otherwise decompression will fail. + return : the number of bytes decompressed into destination buffer (originalSize) + or an errorCode if it fails (which can be tested using ZSTDv01_isError()) +*/ +size_t ZSTDv02_decompress( void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + /** + ZSTDv02_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.2.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ +void ZSTDv02_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/** +ZSTDv02_isError() : tells if the result of ZSTDv02_decompress() is an error +*/ +unsigned ZSTDv02_isError(size_t code); + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTDv02_Dctx_s ZSTDv02_Dctx; +ZSTDv02_Dctx* ZSTDv02_createDCtx(void); +size_t ZSTDv02_freeDCtx(ZSTDv02_Dctx* dctx); + +size_t ZSTDv02_decompressDCtx(void* ctx, + void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + +/* ************************************* +* Streaming functions +***************************************/ +size_t ZSTDv02_resetDCtx(ZSTDv02_Dctx* dctx); + +size_t ZSTDv02_nextSrcSizeToDecompress(ZSTDv02_Dctx* dctx); +size_t ZSTDv02_decompressContinue(ZSTDv02_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +/** + Use above functions alternatively. + ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. + Result is the number of bytes regenerated within 'dst'. + It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. +*/ + +/* ************************************* +* Prefix - version detection +***************************************/ +#define ZSTDv02_magicNumber 0xFD2FB522 /* v0.2 */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_V02_H_4174539423 */ +/**** ended inlining zstd_v02.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 3) +/**** start inlining zstd_v03.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_V03_H_298734209782 +#define ZSTD_V03_H_298734209782 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include /* size_t */ + + +/* ************************************* +* Simple one-step function +***************************************/ +/** +ZSTDv03_decompress() : decompress ZSTD frames compliant with v0.3.x format + compressedSize : is the exact source size + maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. + It must be equal or larger than originalSize, otherwise decompression will fail. + return : the number of bytes decompressed into destination buffer (originalSize) + or an errorCode if it fails (which can be tested using ZSTDv01_isError()) +*/ +size_t ZSTDv03_decompress( void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + /** + ZSTDv03_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.3.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ + void ZSTDv03_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + + /** +ZSTDv03_isError() : tells if the result of ZSTDv03_decompress() is an error +*/ +unsigned ZSTDv03_isError(size_t code); + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTDv03_Dctx_s ZSTDv03_Dctx; +ZSTDv03_Dctx* ZSTDv03_createDCtx(void); +size_t ZSTDv03_freeDCtx(ZSTDv03_Dctx* dctx); + +size_t ZSTDv03_decompressDCtx(void* ctx, + void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + +/* ************************************* +* Streaming functions +***************************************/ +size_t ZSTDv03_resetDCtx(ZSTDv03_Dctx* dctx); + +size_t ZSTDv03_nextSrcSizeToDecompress(ZSTDv03_Dctx* dctx); +size_t ZSTDv03_decompressContinue(ZSTDv03_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +/** + Use above functions alternatively. + ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. + Result is the number of bytes regenerated within 'dst'. + It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. +*/ + +/* ************************************* +* Prefix - version detection +***************************************/ +#define ZSTDv03_magicNumber 0xFD2FB523 /* v0.3 */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_V03_H_298734209782 */ +/**** ended inlining zstd_v03.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 4) +/**** start inlining zstd_v04.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_V04_H_91868324769238 +#define ZSTD_V04_H_91868324769238 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include /* size_t */ + + +/* ************************************* +* Simple one-step function +***************************************/ +/** +ZSTDv04_decompress() : decompress ZSTD frames compliant with v0.4.x format + compressedSize : is the exact source size + maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated. + It must be equal or larger than originalSize, otherwise decompression will fail. + return : the number of bytes decompressed into destination buffer (originalSize) + or an errorCode if it fails (which can be tested using ZSTDv01_isError()) +*/ +size_t ZSTDv04_decompress( void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + /** + ZSTDv04_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.4.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ + void ZSTDv04_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/** +ZSTDv04_isError() : tells if the result of ZSTDv04_decompress() is an error +*/ +unsigned ZSTDv04_isError(size_t code); + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTDv04_Dctx_s ZSTDv04_Dctx; +ZSTDv04_Dctx* ZSTDv04_createDCtx(void); +size_t ZSTDv04_freeDCtx(ZSTDv04_Dctx* dctx); + +size_t ZSTDv04_decompressDCtx(ZSTDv04_Dctx* dctx, + void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize); + + +/* ************************************* +* Direct Streaming +***************************************/ +size_t ZSTDv04_resetDCtx(ZSTDv04_Dctx* dctx); + +size_t ZSTDv04_nextSrcSizeToDecompress(ZSTDv04_Dctx* dctx); +size_t ZSTDv04_decompressContinue(ZSTDv04_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +/** + Use above functions alternatively. + ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. + Result is the number of bytes regenerated within 'dst'. + It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. +*/ + + +/* ************************************* +* Buffered Streaming +***************************************/ +typedef struct ZBUFFv04_DCtx_s ZBUFFv04_DCtx; +ZBUFFv04_DCtx* ZBUFFv04_createDCtx(void); +size_t ZBUFFv04_freeDCtx(ZBUFFv04_DCtx* dctx); + +size_t ZBUFFv04_decompressInit(ZBUFFv04_DCtx* dctx); +size_t ZBUFFv04_decompressWithDictionary(ZBUFFv04_DCtx* dctx, const void* dict, size_t dictSize); + +size_t ZBUFFv04_decompressContinue(ZBUFFv04_DCtx* dctx, void* dst, size_t* maxDstSizePtr, const void* src, size_t* srcSizePtr); + +/** ************************************************ +* Streaming decompression +* +* A ZBUFF_DCtx object is required to track streaming operation. +* Use ZBUFF_createDCtx() and ZBUFF_freeDCtx() to create/release resources. +* Use ZBUFF_decompressInit() to start a new decompression operation. +* ZBUFF_DCtx objects can be reused multiple times. +* +* Optionally, a reference to a static dictionary can be set, using ZBUFF_decompressWithDictionary() +* It must be the same content as the one set during compression phase. +* Dictionary content must remain accessible during the decompression process. +* +* Use ZBUFF_decompressContinue() repetitively to consume your input. +* *srcSizePtr and *maxDstSizePtr can be any size. +* The function will report how many bytes were read or written by modifying *srcSizePtr and *maxDstSizePtr. +* Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. +* The content of dst will be overwritten (up to *maxDstSizePtr) at each function call, so save its content if it matters or change dst. +* @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to improve latency) +* or 0 when a frame is completely decoded +* or an error code, which can be tested using ZBUFF_isError(). +* +* Hint : recommended buffer sizes (not compulsory) : ZBUFF_recommendedDInSize / ZBUFF_recommendedDOutSize +* output : ZBUFF_recommendedDOutSize==128 KB block size is the internal unit, it ensures it's always possible to write a full block when it's decoded. +* input : ZBUFF_recommendedDInSize==128Kb+3; just follow indications from ZBUFF_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . +* **************************************************/ +unsigned ZBUFFv04_isError(size_t errorCode); +const char* ZBUFFv04_getErrorName(size_t errorCode); + + +/** The below functions provide recommended buffer sizes for Compression or Decompression operations. +* These sizes are not compulsory, they just tend to offer better latency */ +size_t ZBUFFv04_recommendedDInSize(void); +size_t ZBUFFv04_recommendedDOutSize(void); + + +/* ************************************* +* Prefix - version detection +***************************************/ +#define ZSTDv04_magicNumber 0xFD2FB524 /* v0.4 */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_V04_H_91868324769238 */ +/**** ended inlining zstd_v04.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) +/**** start inlining zstd_v05.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTDv05_H +#define ZSTDv05_H + +#if defined (__cplusplus) +extern "C" { +#endif + +/*-************************************* +* Dependencies +***************************************/ +#include /* size_t */ +/**** skipping file: ../common/mem.h ****/ + + +/* ************************************* +* Simple functions +***************************************/ +/*! ZSTDv05_decompress() : + `compressedSize` : is the _exact_ size of the compressed blob, otherwise decompression will fail. + `dstCapacity` must be large enough, equal or larger than originalSize. + @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + or an errorCode if it fails (which can be tested using ZSTDv05_isError()) */ +size_t ZSTDv05_decompress( void* dst, size_t dstCapacity, + const void* src, size_t compressedSize); + + /** + ZSTDv05_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.5.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. + */ +void ZSTDv05_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/* ************************************* +* Helper functions +***************************************/ +/* Error Management */ +unsigned ZSTDv05_isError(size_t code); /*!< tells if a `size_t` function result is an error code */ +const char* ZSTDv05_getErrorName(size_t code); /*!< provides readable string for an error code */ + + +/* ************************************* +* Explicit memory management +***************************************/ +/** Decompression context */ +typedef struct ZSTDv05_DCtx_s ZSTDv05_DCtx; +ZSTDv05_DCtx* ZSTDv05_createDCtx(void); +size_t ZSTDv05_freeDCtx(ZSTDv05_DCtx* dctx); /*!< @return : errorCode */ + +/** ZSTDv05_decompressDCtx() : +* Same as ZSTDv05_decompress(), but requires an already allocated ZSTDv05_DCtx (see ZSTDv05_createDCtx()) */ +size_t ZSTDv05_decompressDCtx(ZSTDv05_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + +/*-*********************** +* Simple Dictionary API +*************************/ +/*! ZSTDv05_decompress_usingDict() : +* Decompression using a pre-defined Dictionary content (see dictBuilder). +* Dictionary must be identical to the one used during compression, otherwise regenerated data will be corrupted. +* Note : dict can be NULL, in which case, it's equivalent to ZSTDv05_decompressDCtx() */ +size_t ZSTDv05_decompress_usingDict(ZSTDv05_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize); + +/*-************************ +* Advanced Streaming API +***************************/ +typedef enum { ZSTDv05_fast, ZSTDv05_greedy, ZSTDv05_lazy, ZSTDv05_lazy2, ZSTDv05_btlazy2, ZSTDv05_opt, ZSTDv05_btopt } ZSTDv05_strategy; +typedef struct { + U64 srcSize; + U32 windowLog; /* the only useful information to retrieve */ + U32 contentLog; U32 hashLog; U32 searchLog; U32 searchLength; U32 targetLength; ZSTDv05_strategy strategy; +} ZSTDv05_parameters; +size_t ZSTDv05_getFrameParams(ZSTDv05_parameters* params, const void* src, size_t srcSize); + +size_t ZSTDv05_decompressBegin_usingDict(ZSTDv05_DCtx* dctx, const void* dict, size_t dictSize); +void ZSTDv05_copyDCtx(ZSTDv05_DCtx* dstDCtx, const ZSTDv05_DCtx* srcDCtx); +size_t ZSTDv05_nextSrcSizeToDecompress(ZSTDv05_DCtx* dctx); +size_t ZSTDv05_decompressContinue(ZSTDv05_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + +/*-*********************** +* ZBUFF API +*************************/ +typedef struct ZBUFFv05_DCtx_s ZBUFFv05_DCtx; +ZBUFFv05_DCtx* ZBUFFv05_createDCtx(void); +size_t ZBUFFv05_freeDCtx(ZBUFFv05_DCtx* dctx); + +size_t ZBUFFv05_decompressInit(ZBUFFv05_DCtx* dctx); +size_t ZBUFFv05_decompressInitDictionary(ZBUFFv05_DCtx* dctx, const void* dict, size_t dictSize); + +size_t ZBUFFv05_decompressContinue(ZBUFFv05_DCtx* dctx, + void* dst, size_t* dstCapacityPtr, + const void* src, size_t* srcSizePtr); + +/*-*************************************************************************** +* Streaming decompression +* +* A ZBUFFv05_DCtx object is required to track streaming operations. +* Use ZBUFFv05_createDCtx() and ZBUFFv05_freeDCtx() to create/release resources. +* Use ZBUFFv05_decompressInit() to start a new decompression operation, +* or ZBUFFv05_decompressInitDictionary() if decompression requires a dictionary. +* Note that ZBUFFv05_DCtx objects can be reused multiple times. +* +* Use ZBUFFv05_decompressContinue() repetitively to consume your input. +* *srcSizePtr and *dstCapacityPtr can be any size. +* The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr. +* Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. +* The content of @dst will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters or change @dst. +* @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency) +* or 0 when a frame is completely decoded +* or an error code, which can be tested using ZBUFFv05_isError(). +* +* Hint : recommended buffer sizes (not compulsory) : ZBUFFv05_recommendedDInSize() / ZBUFFv05_recommendedDOutSize() +* output : ZBUFFv05_recommendedDOutSize==128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded. +* input : ZBUFFv05_recommendedDInSize==128Kb+3; just follow indications from ZBUFFv05_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . +* *******************************************************************************/ + + +/* ************************************* +* Tool functions +***************************************/ +unsigned ZBUFFv05_isError(size_t errorCode); +const char* ZBUFFv05_getErrorName(size_t errorCode); + +/** Functions below provide recommended buffer sizes for Compression or Decompression operations. +* These sizes are just hints, and tend to offer better latency */ +size_t ZBUFFv05_recommendedDInSize(void); +size_t ZBUFFv05_recommendedDOutSize(void); + + + +/*-************************************* +* Constants +***************************************/ +#define ZSTDv05_MAGICNUMBER 0xFD2FB525 /* v0.5 */ + + + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTDv0505_H */ +/**** ended inlining zstd_v05.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) +/**** start inlining zstd_v06.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTDv06_H +#define ZSTDv06_H + +#if defined (__cplusplus) +extern "C" { +#endif + +/*====== Dependency ======*/ +#include /* size_t */ + + +/*====== Export for Windows ======*/ +/*! +* ZSTDv06_DLL_EXPORT : +* Enable exporting of functions when building a Windows DLL +*/ +#if defined(_WIN32) && defined(ZSTDv06_DLL_EXPORT) && (ZSTDv06_DLL_EXPORT==1) +# define ZSTDLIBv06_API __declspec(dllexport) +#else +# define ZSTDLIBv06_API +#endif + + +/* ************************************* +* Simple functions +***************************************/ +/*! ZSTDv06_decompress() : + `compressedSize` : is the _exact_ size of the compressed blob, otherwise decompression will fail. + `dstCapacity` must be large enough, equal or larger than originalSize. + @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + or an errorCode if it fails (which can be tested using ZSTDv06_isError()) */ +ZSTDLIBv06_API size_t ZSTDv06_decompress( void* dst, size_t dstCapacity, + const void* src, size_t compressedSize); + +/** +ZSTDv06_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.6.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. +*/ +void ZSTDv06_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/* ************************************* +* Helper functions +***************************************/ +ZSTDLIBv06_API size_t ZSTDv06_compressBound(size_t srcSize); /*!< maximum compressed size (worst case scenario) */ + +/* Error Management */ +ZSTDLIBv06_API unsigned ZSTDv06_isError(size_t code); /*!< tells if a `size_t` function result is an error code */ +ZSTDLIBv06_API const char* ZSTDv06_getErrorName(size_t code); /*!< provides readable string for an error code */ + + +/* ************************************* +* Explicit memory management +***************************************/ +/** Decompression context */ +typedef struct ZSTDv06_DCtx_s ZSTDv06_DCtx; +ZSTDLIBv06_API ZSTDv06_DCtx* ZSTDv06_createDCtx(void); +ZSTDLIBv06_API size_t ZSTDv06_freeDCtx(ZSTDv06_DCtx* dctx); /*!< @return : errorCode */ + +/** ZSTDv06_decompressDCtx() : +* Same as ZSTDv06_decompress(), but requires an already allocated ZSTDv06_DCtx (see ZSTDv06_createDCtx()) */ +ZSTDLIBv06_API size_t ZSTDv06_decompressDCtx(ZSTDv06_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + +/*-*********************** +* Dictionary API +*************************/ +/*! ZSTDv06_decompress_usingDict() : +* Decompression using a pre-defined Dictionary content (see dictBuilder). +* Dictionary must be identical to the one used during compression, otherwise regenerated data will be corrupted. +* Note : dict can be NULL, in which case, it's equivalent to ZSTDv06_decompressDCtx() */ +ZSTDLIBv06_API size_t ZSTDv06_decompress_usingDict(ZSTDv06_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize); + + +/*-************************ +* Advanced Streaming API +***************************/ +struct ZSTDv06_frameParams_s { unsigned long long frameContentSize; unsigned windowLog; }; +typedef struct ZSTDv06_frameParams_s ZSTDv06_frameParams; + +ZSTDLIBv06_API size_t ZSTDv06_getFrameParams(ZSTDv06_frameParams* fparamsPtr, const void* src, size_t srcSize); /**< doesn't consume input */ +ZSTDLIBv06_API size_t ZSTDv06_decompressBegin_usingDict(ZSTDv06_DCtx* dctx, const void* dict, size_t dictSize); +ZSTDLIBv06_API void ZSTDv06_copyDCtx(ZSTDv06_DCtx* dctx, const ZSTDv06_DCtx* preparedDCtx); + +ZSTDLIBv06_API size_t ZSTDv06_nextSrcSizeToDecompress(ZSTDv06_DCtx* dctx); +ZSTDLIBv06_API size_t ZSTDv06_decompressContinue(ZSTDv06_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + + +/* ************************************* +* ZBUFF API +***************************************/ + +typedef struct ZBUFFv06_DCtx_s ZBUFFv06_DCtx; +ZSTDLIBv06_API ZBUFFv06_DCtx* ZBUFFv06_createDCtx(void); +ZSTDLIBv06_API size_t ZBUFFv06_freeDCtx(ZBUFFv06_DCtx* dctx); + +ZSTDLIBv06_API size_t ZBUFFv06_decompressInit(ZBUFFv06_DCtx* dctx); +ZSTDLIBv06_API size_t ZBUFFv06_decompressInitDictionary(ZBUFFv06_DCtx* dctx, const void* dict, size_t dictSize); + +ZSTDLIBv06_API size_t ZBUFFv06_decompressContinue(ZBUFFv06_DCtx* dctx, + void* dst, size_t* dstCapacityPtr, + const void* src, size_t* srcSizePtr); + +/*-*************************************************************************** +* Streaming decompression howto +* +* A ZBUFFv06_DCtx object is required to track streaming operations. +* Use ZBUFFv06_createDCtx() and ZBUFFv06_freeDCtx() to create/release resources. +* Use ZBUFFv06_decompressInit() to start a new decompression operation, +* or ZBUFFv06_decompressInitDictionary() if decompression requires a dictionary. +* Note that ZBUFFv06_DCtx objects can be re-init multiple times. +* +* Use ZBUFFv06_decompressContinue() repetitively to consume your input. +* *srcSizePtr and *dstCapacityPtr can be any size. +* The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr. +* Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. +* The content of `dst` will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change `dst`. +* @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency), +* or 0 when a frame is completely decoded, +* or an error code, which can be tested using ZBUFFv06_isError(). +* +* Hint : recommended buffer sizes (not compulsory) : ZBUFFv06_recommendedDInSize() and ZBUFFv06_recommendedDOutSize() +* output : ZBUFFv06_recommendedDOutSize== 128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded. +* input : ZBUFFv06_recommendedDInSize == 128KB + 3; +* just follow indications from ZBUFFv06_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . +* *******************************************************************************/ + + +/* ************************************* +* Tool functions +***************************************/ +ZSTDLIBv06_API unsigned ZBUFFv06_isError(size_t errorCode); +ZSTDLIBv06_API const char* ZBUFFv06_getErrorName(size_t errorCode); + +/** Functions below provide recommended buffer sizes for Compression or Decompression operations. +* These sizes are just hints, they tend to offer better latency */ +ZSTDLIBv06_API size_t ZBUFFv06_recommendedDInSize(void); +ZSTDLIBv06_API size_t ZBUFFv06_recommendedDOutSize(void); + + +/*-************************************* +* Constants +***************************************/ +#define ZSTDv06_MAGICNUMBER 0xFD2FB526 /* v0.6 */ + + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTDv06_BUFFERED_H */ +/**** ended inlining zstd_v06.h ****/ +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) +/**** start inlining zstd_v07.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTDv07_H_235446 +#define ZSTDv07_H_235446 + +#if defined (__cplusplus) +extern "C" { +#endif + +/*====== Dependency ======*/ +#include /* size_t */ + + +/*====== Export for Windows ======*/ +/*! +* ZSTDv07_DLL_EXPORT : +* Enable exporting of functions when building a Windows DLL +*/ +#if defined(_WIN32) && defined(ZSTDv07_DLL_EXPORT) && (ZSTDv07_DLL_EXPORT==1) +# define ZSTDLIBv07_API __declspec(dllexport) +#else +# define ZSTDLIBv07_API +#endif + + +/* ************************************* +* Simple API +***************************************/ +/*! ZSTDv07_getDecompressedSize() : +* @return : decompressed size if known, 0 otherwise. + note 1 : if `0`, follow up with ZSTDv07_getFrameParams() to know precise failure cause. + note 2 : decompressed size could be wrong or intentionally modified ! + always ensure results fit within application's authorized limits */ +unsigned long long ZSTDv07_getDecompressedSize(const void* src, size_t srcSize); + +/*! ZSTDv07_decompress() : + `compressedSize` : must be _exact_ size of compressed input, otherwise decompression will fail. + `dstCapacity` must be equal or larger than originalSize. + @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + or an errorCode if it fails (which can be tested using ZSTDv07_isError()) */ +ZSTDLIBv07_API size_t ZSTDv07_decompress( void* dst, size_t dstCapacity, + const void* src, size_t compressedSize); + +/** +ZSTDv07_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.7.x format + srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src' + cSize (output parameter) : the number of bytes that would be read to decompress this frame + or an error code if it fails (which can be tested using ZSTDv01_isError()) + dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame + or ZSTD_CONTENTSIZE_ERROR if an error occurs + + note : assumes `cSize` and `dBound` are _not_ NULL. +*/ +void ZSTDv07_findFrameSizeInfoLegacy(const void *src, size_t srcSize, + size_t* cSize, unsigned long long* dBound); + +/*====== Helper functions ======*/ +ZSTDLIBv07_API unsigned ZSTDv07_isError(size_t code); /*!< tells if a `size_t` function result is an error code */ +ZSTDLIBv07_API const char* ZSTDv07_getErrorName(size_t code); /*!< provides readable string from an error code */ + + +/*-************************************* +* Explicit memory management +***************************************/ +/** Decompression context */ +typedef struct ZSTDv07_DCtx_s ZSTDv07_DCtx; +ZSTDLIBv07_API ZSTDv07_DCtx* ZSTDv07_createDCtx(void); +ZSTDLIBv07_API size_t ZSTDv07_freeDCtx(ZSTDv07_DCtx* dctx); /*!< @return : errorCode */ + +/** ZSTDv07_decompressDCtx() : +* Same as ZSTDv07_decompress(), requires an allocated ZSTDv07_DCtx (see ZSTDv07_createDCtx()) */ +ZSTDLIBv07_API size_t ZSTDv07_decompressDCtx(ZSTDv07_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); + + +/*-************************ +* Simple dictionary API +***************************/ +/*! ZSTDv07_decompress_usingDict() : +* Decompression using a pre-defined Dictionary content (see dictBuilder). +* Dictionary must be identical to the one used during compression. +* Note : This function load the dictionary, resulting in a significant startup time */ +ZSTDLIBv07_API size_t ZSTDv07_decompress_usingDict(ZSTDv07_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict,size_t dictSize); + + +/*-************************** +* Advanced Dictionary API +****************************/ +/*! ZSTDv07_createDDict() : +* Create a digested dictionary, ready to start decompression operation without startup delay. +* `dict` can be released after creation */ +typedef struct ZSTDv07_DDict_s ZSTDv07_DDict; +ZSTDLIBv07_API ZSTDv07_DDict* ZSTDv07_createDDict(const void* dict, size_t dictSize); +ZSTDLIBv07_API size_t ZSTDv07_freeDDict(ZSTDv07_DDict* ddict); + +/*! ZSTDv07_decompress_usingDDict() : +* Decompression using a pre-digested Dictionary +* Faster startup than ZSTDv07_decompress_usingDict(), recommended when same dictionary is used multiple times. */ +ZSTDLIBv07_API size_t ZSTDv07_decompress_usingDDict(ZSTDv07_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTDv07_DDict* ddict); + +typedef struct { + unsigned long long frameContentSize; + unsigned windowSize; + unsigned dictID; + unsigned checksumFlag; +} ZSTDv07_frameParams; + +ZSTDLIBv07_API size_t ZSTDv07_getFrameParams(ZSTDv07_frameParams* fparamsPtr, const void* src, size_t srcSize); /**< doesn't consume input */ + + + + +/* ************************************* +* Streaming functions +***************************************/ +typedef struct ZBUFFv07_DCtx_s ZBUFFv07_DCtx; +ZSTDLIBv07_API ZBUFFv07_DCtx* ZBUFFv07_createDCtx(void); +ZSTDLIBv07_API size_t ZBUFFv07_freeDCtx(ZBUFFv07_DCtx* dctx); + +ZSTDLIBv07_API size_t ZBUFFv07_decompressInit(ZBUFFv07_DCtx* dctx); +ZSTDLIBv07_API size_t ZBUFFv07_decompressInitDictionary(ZBUFFv07_DCtx* dctx, const void* dict, size_t dictSize); + +ZSTDLIBv07_API size_t ZBUFFv07_decompressContinue(ZBUFFv07_DCtx* dctx, + void* dst, size_t* dstCapacityPtr, + const void* src, size_t* srcSizePtr); + +/*-*************************************************************************** +* Streaming decompression howto +* +* A ZBUFFv07_DCtx object is required to track streaming operations. +* Use ZBUFFv07_createDCtx() and ZBUFFv07_freeDCtx() to create/release resources. +* Use ZBUFFv07_decompressInit() to start a new decompression operation, +* or ZBUFFv07_decompressInitDictionary() if decompression requires a dictionary. +* Note that ZBUFFv07_DCtx objects can be re-init multiple times. +* +* Use ZBUFFv07_decompressContinue() repetitively to consume your input. +* *srcSizePtr and *dstCapacityPtr can be any size. +* The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr. +* Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again. +* The content of `dst` will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change `dst`. +* @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency), +* or 0 when a frame is completely decoded, +* or an error code, which can be tested using ZBUFFv07_isError(). +* +* Hint : recommended buffer sizes (not compulsory) : ZBUFFv07_recommendedDInSize() and ZBUFFv07_recommendedDOutSize() +* output : ZBUFFv07_recommendedDOutSize== 128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded. +* input : ZBUFFv07_recommendedDInSize == 128KB + 3; +* just follow indications from ZBUFFv07_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 . +* *******************************************************************************/ + + +/* ************************************* +* Tool functions +***************************************/ +ZSTDLIBv07_API unsigned ZBUFFv07_isError(size_t errorCode); +ZSTDLIBv07_API const char* ZBUFFv07_getErrorName(size_t errorCode); + +/** Functions below provide recommended buffer sizes for Compression or Decompression operations. +* These sizes are just hints, they tend to offer better latency */ +ZSTDLIBv07_API size_t ZBUFFv07_recommendedDInSize(void); +ZSTDLIBv07_API size_t ZBUFFv07_recommendedDOutSize(void); + + +/*-************************************* +* Constants +***************************************/ +#define ZSTDv07_MAGICNUMBER 0xFD2FB527 /* v0.7 */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTDv07_H_235446 */ +/**** ended inlining zstd_v07.h ****/ +#endif + +/** ZSTD_isLegacy() : + @return : > 0 if supported by legacy decoder. 0 otherwise. + return value is the version. +*/ +MEM_STATIC unsigned ZSTD_isLegacy(const void* src, size_t srcSize) +{ + U32 magicNumberLE; + if (srcSize<4) return 0; + magicNumberLE = MEM_readLE32(src); + switch(magicNumberLE) + { +#if (ZSTD_LEGACY_SUPPORT <= 1) + case ZSTDv01_magicNumberLE:return 1; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 2) + case ZSTDv02_magicNumber : return 2; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 3) + case ZSTDv03_magicNumber : return 3; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 4) + case ZSTDv04_magicNumber : return 4; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case ZSTDv05_MAGICNUMBER : return 5; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case ZSTDv06_MAGICNUMBER : return 6; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case ZSTDv07_MAGICNUMBER : return 7; +#endif + default : return 0; + } +} + + +MEM_STATIC unsigned long long ZSTD_getDecompressedSize_legacy(const void* src, size_t srcSize) +{ + U32 const version = ZSTD_isLegacy(src, srcSize); + if (version < 5) return 0; /* no decompressed size in frame header, or not a legacy format */ +#if (ZSTD_LEGACY_SUPPORT <= 5) + if (version==5) { + ZSTDv05_parameters fParams; + size_t const frResult = ZSTDv05_getFrameParams(&fParams, src, srcSize); + if (frResult != 0) return 0; + return fParams.srcSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + if (version==6) { + ZSTDv06_frameParams fParams; + size_t const frResult = ZSTDv06_getFrameParams(&fParams, src, srcSize); + if (frResult != 0) return 0; + return fParams.frameContentSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + if (version==7) { + ZSTDv07_frameParams fParams; + size_t const frResult = ZSTDv07_getFrameParams(&fParams, src, srcSize); + if (frResult != 0) return 0; + return fParams.frameContentSize; + } +#endif + return 0; /* should not be possible */ +} + + +MEM_STATIC size_t ZSTD_decompressLegacy( + void* dst, size_t dstCapacity, + const void* src, size_t compressedSize, + const void* dict,size_t dictSize) +{ + U32 const version = ZSTD_isLegacy(src, compressedSize); + (void)dst; (void)dstCapacity; (void)dict; (void)dictSize; /* unused when ZSTD_LEGACY_SUPPORT >= 8 */ + switch(version) + { +#if (ZSTD_LEGACY_SUPPORT <= 1) + case 1 : + return ZSTDv01_decompress(dst, dstCapacity, src, compressedSize); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 2) + case 2 : + return ZSTDv02_decompress(dst, dstCapacity, src, compressedSize); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 3) + case 3 : + return ZSTDv03_decompress(dst, dstCapacity, src, compressedSize); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : + return ZSTDv04_decompress(dst, dstCapacity, src, compressedSize); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : + { size_t result; + ZSTDv05_DCtx* const zd = ZSTDv05_createDCtx(); + if (zd==NULL) return ERROR(memory_allocation); + result = ZSTDv05_decompress_usingDict(zd, dst, dstCapacity, src, compressedSize, dict, dictSize); + ZSTDv05_freeDCtx(zd); + return result; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : + { size_t result; + ZSTDv06_DCtx* const zd = ZSTDv06_createDCtx(); + if (zd==NULL) return ERROR(memory_allocation); + result = ZSTDv06_decompress_usingDict(zd, dst, dstCapacity, src, compressedSize, dict, dictSize); + ZSTDv06_freeDCtx(zd); + return result; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : + { size_t result; + ZSTDv07_DCtx* const zd = ZSTDv07_createDCtx(); + if (zd==NULL) return ERROR(memory_allocation); + result = ZSTDv07_decompress_usingDict(zd, dst, dstCapacity, src, compressedSize, dict, dictSize); + ZSTDv07_freeDCtx(zd); + return result; + } +#endif + default : + return ERROR(prefix_unknown); + } +} + +MEM_STATIC ZSTD_frameSizeInfo ZSTD_findFrameSizeInfoLegacy(const void *src, size_t srcSize) +{ + ZSTD_frameSizeInfo frameSizeInfo; + U32 const version = ZSTD_isLegacy(src, srcSize); + switch(version) + { +#if (ZSTD_LEGACY_SUPPORT <= 1) + case 1 : + ZSTDv01_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 2) + case 2 : + ZSTDv02_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 3) + case 3 : + ZSTDv03_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : + ZSTDv04_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : + ZSTDv05_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : + ZSTDv06_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : + ZSTDv07_findFrameSizeInfoLegacy(src, srcSize, + &frameSizeInfo.compressedSize, + &frameSizeInfo.decompressedBound); + break; +#endif + default : + frameSizeInfo.compressedSize = ERROR(prefix_unknown); + frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR; + break; + } + if (!ZSTD_isError(frameSizeInfo.compressedSize) && frameSizeInfo.compressedSize > srcSize) { + frameSizeInfo.compressedSize = ERROR(srcSize_wrong); + frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR; + } + return frameSizeInfo; +} + +MEM_STATIC size_t ZSTD_findFrameCompressedSizeLegacy(const void *src, size_t srcSize) +{ + ZSTD_frameSizeInfo frameSizeInfo = ZSTD_findFrameSizeInfoLegacy(src, srcSize); + return frameSizeInfo.compressedSize; +} + +MEM_STATIC size_t ZSTD_freeLegacyStreamContext(void* legacyContext, U32 version) +{ + switch(version) + { + default : + case 1 : + case 2 : + case 3 : + (void)legacyContext; + return ERROR(version_unsupported); +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : return ZBUFFv04_freeDCtx((ZBUFFv04_DCtx*)legacyContext); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : return ZBUFFv05_freeDCtx((ZBUFFv05_DCtx*)legacyContext); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : return ZBUFFv06_freeDCtx((ZBUFFv06_DCtx*)legacyContext); +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : return ZBUFFv07_freeDCtx((ZBUFFv07_DCtx*)legacyContext); +#endif + } +} + + +MEM_STATIC size_t ZSTD_initLegacyStream(void** legacyContext, U32 prevVersion, U32 newVersion, + const void* dict, size_t dictSize) +{ + DEBUGLOG(5, "ZSTD_initLegacyStream for v0.%u", newVersion); + if (prevVersion != newVersion) ZSTD_freeLegacyStreamContext(*legacyContext, prevVersion); + switch(newVersion) + { + default : + case 1 : + case 2 : + case 3 : + (void)dict; (void)dictSize; + return 0; +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : + { + ZBUFFv04_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv04_createDCtx() : (ZBUFFv04_DCtx*)*legacyContext; + if (dctx==NULL) return ERROR(memory_allocation); + ZBUFFv04_decompressInit(dctx); + ZBUFFv04_decompressWithDictionary(dctx, dict, dictSize); + *legacyContext = dctx; + return 0; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : + { + ZBUFFv05_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv05_createDCtx() : (ZBUFFv05_DCtx*)*legacyContext; + if (dctx==NULL) return ERROR(memory_allocation); + ZBUFFv05_decompressInitDictionary(dctx, dict, dictSize); + *legacyContext = dctx; + return 0; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : + { + ZBUFFv06_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv06_createDCtx() : (ZBUFFv06_DCtx*)*legacyContext; + if (dctx==NULL) return ERROR(memory_allocation); + ZBUFFv06_decompressInitDictionary(dctx, dict, dictSize); + *legacyContext = dctx; + return 0; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : + { + ZBUFFv07_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv07_createDCtx() : (ZBUFFv07_DCtx*)*legacyContext; + if (dctx==NULL) return ERROR(memory_allocation); + ZBUFFv07_decompressInitDictionary(dctx, dict, dictSize); + *legacyContext = dctx; + return 0; + } +#endif + } +} + + + +MEM_STATIC size_t ZSTD_decompressLegacyStream(void* legacyContext, U32 version, + ZSTD_outBuffer* output, ZSTD_inBuffer* input) +{ + DEBUGLOG(5, "ZSTD_decompressLegacyStream for v0.%u", version); + switch(version) + { + default : + case 1 : + case 2 : + case 3 : + (void)legacyContext; (void)output; (void)input; + return ERROR(version_unsupported); +#if (ZSTD_LEGACY_SUPPORT <= 4) + case 4 : + { + ZBUFFv04_DCtx* dctx = (ZBUFFv04_DCtx*) legacyContext; + const void* src = (const char*)input->src + input->pos; + size_t readSize = input->size - input->pos; + void* dst = (char*)output->dst + output->pos; + size_t decodedSize = output->size - output->pos; + size_t const hintSize = ZBUFFv04_decompressContinue(dctx, dst, &decodedSize, src, &readSize); + output->pos += decodedSize; + input->pos += readSize; + return hintSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 5) + case 5 : + { + ZBUFFv05_DCtx* dctx = (ZBUFFv05_DCtx*) legacyContext; + const void* src = (const char*)input->src + input->pos; + size_t readSize = input->size - input->pos; + void* dst = (char*)output->dst + output->pos; + size_t decodedSize = output->size - output->pos; + size_t const hintSize = ZBUFFv05_decompressContinue(dctx, dst, &decodedSize, src, &readSize); + output->pos += decodedSize; + input->pos += readSize; + return hintSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 6) + case 6 : + { + ZBUFFv06_DCtx* dctx = (ZBUFFv06_DCtx*) legacyContext; + const void* src = (const char*)input->src + input->pos; + size_t readSize = input->size - input->pos; + void* dst = (char*)output->dst + output->pos; + size_t decodedSize = output->size - output->pos; + size_t const hintSize = ZBUFFv06_decompressContinue(dctx, dst, &decodedSize, src, &readSize); + output->pos += decodedSize; + input->pos += readSize; + return hintSize; + } +#endif +#if (ZSTD_LEGACY_SUPPORT <= 7) + case 7 : + { + ZBUFFv07_DCtx* dctx = (ZBUFFv07_DCtx*) legacyContext; + const void* src = (const char*)input->src + input->pos; + size_t readSize = input->size - input->pos; + void* dst = (char*)output->dst + output->pos; + size_t decodedSize = output->size - output->pos; + size_t const hintSize = ZBUFFv07_decompressContinue(dctx, dst, &decodedSize, src, &readSize); + output->pos += decodedSize; + input->pos += readSize; + return hintSize; + } +#endif + } +} + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_LEGACY_H */ +/**** ended inlining ../legacy/zstd_legacy.h ****/ +#endif + + + +/*-******************************************************* +* Types +*********************************************************/ +struct ZSTD_DDict_s { + void* dictBuffer; + const void* dictContent; + size_t dictSize; + ZSTD_entropyDTables_t entropy; + U32 dictID; + U32 entropyPresent; + ZSTD_customMem cMem; +}; /* typedef'd to ZSTD_DDict within "zstd.h" */ + +const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict) +{ + assert(ddict != NULL); + return ddict->dictContent; +} + +size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict) +{ + assert(ddict != NULL); + return ddict->dictSize; +} + +void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) +{ + DEBUGLOG(4, "ZSTD_copyDDictParameters"); + assert(dctx != NULL); + assert(ddict != NULL); + dctx->dictID = ddict->dictID; + dctx->prefixStart = ddict->dictContent; + dctx->virtualStart = ddict->dictContent; + dctx->dictEnd = (const BYTE*)ddict->dictContent + ddict->dictSize; + dctx->previousDstEnd = dctx->dictEnd; +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + dctx->dictContentBeginForFuzzing = dctx->prefixStart; + dctx->dictContentEndForFuzzing = dctx->previousDstEnd; +#endif + if (ddict->entropyPresent) { + dctx->litEntropy = 1; + dctx->fseEntropy = 1; + dctx->LLTptr = ddict->entropy.LLTable; + dctx->MLTptr = ddict->entropy.MLTable; + dctx->OFTptr = ddict->entropy.OFTable; + dctx->HUFptr = ddict->entropy.hufTable; + dctx->entropy.rep[0] = ddict->entropy.rep[0]; + dctx->entropy.rep[1] = ddict->entropy.rep[1]; + dctx->entropy.rep[2] = ddict->entropy.rep[2]; + } else { + dctx->litEntropy = 0; + dctx->fseEntropy = 0; + } +} + + +static size_t +ZSTD_loadEntropy_intoDDict(ZSTD_DDict* ddict, + ZSTD_dictContentType_e dictContentType) +{ + ddict->dictID = 0; + ddict->entropyPresent = 0; + if (dictContentType == ZSTD_dct_rawContent) return 0; + + if (ddict->dictSize < 8) { + if (dictContentType == ZSTD_dct_fullDict) + return ERROR(dictionary_corrupted); /* only accept specified dictionaries */ + return 0; /* pure content mode */ + } + { U32 const magic = MEM_readLE32(ddict->dictContent); + if (magic != ZSTD_MAGIC_DICTIONARY) { + if (dictContentType == ZSTD_dct_fullDict) + return ERROR(dictionary_corrupted); /* only accept specified dictionaries */ + return 0; /* pure content mode */ + } + } + ddict->dictID = MEM_readLE32((const char*)ddict->dictContent + ZSTD_FRAMEIDSIZE); + + /* load entropy tables */ + RETURN_ERROR_IF(ZSTD_isError(ZSTD_loadDEntropy( + &ddict->entropy, ddict->dictContent, ddict->dictSize)), + dictionary_corrupted, ""); + ddict->entropyPresent = 1; + return 0; +} + + +static size_t ZSTD_initDDict_internal(ZSTD_DDict* ddict, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType) +{ + if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dict) || (!dictSize)) { + ddict->dictBuffer = NULL; + ddict->dictContent = dict; + if (!dict) dictSize = 0; + } else { + void* const internalBuffer = ZSTD_malloc(dictSize, ddict->cMem); + ddict->dictBuffer = internalBuffer; + ddict->dictContent = internalBuffer; + if (!internalBuffer) return ERROR(memory_allocation); + memcpy(internalBuffer, dict, dictSize); + } + ddict->dictSize = dictSize; + ddict->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */ + + /* parse dictionary content */ + FORWARD_IF_ERROR( ZSTD_loadEntropy_intoDDict(ddict, dictContentType) , ""); + + return 0; +} + +ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_customMem customMem) +{ + if (!customMem.customAlloc ^ !customMem.customFree) return NULL; + + { ZSTD_DDict* const ddict = (ZSTD_DDict*) ZSTD_malloc(sizeof(ZSTD_DDict), customMem); + if (ddict == NULL) return NULL; + ddict->cMem = customMem; + { size_t const initResult = ZSTD_initDDict_internal(ddict, + dict, dictSize, + dictLoadMethod, dictContentType); + if (ZSTD_isError(initResult)) { + ZSTD_freeDDict(ddict); + return NULL; + } } + return ddict; + } +} + +/*! ZSTD_createDDict() : +* Create a digested dictionary, to start decompression without startup delay. +* `dict` content is copied inside DDict. +* Consequently, `dict` can be released after `ZSTD_DDict` creation */ +ZSTD_DDict* ZSTD_createDDict(const void* dict, size_t dictSize) +{ + ZSTD_customMem const allocator = { NULL, NULL, NULL }; + return ZSTD_createDDict_advanced(dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto, allocator); +} + +/*! ZSTD_createDDict_byReference() : + * Create a digested dictionary, to start decompression without startup delay. + * Dictionary content is simply referenced, it will be accessed during decompression. + * Warning : dictBuffer must outlive DDict (DDict must be freed before dictBuffer) */ +ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize) +{ + ZSTD_customMem const allocator = { NULL, NULL, NULL }; + return ZSTD_createDDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto, allocator); +} + + +const ZSTD_DDict* ZSTD_initStaticDDict( + void* sBuffer, size_t sBufferSize, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType) +{ + size_t const neededSpace = sizeof(ZSTD_DDict) + + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize); + ZSTD_DDict* const ddict = (ZSTD_DDict*)sBuffer; + assert(sBuffer != NULL); + assert(dict != NULL); + if ((size_t)sBuffer & 7) return NULL; /* 8-aligned */ + if (sBufferSize < neededSpace) return NULL; + if (dictLoadMethod == ZSTD_dlm_byCopy) { + memcpy(ddict+1, dict, dictSize); /* local copy */ + dict = ddict+1; + } + if (ZSTD_isError( ZSTD_initDDict_internal(ddict, + dict, dictSize, + ZSTD_dlm_byRef, dictContentType) )) + return NULL; + return ddict; +} + + +size_t ZSTD_freeDDict(ZSTD_DDict* ddict) +{ + if (ddict==NULL) return 0; /* support free on NULL */ + { ZSTD_customMem const cMem = ddict->cMem; + ZSTD_free(ddict->dictBuffer, cMem); + ZSTD_free(ddict, cMem); + return 0; + } +} + +/*! ZSTD_estimateDDictSize() : + * Estimate amount of memory that will be needed to create a dictionary for decompression. + * Note : dictionary created by reference using ZSTD_dlm_byRef are smaller */ +size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod) +{ + return sizeof(ZSTD_DDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize); +} + +size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict) +{ + if (ddict==NULL) return 0; /* support sizeof on NULL */ + return sizeof(*ddict) + (ddict->dictBuffer ? ddict->dictSize : 0) ; +} + +/*! ZSTD_getDictID_fromDDict() : + * Provides the dictID of the dictionary loaded into `ddict`. + * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty. + * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */ +unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict) +{ + if (ddict==NULL) return 0; + return ZSTD_getDictID_fromDict(ddict->dictContent, ddict->dictSize); +} +/**** ended inlining decompress/zstd_ddict.c ****/ +/**** start inlining decompress/zstd_decompress.c ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + +/* *************************************************************** +* Tuning parameters +*****************************************************************/ +/*! + * HEAPMODE : + * Select how default decompression function ZSTD_decompress() allocates its context, + * on stack (0), or into heap (1, default; requires malloc()). + * Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected. + */ +#ifndef ZSTD_HEAPMODE +# define ZSTD_HEAPMODE 1 +#endif + +/*! +* LEGACY_SUPPORT : +* if set to 1+, ZSTD_decompress() can decode older formats (v0.1+) +*/ +#ifndef ZSTD_LEGACY_SUPPORT +# define ZSTD_LEGACY_SUPPORT 0 +#endif + +/*! + * MAXWINDOWSIZE_DEFAULT : + * maximum window size accepted by DStream __by default__. + * Frames requiring more memory will be rejected. + * It's possible to set a different limit using ZSTD_DCtx_setMaxWindowSize(). + */ +#ifndef ZSTD_MAXWINDOWSIZE_DEFAULT +# define ZSTD_MAXWINDOWSIZE_DEFAULT (((U32)1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + 1) +#endif + +/*! + * NO_FORWARD_PROGRESS_MAX : + * maximum allowed nb of calls to ZSTD_decompressStream() + * without any forward progress + * (defined as: no byte read from input, and no byte flushed to output) + * before triggering an error. + */ +#ifndef ZSTD_NO_FORWARD_PROGRESS_MAX +# define ZSTD_NO_FORWARD_PROGRESS_MAX 16 +#endif + + +/*-******************************************************* +* Dependencies +*********************************************************/ +/**** skipping file: ../common/cpu.h ****/ +/**** skipping file: ../common/mem.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: ../common/fse.h ****/ +#define HUF_STATIC_LINKING_ONLY +/**** skipping file: ../common/huf.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ +/**** skipping file: zstd_decompress_internal.h ****/ +/**** skipping file: zstd_ddict.h ****/ +/**** start inlining zstd_decompress_block.h ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + + +#ifndef ZSTD_DEC_BLOCK_H +#define ZSTD_DEC_BLOCK_H + +/*-******************************************************* + * Dependencies + *********************************************************/ +#include /* size_t */ +/**** skipping file: ../zstd.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ +/**** skipping file: zstd_decompress_internal.h ****/ + + +/* === Prototypes === */ + +/* note: prototypes already published within `zstd.h` : + * ZSTD_decompressBlock() + */ + +/* note: prototypes already published within `zstd_internal.h` : + * ZSTD_getcBlockSize() + * ZSTD_decodeSeqHeaders() + */ + + +/* ZSTD_decompressBlock_internal() : + * decompress block, starting at `src`, + * into destination buffer `dst`. + * @return : decompressed block size, + * or an error code (which can be tested using ZSTD_isError()) + */ +size_t ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, const int frame); + +/* ZSTD_buildFSETable() : + * generate FSE decoding table for one symbol (ll, ml or off) + * this function must be called with valid parameters only + * (dt is large enough, normalizedCounter distribution total is a power of 2, max is within range, etc.) + * in which case it cannot fail. + * Internal use only. + */ +void ZSTD_buildFSETable(ZSTD_seqSymbol* dt, + const short* normalizedCounter, unsigned maxSymbolValue, + const U32* baseValue, const U32* nbAdditionalBits, + unsigned tableLog); + + +#endif /* ZSTD_DEC_BLOCK_H */ +/**** ended inlining zstd_decompress_block.h ****/ + +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) +/**** skipping file: ../legacy/zstd_legacy.h ****/ +#endif + + +/*-************************************************************* +* Context management +***************************************************************/ +size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx) +{ + if (dctx==NULL) return 0; /* support sizeof NULL */ + return sizeof(*dctx) + + ZSTD_sizeof_DDict(dctx->ddictLocal) + + dctx->inBuffSize + dctx->outBuffSize; +} + +size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); } + + +static size_t ZSTD_startingInputLength(ZSTD_format_e format) +{ + size_t const startingInputLength = ZSTD_FRAMEHEADERSIZE_PREFIX(format); + /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */ + assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) ); + return startingInputLength; +} + +static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx) +{ + dctx->format = ZSTD_f_zstd1; /* ZSTD_decompressBegin() invokes ZSTD_startingInputLength() with argument dctx->format */ + dctx->staticSize = 0; + dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT; + dctx->ddict = NULL; + dctx->ddictLocal = NULL; + dctx->dictEnd = NULL; + dctx->ddictIsCold = 0; + dctx->dictUses = ZSTD_dont_use; + dctx->inBuff = NULL; + dctx->inBuffSize = 0; + dctx->outBuffSize = 0; + dctx->streamStage = zdss_init; + dctx->legacyContext = NULL; + dctx->previousLegacyVersion = 0; + dctx->noForwardProgress = 0; + dctx->oversizedDuration = 0; + dctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid()); + dctx->outBufferMode = ZSTD_obm_buffered; +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + dctx->dictContentEndForFuzzing = NULL; +#endif +} + +ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize) +{ + ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace; + + if ((size_t)workspace & 7) return NULL; /* 8-aligned */ + if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL; /* minimum size */ + + ZSTD_initDCtx_internal(dctx); + dctx->staticSize = workspaceSize; + dctx->inBuff = (char*)(dctx+1); + return dctx; +} + +ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem) +{ + if (!customMem.customAlloc ^ !customMem.customFree) return NULL; + + { ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_malloc(sizeof(*dctx), customMem); + if (!dctx) return NULL; + dctx->customMem = customMem; + ZSTD_initDCtx_internal(dctx); + return dctx; + } +} + +ZSTD_DCtx* ZSTD_createDCtx(void) +{ + DEBUGLOG(3, "ZSTD_createDCtx"); + return ZSTD_createDCtx_advanced(ZSTD_defaultCMem); +} + +static void ZSTD_clearDict(ZSTD_DCtx* dctx) +{ + ZSTD_freeDDict(dctx->ddictLocal); + dctx->ddictLocal = NULL; + dctx->ddict = NULL; + dctx->dictUses = ZSTD_dont_use; +} + +size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx) +{ + if (dctx==NULL) return 0; /* support free on NULL */ + RETURN_ERROR_IF(dctx->staticSize, memory_allocation, "not compatible with static DCtx"); + { ZSTD_customMem const cMem = dctx->customMem; + ZSTD_clearDict(dctx); + ZSTD_free(dctx->inBuff, cMem); + dctx->inBuff = NULL; +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (dctx->legacyContext) + ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion); +#endif + ZSTD_free(dctx, cMem); + return 0; + } +} + +/* no longer useful */ +void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx) +{ + size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx); + memcpy(dstDCtx, srcDCtx, toCopy); /* no need to copy workspace */ +} + + +/*-************************************************************* + * Frame header decoding + ***************************************************************/ + +/*! ZSTD_isFrame() : + * Tells if the content of `buffer` starts with a valid Frame Identifier. + * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0. + * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled. + * Note 3 : Skippable Frame Identifiers are considered valid. */ +unsigned ZSTD_isFrame(const void* buffer, size_t size) +{ + if (size < ZSTD_FRAMEIDSIZE) return 0; + { U32 const magic = MEM_readLE32(buffer); + if (magic == ZSTD_MAGICNUMBER) return 1; + if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1; + } +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (ZSTD_isLegacy(buffer, size)) return 1; +#endif + return 0; +} + +/** ZSTD_frameHeaderSize_internal() : + * srcSize must be large enough to reach header size fields. + * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless. + * @return : size of the Frame Header + * or an error code, which can be tested with ZSTD_isError() */ +static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format) +{ + size_t const minInputSize = ZSTD_startingInputLength(format); + RETURN_ERROR_IF(srcSize < minInputSize, srcSize_wrong, ""); + + { BYTE const fhd = ((const BYTE*)src)[minInputSize-1]; + U32 const dictID= fhd & 3; + U32 const singleSegment = (fhd >> 5) & 1; + U32 const fcsId = fhd >> 6; + return minInputSize + !singleSegment + + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId] + + (singleSegment && !fcsId); + } +} + +/** ZSTD_frameHeaderSize() : + * srcSize must be >= ZSTD_frameHeaderSize_prefix. + * @return : size of the Frame Header, + * or an error code (if srcSize is too small) */ +size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize) +{ + return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1); +} + + +/** ZSTD_getFrameHeader_advanced() : + * decode Frame Header, or require larger `srcSize`. + * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless + * @return : 0, `zfhPtr` is correctly filled, + * >0, `srcSize` is too small, value is wanted `srcSize` amount, + * or an error code, which can be tested using ZSTD_isError() */ +size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format) +{ + const BYTE* ip = (const BYTE*)src; + size_t const minInputSize = ZSTD_startingInputLength(format); + + memset(zfhPtr, 0, sizeof(*zfhPtr)); /* not strictly necessary, but static analyzer do not understand that zfhPtr is only going to be read only if return value is zero, since they are 2 different signals */ + if (srcSize < minInputSize) return minInputSize; + RETURN_ERROR_IF(src==NULL, GENERIC, "invalid parameter"); + + if ( (format != ZSTD_f_zstd1_magicless) + && (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) { + if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { + /* skippable frame */ + if (srcSize < ZSTD_SKIPPABLEHEADERSIZE) + return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */ + memset(zfhPtr, 0, sizeof(*zfhPtr)); + zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE); + zfhPtr->frameType = ZSTD_skippableFrame; + return 0; + } + RETURN_ERROR(prefix_unknown, ""); + } + + /* ensure there is enough `srcSize` to fully read/decode frame header */ + { size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format); + if (srcSize < fhsize) return fhsize; + zfhPtr->headerSize = (U32)fhsize; + } + + { BYTE const fhdByte = ip[minInputSize-1]; + size_t pos = minInputSize; + U32 const dictIDSizeCode = fhdByte&3; + U32 const checksumFlag = (fhdByte>>2)&1; + U32 const singleSegment = (fhdByte>>5)&1; + U32 const fcsID = fhdByte>>6; + U64 windowSize = 0; + U32 dictID = 0; + U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN; + RETURN_ERROR_IF((fhdByte & 0x08) != 0, frameParameter_unsupported, + "reserved bits, must be zero"); + + if (!singleSegment) { + BYTE const wlByte = ip[pos++]; + U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN; + RETURN_ERROR_IF(windowLog > ZSTD_WINDOWLOG_MAX, frameParameter_windowTooLarge, ""); + windowSize = (1ULL << windowLog); + windowSize += (windowSize >> 3) * (wlByte&7); + } + switch(dictIDSizeCode) + { + default: assert(0); /* impossible */ + case 0 : break; + case 1 : dictID = ip[pos]; pos++; break; + case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break; + case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break; + } + switch(fcsID) + { + default: assert(0); /* impossible */ + case 0 : if (singleSegment) frameContentSize = ip[pos]; break; + case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break; + case 2 : frameContentSize = MEM_readLE32(ip+pos); break; + case 3 : frameContentSize = MEM_readLE64(ip+pos); break; + } + if (singleSegment) windowSize = frameContentSize; + + zfhPtr->frameType = ZSTD_frame; + zfhPtr->frameContentSize = frameContentSize; + zfhPtr->windowSize = windowSize; + zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX); + zfhPtr->dictID = dictID; + zfhPtr->checksumFlag = checksumFlag; + } + return 0; +} + +/** ZSTD_getFrameHeader() : + * decode Frame Header, or require larger `srcSize`. + * note : this function does not consume input, it only reads it. + * @return : 0, `zfhPtr` is correctly filled, + * >0, `srcSize` is too small, value is wanted `srcSize` amount, + * or an error code, which can be tested using ZSTD_isError() */ +size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize) +{ + return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1); +} + + +/** ZSTD_getFrameContentSize() : + * compatible with legacy mode + * @return : decompressed size of the single frame pointed to be `src` if known, otherwise + * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined + * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */ +unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize) +{ +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (ZSTD_isLegacy(src, srcSize)) { + unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize); + return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret; + } +#endif + { ZSTD_frameHeader zfh; + if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0) + return ZSTD_CONTENTSIZE_ERROR; + if (zfh.frameType == ZSTD_skippableFrame) { + return 0; + } else { + return zfh.frameContentSize; + } } +} + +static size_t readSkippableFrameSize(void const* src, size_t srcSize) +{ + size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE; + U32 sizeU32; + + RETURN_ERROR_IF(srcSize < ZSTD_SKIPPABLEHEADERSIZE, srcSize_wrong, ""); + + sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE); + RETURN_ERROR_IF((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32, + frameParameter_unsupported, ""); + { + size_t const skippableSize = skippableHeaderSize + sizeU32; + RETURN_ERROR_IF(skippableSize > srcSize, srcSize_wrong, ""); + return skippableSize; + } +} + +/** ZSTD_findDecompressedSize() : + * compatible with legacy mode + * `srcSize` must be the exact length of some number of ZSTD compressed and/or + * skippable frames + * @return : decompressed size of the frames contained */ +unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize) +{ + unsigned long long totalDstSize = 0; + + while (srcSize >= ZSTD_startingInputLength(ZSTD_f_zstd1)) { + U32 const magicNumber = MEM_readLE32(src); + + if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { + size_t const skippableSize = readSkippableFrameSize(src, srcSize); + if (ZSTD_isError(skippableSize)) { + return ZSTD_CONTENTSIZE_ERROR; + } + assert(skippableSize <= srcSize); + + src = (const BYTE *)src + skippableSize; + srcSize -= skippableSize; + continue; + } + + { unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize); + if (ret >= ZSTD_CONTENTSIZE_ERROR) return ret; + + /* check for overflow */ + if (totalDstSize + ret < totalDstSize) return ZSTD_CONTENTSIZE_ERROR; + totalDstSize += ret; + } + { size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize); + if (ZSTD_isError(frameSrcSize)) { + return ZSTD_CONTENTSIZE_ERROR; + } + + src = (const BYTE *)src + frameSrcSize; + srcSize -= frameSrcSize; + } + } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */ + + if (srcSize) return ZSTD_CONTENTSIZE_ERROR; + + return totalDstSize; +} + +/** ZSTD_getDecompressedSize() : + * compatible with legacy mode + * @return : decompressed size if known, 0 otherwise + note : 0 can mean any of the following : + - frame content is empty + - decompressed size field is not present in frame header + - frame header unknown / not supported + - frame header not complete (`srcSize` too small) */ +unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize) +{ + unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize); + ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN); + return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret; +} + + +/** ZSTD_decodeFrameHeader() : + * `headerSize` must be the size provided by ZSTD_frameHeaderSize(). + * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */ +static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize) +{ + size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format); + if (ZSTD_isError(result)) return result; /* invalid header */ + RETURN_ERROR_IF(result>0, srcSize_wrong, "headerSize too small"); +#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + /* Skip the dictID check in fuzzing mode, because it makes the search + * harder. + */ + RETURN_ERROR_IF(dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID), + dictionary_wrong, ""); +#endif + if (dctx->fParams.checksumFlag) XXH64_reset(&dctx->xxhState, 0); + return 0; +} + +static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo(size_t ret) +{ + ZSTD_frameSizeInfo frameSizeInfo; + frameSizeInfo.compressedSize = ret; + frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR; + return frameSizeInfo; +} + +static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize) +{ + ZSTD_frameSizeInfo frameSizeInfo; + memset(&frameSizeInfo, 0, sizeof(ZSTD_frameSizeInfo)); + +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (ZSTD_isLegacy(src, srcSize)) + return ZSTD_findFrameSizeInfoLegacy(src, srcSize); +#endif + + if ((srcSize >= ZSTD_SKIPPABLEHEADERSIZE) + && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { + frameSizeInfo.compressedSize = readSkippableFrameSize(src, srcSize); + assert(ZSTD_isError(frameSizeInfo.compressedSize) || + frameSizeInfo.compressedSize <= srcSize); + return frameSizeInfo; + } else { + const BYTE* ip = (const BYTE*)src; + const BYTE* const ipstart = ip; + size_t remainingSize = srcSize; + size_t nbBlocks = 0; + ZSTD_frameHeader zfh; + + /* Extract Frame Header */ + { size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize); + if (ZSTD_isError(ret)) + return ZSTD_errorFrameSizeInfo(ret); + if (ret > 0) + return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong)); + } + + ip += zfh.headerSize; + remainingSize -= zfh.headerSize; + + /* Iterate over each block */ + while (1) { + blockProperties_t blockProperties; + size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties); + if (ZSTD_isError(cBlockSize)) + return ZSTD_errorFrameSizeInfo(cBlockSize); + + if (ZSTD_blockHeaderSize + cBlockSize > remainingSize) + return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong)); + + ip += ZSTD_blockHeaderSize + cBlockSize; + remainingSize -= ZSTD_blockHeaderSize + cBlockSize; + nbBlocks++; + + if (blockProperties.lastBlock) break; + } + + /* Final frame content checksum */ + if (zfh.checksumFlag) { + if (remainingSize < 4) + return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong)); + ip += 4; + } + + frameSizeInfo.compressedSize = ip - ipstart; + frameSizeInfo.decompressedBound = (zfh.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) + ? zfh.frameContentSize + : nbBlocks * zfh.blockSizeMax; + return frameSizeInfo; + } +} + +/** ZSTD_findFrameCompressedSize() : + * compatible with legacy mode + * `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame + * `srcSize` must be at least as large as the frame contained + * @return : the compressed size of the frame starting at `src` */ +size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize) +{ + ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize); + return frameSizeInfo.compressedSize; +} + +/** ZSTD_decompressBound() : + * compatible with legacy mode + * `src` must point to the start of a ZSTD frame or a skippeable frame + * `srcSize` must be at least as large as the frame contained + * @return : the maximum decompressed size of the compressed source + */ +unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize) +{ + unsigned long long bound = 0; + /* Iterate over each frame */ + while (srcSize > 0) { + ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize); + size_t const compressedSize = frameSizeInfo.compressedSize; + unsigned long long const decompressedBound = frameSizeInfo.decompressedBound; + if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR) + return ZSTD_CONTENTSIZE_ERROR; + assert(srcSize >= compressedSize); + src = (const BYTE*)src + compressedSize; + srcSize -= compressedSize; + bound += decompressedBound; + } + return bound; +} + + +/*-************************************************************* + * Frame decoding + ***************************************************************/ + +/** ZSTD_insertBlock() : + * insert `src` block into `dctx` history. Useful to track uncompressed blocks. */ +size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize) +{ + DEBUGLOG(5, "ZSTD_insertBlock: %u bytes", (unsigned)blockSize); + ZSTD_checkContinuity(dctx, blockStart); + dctx->previousDstEnd = (const char*)blockStart + blockSize; + return blockSize; +} + + +static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity, + const void* src, size_t srcSize) +{ + DEBUGLOG(5, "ZSTD_copyRawBlock"); + if (dst == NULL) { + if (srcSize == 0) return 0; + RETURN_ERROR(dstBuffer_null, ""); + } + RETURN_ERROR_IF(srcSize > dstCapacity, dstSize_tooSmall, ""); + memcpy(dst, src, srcSize); + return srcSize; +} + +static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity, + BYTE b, + size_t regenSize) +{ + if (dst == NULL) { + if (regenSize == 0) return 0; + RETURN_ERROR(dstBuffer_null, ""); + } + RETURN_ERROR_IF(regenSize > dstCapacity, dstSize_tooSmall, ""); + memset(dst, b, regenSize); + return regenSize; +} + + +/*! ZSTD_decompressFrame() : + * @dctx must be properly initialized + * will update *srcPtr and *srcSizePtr, + * to make *srcPtr progress by one frame. */ +static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void** srcPtr, size_t *srcSizePtr) +{ + const BYTE* ip = (const BYTE*)(*srcPtr); + BYTE* const ostart = (BYTE* const)dst; + BYTE* const oend = dstCapacity != 0 ? ostart + dstCapacity : ostart; + BYTE* op = ostart; + size_t remainingSrcSize = *srcSizePtr; + + DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr); + + /* check */ + RETURN_ERROR_IF( + remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN(dctx->format)+ZSTD_blockHeaderSize, + srcSize_wrong, ""); + + /* Frame Header */ + { size_t const frameHeaderSize = ZSTD_frameHeaderSize_internal( + ip, ZSTD_FRAMEHEADERSIZE_PREFIX(dctx->format), dctx->format); + if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize; + RETURN_ERROR_IF(remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize, + srcSize_wrong, ""); + FORWARD_IF_ERROR( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) , ""); + ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize; + } + + /* Loop on each block */ + while (1) { + size_t decodedSize; + blockProperties_t blockProperties; + size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties); + if (ZSTD_isError(cBlockSize)) return cBlockSize; + + ip += ZSTD_blockHeaderSize; + remainingSrcSize -= ZSTD_blockHeaderSize; + RETURN_ERROR_IF(cBlockSize > remainingSrcSize, srcSize_wrong, ""); + + switch(blockProperties.blockType) + { + case bt_compressed: + decodedSize = ZSTD_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize, /* frame */ 1); + break; + case bt_raw : + decodedSize = ZSTD_copyRawBlock(op, oend-op, ip, cBlockSize); + break; + case bt_rle : + decodedSize = ZSTD_setRleBlock(op, oend-op, *ip, blockProperties.origSize); + break; + case bt_reserved : + default: + RETURN_ERROR(corruption_detected, "invalid block type"); + } + + if (ZSTD_isError(decodedSize)) return decodedSize; + if (dctx->fParams.checksumFlag) + XXH64_update(&dctx->xxhState, op, decodedSize); + if (decodedSize != 0) + op += decodedSize; + assert(ip != NULL); + ip += cBlockSize; + remainingSrcSize -= cBlockSize; + if (blockProperties.lastBlock) break; + } + + if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) { + RETURN_ERROR_IF((U64)(op-ostart) != dctx->fParams.frameContentSize, + corruption_detected, ""); + } + if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */ + U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState); + U32 checkRead; + RETURN_ERROR_IF(remainingSrcSize<4, checksum_wrong, ""); + checkRead = MEM_readLE32(ip); + RETURN_ERROR_IF(checkRead != checkCalc, checksum_wrong, ""); + ip += 4; + remainingSrcSize -= 4; + } + + /* Allow caller to get size read */ + *srcPtr = ip; + *srcSizePtr = remainingSrcSize; + return op-ostart; +} + +static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict, size_t dictSize, + const ZSTD_DDict* ddict) +{ + void* const dststart = dst; + int moreThan1Frame = 0; + + DEBUGLOG(5, "ZSTD_decompressMultiFrame"); + assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */ + + if (ddict) { + dict = ZSTD_DDict_dictContent(ddict); + dictSize = ZSTD_DDict_dictSize(ddict); + } + + while (srcSize >= ZSTD_startingInputLength(dctx->format)) { + +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) + if (ZSTD_isLegacy(src, srcSize)) { + size_t decodedSize; + size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize); + if (ZSTD_isError(frameSize)) return frameSize; + RETURN_ERROR_IF(dctx->staticSize, memory_allocation, + "legacy support is not compatible with static dctx"); + + decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize); + if (ZSTD_isError(decodedSize)) return decodedSize; + + assert(decodedSize <=- dstCapacity); + dst = (BYTE*)dst + decodedSize; + dstCapacity -= decodedSize; + + src = (const BYTE*)src + frameSize; + srcSize -= frameSize; + + continue; + } +#endif + + { U32 const magicNumber = MEM_readLE32(src); + DEBUGLOG(4, "reading magic number %08X (expecting %08X)", + (unsigned)magicNumber, ZSTD_MAGICNUMBER); + if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { + size_t const skippableSize = readSkippableFrameSize(src, srcSize); + FORWARD_IF_ERROR(skippableSize, "readSkippableFrameSize failed"); + assert(skippableSize <= srcSize); + + src = (const BYTE *)src + skippableSize; + srcSize -= skippableSize; + continue; + } } + + if (ddict) { + /* we were called from ZSTD_decompress_usingDDict */ + FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(dctx, ddict), ""); + } else { + /* this will initialize correctly with no dict if dict == NULL, so + * use this in all cases but ddict */ + FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize), ""); + } + ZSTD_checkContinuity(dctx, dst); + + { const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity, + &src, &srcSize); + RETURN_ERROR_IF( + (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown) + && (moreThan1Frame==1), + srcSize_wrong, + "at least one frame successfully completed, but following " + "bytes are garbage: it's more likely to be a srcSize error, " + "specifying more bytes than compressed size of frame(s). This " + "error message replaces ERROR(prefix_unknown), which would be " + "confusing, as the first header is actually correct. Note that " + "one could be unlucky, it might be a corruption error instead, " + "happening right at the place where we expect zstd magic " + "bytes. But this is _much_ less likely than a srcSize field " + "error."); + if (ZSTD_isError(res)) return res; + assert(res <= dstCapacity); + if (res != 0) + dst = (BYTE*)dst + res; + dstCapacity -= res; + } + moreThan1Frame = 1; + } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */ + + RETURN_ERROR_IF(srcSize, srcSize_wrong, "input not entirely consumed"); + + return (BYTE*)dst - (BYTE*)dststart; +} + +size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const void* dict, size_t dictSize) +{ + return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL); +} + + +static ZSTD_DDict const* ZSTD_getDDict(ZSTD_DCtx* dctx) +{ + switch (dctx->dictUses) { + default: + assert(0 /* Impossible */); + /* fall-through */ + case ZSTD_dont_use: + ZSTD_clearDict(dctx); + return NULL; + case ZSTD_use_indefinitely: + return dctx->ddict; + case ZSTD_use_once: + dctx->dictUses = ZSTD_dont_use; + return dctx->ddict; + } +} + +size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) +{ + return ZSTD_decompress_usingDDict(dctx, dst, dstCapacity, src, srcSize, ZSTD_getDDict(dctx)); +} + + +size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize) +{ +#if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1) + size_t regenSize; + ZSTD_DCtx* const dctx = ZSTD_createDCtx(); + RETURN_ERROR_IF(dctx==NULL, memory_allocation, "NULL pointer!"); + regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize); + ZSTD_freeDCtx(dctx); + return regenSize; +#else /* stack mode */ + ZSTD_DCtx dctx; + ZSTD_initDCtx_internal(&dctx); + return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize); +#endif +} + + +/*-************************************** +* Advanced Streaming Decompression API +* Bufferless and synchronous +****************************************/ +size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; } + +/** + * Similar to ZSTD_nextSrcSizeToDecompress(), but when when a block input can be streamed, + * we allow taking a partial block as the input. Currently only raw uncompressed blocks can + * be streamed. + * + * For blocks that can be streamed, this allows us to reduce the latency until we produce + * output, and avoid copying the input. + * + * @param inputSize - The total amount of input that the caller currently has. + */ +static size_t ZSTD_nextSrcSizeToDecompressWithInputSize(ZSTD_DCtx* dctx, size_t inputSize) { + if (!(dctx->stage == ZSTDds_decompressBlock || dctx->stage == ZSTDds_decompressLastBlock)) + return dctx->expected; + if (dctx->bType != bt_raw) + return dctx->expected; + return MIN(MAX(inputSize, 1), dctx->expected); +} + +ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) { + switch(dctx->stage) + { + default: /* should not happen */ + assert(0); + case ZSTDds_getFrameHeaderSize: + case ZSTDds_decodeFrameHeader: + return ZSTDnit_frameHeader; + case ZSTDds_decodeBlockHeader: + return ZSTDnit_blockHeader; + case ZSTDds_decompressBlock: + return ZSTDnit_block; + case ZSTDds_decompressLastBlock: + return ZSTDnit_lastBlock; + case ZSTDds_checkChecksum: + return ZSTDnit_checksum; + case ZSTDds_decodeSkippableHeader: + case ZSTDds_skipFrame: + return ZSTDnit_skippableFrame; + } +} + +static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; } + +/** ZSTD_decompressContinue() : + * srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress()) + * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity) + * or an error code, which can be tested using ZSTD_isError() */ +size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) +{ + DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize); + /* Sanity check */ + RETURN_ERROR_IF(srcSize != ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize), srcSize_wrong, "not allowed"); + if (dstCapacity) ZSTD_checkContinuity(dctx, dst); + + switch (dctx->stage) + { + case ZSTDds_getFrameHeaderSize : + assert(src != NULL); + if (dctx->format == ZSTD_f_zstd1) { /* allows header */ + assert(srcSize >= ZSTD_FRAMEIDSIZE); /* to read skippable magic number */ + if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ + memcpy(dctx->headerBuffer, src, srcSize); + dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize; /* remaining to load to get full skippable frame header */ + dctx->stage = ZSTDds_decodeSkippableHeader; + return 0; + } } + dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format); + if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize; + memcpy(dctx->headerBuffer, src, srcSize); + dctx->expected = dctx->headerSize - srcSize; + dctx->stage = ZSTDds_decodeFrameHeader; + return 0; + + case ZSTDds_decodeFrameHeader: + assert(src != NULL); + memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize); + FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize), ""); + dctx->expected = ZSTD_blockHeaderSize; + dctx->stage = ZSTDds_decodeBlockHeader; + return 0; + + case ZSTDds_decodeBlockHeader: + { blockProperties_t bp; + size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp); + if (ZSTD_isError(cBlockSize)) return cBlockSize; + RETURN_ERROR_IF(cBlockSize > dctx->fParams.blockSizeMax, corruption_detected, "Block Size Exceeds Maximum"); + dctx->expected = cBlockSize; + dctx->bType = bp.blockType; + dctx->rleSize = bp.origSize; + if (cBlockSize) { + dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock; + return 0; + } + /* empty block */ + if (bp.lastBlock) { + if (dctx->fParams.checksumFlag) { + dctx->expected = 4; + dctx->stage = ZSTDds_checkChecksum; + } else { + dctx->expected = 0; /* end of frame */ + dctx->stage = ZSTDds_getFrameHeaderSize; + } + } else { + dctx->expected = ZSTD_blockHeaderSize; /* jump to next header */ + dctx->stage = ZSTDds_decodeBlockHeader; + } + return 0; + } + + case ZSTDds_decompressLastBlock: + case ZSTDds_decompressBlock: + DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock"); + { size_t rSize; + switch(dctx->bType) + { + case bt_compressed: + DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed"); + rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1); + dctx->expected = 0; /* Streaming not supported */ + break; + case bt_raw : + assert(srcSize <= dctx->expected); + rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize); + FORWARD_IF_ERROR(rSize, "ZSTD_copyRawBlock failed"); + assert(rSize == srcSize); + dctx->expected -= rSize; + break; + case bt_rle : + rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize); + dctx->expected = 0; /* Streaming not supported */ + break; + case bt_reserved : /* should never happen */ + default: + RETURN_ERROR(corruption_detected, "invalid block type"); + } + FORWARD_IF_ERROR(rSize, ""); + RETURN_ERROR_IF(rSize > dctx->fParams.blockSizeMax, corruption_detected, "Decompressed Block Size Exceeds Maximum"); + DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize); + dctx->decodedSize += rSize; + if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize); + dctx->previousDstEnd = (char*)dst + rSize; + + /* Stay on the same stage until we are finished streaming the block. */ + if (dctx->expected > 0) { + return rSize; + } + + if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */ + DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize); + RETURN_ERROR_IF( + dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN + && dctx->decodedSize != dctx->fParams.frameContentSize, + corruption_detected, ""); + if (dctx->fParams.checksumFlag) { /* another round for frame checksum */ + dctx->expected = 4; + dctx->stage = ZSTDds_checkChecksum; + } else { + dctx->expected = 0; /* ends here */ + dctx->stage = ZSTDds_getFrameHeaderSize; + } + } else { + dctx->stage = ZSTDds_decodeBlockHeader; + dctx->expected = ZSTD_blockHeaderSize; + } + return rSize; + } + + case ZSTDds_checkChecksum: + assert(srcSize == 4); /* guaranteed by dctx->expected */ + { U32 const h32 = (U32)XXH64_digest(&dctx->xxhState); + U32 const check32 = MEM_readLE32(src); + DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32); + RETURN_ERROR_IF(check32 != h32, checksum_wrong, ""); + dctx->expected = 0; + dctx->stage = ZSTDds_getFrameHeaderSize; + return 0; + } + + case ZSTDds_decodeSkippableHeader: + assert(src != NULL); + assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE); + memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize); /* complete skippable header */ + dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE); /* note : dctx->expected can grow seriously large, beyond local buffer size */ + dctx->stage = ZSTDds_skipFrame; + return 0; + + case ZSTDds_skipFrame: + dctx->expected = 0; + dctx->stage = ZSTDds_getFrameHeaderSize; + return 0; + + default: + assert(0); /* impossible */ + RETURN_ERROR(GENERIC, "impossible to reach"); /* some compiler require default to do something */ + } +} + + +static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + dctx->dictEnd = dctx->previousDstEnd; + dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart)); + dctx->prefixStart = dict; + dctx->previousDstEnd = (const char*)dict + dictSize; +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION + dctx->dictContentBeginForFuzzing = dctx->prefixStart; + dctx->dictContentEndForFuzzing = dctx->previousDstEnd; +#endif + return 0; +} + +/*! ZSTD_loadDEntropy() : + * dict : must point at beginning of a valid zstd dictionary. + * @return : size of entropy tables read */ +size_t +ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy, + const void* const dict, size_t const dictSize) +{ + const BYTE* dictPtr = (const BYTE*)dict; + const BYTE* const dictEnd = dictPtr + dictSize; + + RETURN_ERROR_IF(dictSize <= 8, dictionary_corrupted, "dict is too small"); + assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY); /* dict must be valid */ + dictPtr += 8; /* skip header = magic + dictID */ + + ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable)); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable)); + ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE); + { void* const workspace = &entropy->LLTable; /* use fse tables as temporary workspace; implies fse tables are grouped together */ + size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable); +#ifdef HUF_FORCE_DECOMPRESS_X1 + /* in minimal huffman, we always use X1 variants */ + size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable, + dictPtr, dictEnd - dictPtr, + workspace, workspaceSize); +#else + size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable, + dictPtr, dictEnd - dictPtr, + workspace, workspaceSize); +#endif + RETURN_ERROR_IF(HUF_isError(hSize), dictionary_corrupted, ""); + dictPtr += hSize; + } + + { short offcodeNCount[MaxOff+1]; + unsigned offcodeMaxValue = MaxOff, offcodeLog; + size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr); + RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, ""); + RETURN_ERROR_IF(offcodeMaxValue > MaxOff, dictionary_corrupted, ""); + RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, ""); + ZSTD_buildFSETable( entropy->OFTable, + offcodeNCount, offcodeMaxValue, + OF_base, OF_bits, + offcodeLog); + dictPtr += offcodeHeaderSize; + } + + { short matchlengthNCount[MaxML+1]; + unsigned matchlengthMaxValue = MaxML, matchlengthLog; + size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr); + RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, ""); + RETURN_ERROR_IF(matchlengthMaxValue > MaxML, dictionary_corrupted, ""); + RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, ""); + ZSTD_buildFSETable( entropy->MLTable, + matchlengthNCount, matchlengthMaxValue, + ML_base, ML_bits, + matchlengthLog); + dictPtr += matchlengthHeaderSize; + } + + { short litlengthNCount[MaxLL+1]; + unsigned litlengthMaxValue = MaxLL, litlengthLog; + size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr); + RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, ""); + RETURN_ERROR_IF(litlengthMaxValue > MaxLL, dictionary_corrupted, ""); + RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, ""); + ZSTD_buildFSETable( entropy->LLTable, + litlengthNCount, litlengthMaxValue, + LL_base, LL_bits, + litlengthLog); + dictPtr += litlengthHeaderSize; + } + + RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, ""); + { int i; + size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12)); + for (i=0; i<3; i++) { + U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4; + RETURN_ERROR_IF(rep==0 || rep > dictContentSize, + dictionary_corrupted, ""); + entropy->rep[i] = rep; + } } + + return dictPtr - (const BYTE*)dict; +} + +static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize); + { U32 const magic = MEM_readLE32(dict); + if (magic != ZSTD_MAGIC_DICTIONARY) { + return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */ + } } + dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE); + + /* load entropy tables */ + { size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize); + RETURN_ERROR_IF(ZSTD_isError(eSize), dictionary_corrupted, ""); + dict = (const char*)dict + eSize; + dictSize -= eSize; + } + dctx->litEntropy = dctx->fseEntropy = 1; + + /* reference dictionary content */ + return ZSTD_refDictContent(dctx, dict, dictSize); +} + +size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx) +{ + assert(dctx != NULL); + dctx->expected = ZSTD_startingInputLength(dctx->format); /* dctx->format must be properly set */ + dctx->stage = ZSTDds_getFrameHeaderSize; + dctx->decodedSize = 0; + dctx->previousDstEnd = NULL; + dctx->prefixStart = NULL; + dctx->virtualStart = NULL; + dctx->dictEnd = NULL; + dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */ + dctx->litEntropy = dctx->fseEntropy = 0; + dctx->dictID = 0; + dctx->bType = bt_reserved; + ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue)); + memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */ + dctx->LLTptr = dctx->entropy.LLTable; + dctx->MLTptr = dctx->entropy.MLTable; + dctx->OFTptr = dctx->entropy.OFTable; + dctx->HUFptr = dctx->entropy.hufTable; + return 0; +} + +size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , ""); + if (dict && dictSize) + RETURN_ERROR_IF( + ZSTD_isError(ZSTD_decompress_insertDictionary(dctx, dict, dictSize)), + dictionary_corrupted, ""); + return 0; +} + + +/* ====== ZSTD_DDict ====== */ + +size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) +{ + DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict"); + assert(dctx != NULL); + if (ddict) { + const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict); + size_t const dictSize = ZSTD_DDict_dictSize(ddict); + const void* const dictEnd = dictStart + dictSize; + dctx->ddictIsCold = (dctx->dictEnd != dictEnd); + DEBUGLOG(4, "DDict is %s", + dctx->ddictIsCold ? "~cold~" : "hot!"); + } + FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , ""); + if (ddict) { /* NULL ddict is equivalent to no dictionary */ + ZSTD_copyDDictParameters(dctx, ddict); + } + return 0; +} + +/*! ZSTD_getDictID_fromDict() : + * Provides the dictID stored within dictionary. + * if @return == 0, the dictionary is not conformant with Zstandard specification. + * It can still be loaded, but as a content-only dictionary. */ +unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize) +{ + if (dictSize < 8) return 0; + if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0; + return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE); +} + +/*! ZSTD_getDictID_fromFrame() : + * Provides the dictID required to decompress frame stored within `src`. + * If @return == 0, the dictID could not be decoded. + * This could for one of the following reasons : + * - The frame does not require a dictionary (most common case). + * - The frame was built with dictID intentionally removed. + * Needed dictionary is a hidden information. + * Note : this use case also happens when using a non-conformant dictionary. + * - `srcSize` is too small, and as a result, frame header could not be decoded. + * Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`. + * - This is not a Zstandard frame. + * When identifying the exact failure cause, it's possible to use + * ZSTD_getFrameHeader(), which will provide a more precise error code. */ +unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize) +{ + ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0 }; + size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize); + if (ZSTD_isError(hError)) return 0; + return zfp.dictID; +} + + +/*! ZSTD_decompress_usingDDict() : +* Decompression using a pre-digested Dictionary +* Use dictionary without significant overhead. */ +size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, + const ZSTD_DDict* ddict) +{ + /* pass content and size in case legacy frames are encountered */ + return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, + NULL, 0, + ddict); +} + + +/*===================================== +* Streaming decompression +*====================================*/ + +ZSTD_DStream* ZSTD_createDStream(void) +{ + DEBUGLOG(3, "ZSTD_createDStream"); + return ZSTD_createDStream_advanced(ZSTD_defaultCMem); +} + +ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize) +{ + return ZSTD_initStaticDCtx(workspace, workspaceSize); +} + +ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem) +{ + return ZSTD_createDCtx_advanced(customMem); +} + +size_t ZSTD_freeDStream(ZSTD_DStream* zds) +{ + return ZSTD_freeDCtx(zds); +} + + +/* *** Initialization *** */ + +size_t ZSTD_DStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; } +size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; } + +size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType) +{ + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + ZSTD_clearDict(dctx); + if (dict && dictSize != 0) { + dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem); + RETURN_ERROR_IF(dctx->ddictLocal == NULL, memory_allocation, "NULL pointer!"); + dctx->ddict = dctx->ddictLocal; + dctx->dictUses = ZSTD_use_indefinitely; + } + return 0; +} + +size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto); +} + +size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize) +{ + return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto); +} + +size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType) +{ + FORWARD_IF_ERROR(ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType), ""); + dctx->dictUses = ZSTD_use_once; + return 0; +} + +size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize) +{ + return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent); +} + + +/* ZSTD_initDStream_usingDict() : + * return : expected size, aka ZSTD_startingInputLength(). + * this function cannot fail */ +size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize) +{ + DEBUGLOG(4, "ZSTD_initDStream_usingDict"); + FORWARD_IF_ERROR( ZSTD_DCtx_reset(zds, ZSTD_reset_session_only) , ""); + FORWARD_IF_ERROR( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) , ""); + return ZSTD_startingInputLength(zds->format); +} + +/* note : this variant can't fail */ +size_t ZSTD_initDStream(ZSTD_DStream* zds) +{ + DEBUGLOG(4, "ZSTD_initDStream"); + return ZSTD_initDStream_usingDDict(zds, NULL); +} + +/* ZSTD_initDStream_usingDDict() : + * ddict will just be referenced, and must outlive decompression session + * this function cannot fail */ +size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict) +{ + FORWARD_IF_ERROR( ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only) , ""); + FORWARD_IF_ERROR( ZSTD_DCtx_refDDict(dctx, ddict) , ""); + return ZSTD_startingInputLength(dctx->format); +} + +/* ZSTD_resetDStream() : + * return : expected size, aka ZSTD_startingInputLength(). + * this function cannot fail */ +size_t ZSTD_resetDStream(ZSTD_DStream* dctx) +{ + FORWARD_IF_ERROR(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only), ""); + return ZSTD_startingInputLength(dctx->format); +} + + +size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) +{ + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + ZSTD_clearDict(dctx); + if (ddict) { + dctx->ddict = ddict; + dctx->dictUses = ZSTD_use_indefinitely; + } + return 0; +} + +/* ZSTD_DCtx_setMaxWindowSize() : + * note : no direct equivalence in ZSTD_DCtx_setParameter, + * since this version sets windowSize, and the other sets windowLog */ +size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize) +{ + ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax); + size_t const min = (size_t)1 << bounds.lowerBound; + size_t const max = (size_t)1 << bounds.upperBound; + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + RETURN_ERROR_IF(maxWindowSize < min, parameter_outOfBound, ""); + RETURN_ERROR_IF(maxWindowSize > max, parameter_outOfBound, ""); + dctx->maxWindowSize = maxWindowSize; + return 0; +} + +size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format) +{ + return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, format); +} + +ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam) +{ + ZSTD_bounds bounds = { 0, 0, 0 }; + switch(dParam) { + case ZSTD_d_windowLogMax: + bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN; + bounds.upperBound = ZSTD_WINDOWLOG_MAX; + return bounds; + case ZSTD_d_format: + bounds.lowerBound = (int)ZSTD_f_zstd1; + bounds.upperBound = (int)ZSTD_f_zstd1_magicless; + ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless); + return bounds; + case ZSTD_d_stableOutBuffer: + bounds.lowerBound = (int)ZSTD_obm_buffered; + bounds.upperBound = (int)ZSTD_obm_stable; + return bounds; + default:; + } + bounds.error = ERROR(parameter_unsupported); + return bounds; +} + +/* ZSTD_dParam_withinBounds: + * @return 1 if value is within dParam bounds, + * 0 otherwise */ +static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value) +{ + ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam); + if (ZSTD_isError(bounds.error)) return 0; + if (value < bounds.lowerBound) return 0; + if (value > bounds.upperBound) return 0; + return 1; +} + +#define CHECK_DBOUNDS(p,v) { \ + RETURN_ERROR_IF(!ZSTD_dParam_withinBounds(p, v), parameter_outOfBound, ""); \ +} + +size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value) +{ + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + switch(dParam) { + case ZSTD_d_windowLogMax: + if (value == 0) value = ZSTD_WINDOWLOG_LIMIT_DEFAULT; + CHECK_DBOUNDS(ZSTD_d_windowLogMax, value); + dctx->maxWindowSize = ((size_t)1) << value; + return 0; + case ZSTD_d_format: + CHECK_DBOUNDS(ZSTD_d_format, value); + dctx->format = (ZSTD_format_e)value; + return 0; + case ZSTD_d_stableOutBuffer: + CHECK_DBOUNDS(ZSTD_d_stableOutBuffer, value); + dctx->outBufferMode = (ZSTD_outBufferMode_e)value; + return 0; + default:; + } + RETURN_ERROR(parameter_unsupported, ""); +} + +size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset) +{ + if ( (reset == ZSTD_reset_session_only) + || (reset == ZSTD_reset_session_and_parameters) ) { + dctx->streamStage = zdss_init; + dctx->noForwardProgress = 0; + } + if ( (reset == ZSTD_reset_parameters) + || (reset == ZSTD_reset_session_and_parameters) ) { + RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); + ZSTD_clearDict(dctx); + dctx->format = ZSTD_f_zstd1; + dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT; + } + return 0; +} + + +size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx) +{ + return ZSTD_sizeof_DCtx(dctx); +} + +size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize) +{ + size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX); + unsigned long long const neededRBSize = windowSize + blockSize + (WILDCOPY_OVERLENGTH * 2); + unsigned long long const neededSize = MIN(frameContentSize, neededRBSize); + size_t const minRBSize = (size_t) neededSize; + RETURN_ERROR_IF((unsigned long long)minRBSize != neededSize, + frameParameter_windowTooLarge, ""); + return minRBSize; +} + +size_t ZSTD_estimateDStreamSize(size_t windowSize) +{ + size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX); + size_t const inBuffSize = blockSize; /* no block can be larger */ + size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN); + return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize; +} + +size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize) +{ + U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX; /* note : should be user-selectable, but requires an additional parameter (or a dctx) */ + ZSTD_frameHeader zfh; + size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize); + if (ZSTD_isError(err)) return err; + RETURN_ERROR_IF(err>0, srcSize_wrong, ""); + RETURN_ERROR_IF(zfh.windowSize > windowSizeMax, + frameParameter_windowTooLarge, ""); + return ZSTD_estimateDStreamSize((size_t)zfh.windowSize); +} + + +/* ***** Decompression ***** */ + +static int ZSTD_DCtx_isOverflow(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize) +{ + return (zds->inBuffSize + zds->outBuffSize) >= (neededInBuffSize + neededOutBuffSize) * ZSTD_WORKSPACETOOLARGE_FACTOR; +} + +static void ZSTD_DCtx_updateOversizedDuration(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize) +{ + if (ZSTD_DCtx_isOverflow(zds, neededInBuffSize, neededOutBuffSize)) + zds->oversizedDuration++; + else + zds->oversizedDuration = 0; +} + +static int ZSTD_DCtx_isOversizedTooLong(ZSTD_DStream* zds) +{ + return zds->oversizedDuration >= ZSTD_WORKSPACETOOLARGE_MAXDURATION; +} + +/* Checks that the output buffer hasn't changed if ZSTD_obm_stable is used. */ +static size_t ZSTD_checkOutBuffer(ZSTD_DStream const* zds, ZSTD_outBuffer const* output) +{ + ZSTD_outBuffer const expect = zds->expectedOutBuffer; + /* No requirement when ZSTD_obm_stable is not enabled. */ + if (zds->outBufferMode != ZSTD_obm_stable) + return 0; + /* Any buffer is allowed in zdss_init, this must be the same for every other call until + * the context is reset. + */ + if (zds->streamStage == zdss_init) + return 0; + /* The buffer must match our expectation exactly. */ + if (expect.dst == output->dst && expect.pos == output->pos && expect.size == output->size) + return 0; + RETURN_ERROR(dstBuffer_wrong, "ZSTD_obm_stable enabled but output differs!"); +} + +/* Calls ZSTD_decompressContinue() with the right parameters for ZSTD_decompressStream() + * and updates the stage and the output buffer state. This call is extracted so it can be + * used both when reading directly from the ZSTD_inBuffer, and in buffered input mode. + * NOTE: You must break after calling this function since the streamStage is modified. + */ +static size_t ZSTD_decompressContinueStream( + ZSTD_DStream* zds, char** op, char* oend, + void const* src, size_t srcSize) { + int const isSkipFrame = ZSTD_isSkipFrame(zds); + if (zds->outBufferMode == ZSTD_obm_buffered) { + size_t const dstSize = isSkipFrame ? 0 : zds->outBuffSize - zds->outStart; + size_t const decodedSize = ZSTD_decompressContinue(zds, + zds->outBuff + zds->outStart, dstSize, src, srcSize); + FORWARD_IF_ERROR(decodedSize, ""); + if (!decodedSize && !isSkipFrame) { + zds->streamStage = zdss_read; + } else { + zds->outEnd = zds->outStart + decodedSize; + zds->streamStage = zdss_flush; + } + } else { + /* Write directly into the output buffer */ + size_t const dstSize = isSkipFrame ? 0 : oend - *op; + size_t const decodedSize = ZSTD_decompressContinue(zds, *op, dstSize, src, srcSize); + FORWARD_IF_ERROR(decodedSize, ""); + *op += decodedSize; + /* Flushing is not needed. */ + zds->streamStage = zdss_read; + assert(*op <= oend); + assert(zds->outBufferMode == ZSTD_obm_stable); + } + return 0; +} + +size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input) +{ + const char* const src = (const char*)input->src; + const char* const istart = input->pos != 0 ? src + input->pos : src; + const char* const iend = input->size != 0 ? src + input->size : src; + const char* ip = istart; + char* const dst = (char*)output->dst; + char* const ostart = output->pos != 0 ? dst + output->pos : dst; + char* const oend = output->size != 0 ? dst + output->size : dst; + char* op = ostart; + U32 someMoreWork = 1; + + DEBUGLOG(5, "ZSTD_decompressStream"); + RETURN_ERROR_IF( + input->pos > input->size, + srcSize_wrong, + "forbidden. in: pos: %u vs size: %u", + (U32)input->pos, (U32)input->size); + RETURN_ERROR_IF( + output->pos > output->size, + dstSize_tooSmall, + "forbidden. out: pos: %u vs size: %u", + (U32)output->pos, (U32)output->size); + DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos)); + FORWARD_IF_ERROR(ZSTD_checkOutBuffer(zds, output), ""); + + while (someMoreWork) { + switch(zds->streamStage) + { + case zdss_init : + DEBUGLOG(5, "stage zdss_init => transparent reset "); + zds->streamStage = zdss_loadHeader; + zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0; + zds->legacyVersion = 0; + zds->hostageByte = 0; + zds->expectedOutBuffer = *output; + /* fall-through */ + + case zdss_loadHeader : + DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip)); +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) + if (zds->legacyVersion) { + RETURN_ERROR_IF(zds->staticSize, memory_allocation, + "legacy support is incompatible with static dctx"); + { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input); + if (hint==0) zds->streamStage = zdss_init; + return hint; + } } +#endif + { size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format); + DEBUGLOG(5, "header size : %u", (U32)hSize); + if (ZSTD_isError(hSize)) { +#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) + U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart); + if (legacyVersion) { + ZSTD_DDict const* const ddict = ZSTD_getDDict(zds); + const void* const dict = ddict ? ZSTD_DDict_dictContent(ddict) : NULL; + size_t const dictSize = ddict ? ZSTD_DDict_dictSize(ddict) : 0; + DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion); + RETURN_ERROR_IF(zds->staticSize, memory_allocation, + "legacy support is incompatible with static dctx"); + FORWARD_IF_ERROR(ZSTD_initLegacyStream(&zds->legacyContext, + zds->previousLegacyVersion, legacyVersion, + dict, dictSize), ""); + zds->legacyVersion = zds->previousLegacyVersion = legacyVersion; + { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input); + if (hint==0) zds->streamStage = zdss_init; /* or stay in stage zdss_loadHeader */ + return hint; + } } +#endif + return hSize; /* error */ + } + if (hSize != 0) { /* need more input */ + size_t const toLoad = hSize - zds->lhSize; /* if hSize!=0, hSize > zds->lhSize */ + size_t const remainingInput = (size_t)(iend-ip); + assert(iend >= ip); + if (toLoad > remainingInput) { /* not enough input to load full header */ + if (remainingInput > 0) { + memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput); + zds->lhSize += remainingInput; + } + input->pos = input->size; + return (MAX((size_t)ZSTD_FRAMEHEADERSIZE_MIN(zds->format), hSize) - zds->lhSize) + ZSTD_blockHeaderSize; /* remaining header bytes + next block header */ + } + assert(ip != NULL); + memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad; + break; + } } + + /* check for single-pass mode opportunity */ + if (zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN + && zds->fParams.frameType != ZSTD_skippableFrame + && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) { + size_t const cSize = ZSTD_findFrameCompressedSize(istart, iend-istart); + if (cSize <= (size_t)(iend-istart)) { + /* shortcut : using single-pass mode */ + size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, oend-op, istart, cSize, ZSTD_getDDict(zds)); + if (ZSTD_isError(decompressedSize)) return decompressedSize; + DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()") + ip = istart + cSize; + op += decompressedSize; + zds->expected = 0; + zds->streamStage = zdss_init; + someMoreWork = 0; + break; + } } + + /* Check output buffer is large enough for ZSTD_odm_stable. */ + if (zds->outBufferMode == ZSTD_obm_stable + && zds->fParams.frameType != ZSTD_skippableFrame + && zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN + && (U64)(size_t)(oend-op) < zds->fParams.frameContentSize) { + RETURN_ERROR(dstSize_tooSmall, "ZSTD_obm_stable passed but ZSTD_outBuffer is too small"); + } + + /* Consume header (see ZSTDds_decodeFrameHeader) */ + DEBUGLOG(4, "Consume header"); + FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(zds, ZSTD_getDDict(zds)), ""); + + if ((MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ + zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE); + zds->stage = ZSTDds_skipFrame; + } else { + FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize), ""); + zds->expected = ZSTD_blockHeaderSize; + zds->stage = ZSTDds_decodeBlockHeader; + } + + /* control buffer memory usage */ + DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)", + (U32)(zds->fParams.windowSize >>10), + (U32)(zds->maxWindowSize >> 10) ); + zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN); + RETURN_ERROR_IF(zds->fParams.windowSize > zds->maxWindowSize, + frameParameter_windowTooLarge, ""); + + /* Adapt buffer sizes to frame header instructions */ + { size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */); + size_t const neededOutBuffSize = zds->outBufferMode == ZSTD_obm_buffered + ? ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize) + : 0; + + ZSTD_DCtx_updateOversizedDuration(zds, neededInBuffSize, neededOutBuffSize); + + { int const tooSmall = (zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize); + int const tooLarge = ZSTD_DCtx_isOversizedTooLong(zds); + + if (tooSmall || tooLarge) { + size_t const bufferSize = neededInBuffSize + neededOutBuffSize; + DEBUGLOG(4, "inBuff : from %u to %u", + (U32)zds->inBuffSize, (U32)neededInBuffSize); + DEBUGLOG(4, "outBuff : from %u to %u", + (U32)zds->outBuffSize, (U32)neededOutBuffSize); + if (zds->staticSize) { /* static DCtx */ + DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize); + assert(zds->staticSize >= sizeof(ZSTD_DCtx)); /* controlled at init */ + RETURN_ERROR_IF( + bufferSize > zds->staticSize - sizeof(ZSTD_DCtx), + memory_allocation, ""); + } else { + ZSTD_free(zds->inBuff, zds->customMem); + zds->inBuffSize = 0; + zds->outBuffSize = 0; + zds->inBuff = (char*)ZSTD_malloc(bufferSize, zds->customMem); + RETURN_ERROR_IF(zds->inBuff == NULL, memory_allocation, ""); + } + zds->inBuffSize = neededInBuffSize; + zds->outBuff = zds->inBuff + zds->inBuffSize; + zds->outBuffSize = neededOutBuffSize; + } } } + zds->streamStage = zdss_read; + /* fall-through */ + + case zdss_read: + DEBUGLOG(5, "stage zdss_read"); + { size_t const neededInSize = ZSTD_nextSrcSizeToDecompressWithInputSize(zds, iend - ip); + DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize); + if (neededInSize==0) { /* end of frame */ + zds->streamStage = zdss_init; + someMoreWork = 0; + break; + } + if ((size_t)(iend-ip) >= neededInSize) { /* decode directly from src */ + FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, ip, neededInSize), ""); + ip += neededInSize; + /* Function modifies the stage so we must break */ + break; + } } + if (ip==iend) { someMoreWork = 0; break; } /* no more input */ + zds->streamStage = zdss_load; + /* fall-through */ + + case zdss_load: + { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds); + size_t const toLoad = neededInSize - zds->inPos; + int const isSkipFrame = ZSTD_isSkipFrame(zds); + size_t loadedSize; + /* At this point we shouldn't be decompressing a block that we can stream. */ + assert(neededInSize == ZSTD_nextSrcSizeToDecompressWithInputSize(zds, iend - ip)); + if (isSkipFrame) { + loadedSize = MIN(toLoad, (size_t)(iend-ip)); + } else { + RETURN_ERROR_IF(toLoad > zds->inBuffSize - zds->inPos, + corruption_detected, + "should never happen"); + loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, iend-ip); + } + ip += loadedSize; + zds->inPos += loadedSize; + if (loadedSize < toLoad) { someMoreWork = 0; break; } /* not enough input, wait for more */ + + /* decode loaded input */ + zds->inPos = 0; /* input is consumed */ + FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, zds->inBuff, neededInSize), ""); + /* Function modifies the stage so we must break */ + break; + } + case zdss_flush: + { size_t const toFlushSize = zds->outEnd - zds->outStart; + size_t const flushedSize = ZSTD_limitCopy(op, oend-op, zds->outBuff + zds->outStart, toFlushSize); + op += flushedSize; + zds->outStart += flushedSize; + if (flushedSize == toFlushSize) { /* flush completed */ + zds->streamStage = zdss_read; + if ( (zds->outBuffSize < zds->fParams.frameContentSize) + && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) { + DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)", + (int)(zds->outBuffSize - zds->outStart), + (U32)zds->fParams.blockSizeMax); + zds->outStart = zds->outEnd = 0; + } + break; + } } + /* cannot complete flush */ + someMoreWork = 0; + break; + + default: + assert(0); /* impossible */ + RETURN_ERROR(GENERIC, "impossible to reach"); /* some compiler require default to do something */ + } } + + /* result */ + input->pos = (size_t)(ip - (const char*)(input->src)); + output->pos = (size_t)(op - (char*)(output->dst)); + + /* Update the expected output buffer for ZSTD_obm_stable. */ + zds->expectedOutBuffer = *output; + + if ((ip==istart) && (op==ostart)) { /* no forward progress */ + zds->noForwardProgress ++; + if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) { + RETURN_ERROR_IF(op==oend, dstSize_tooSmall, ""); + RETURN_ERROR_IF(ip==iend, srcSize_wrong, ""); + assert(0); + } + } else { + zds->noForwardProgress = 0; + } + { size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds); + if (!nextSrcSizeHint) { /* frame fully decoded */ + if (zds->outEnd == zds->outStart) { /* output fully flushed */ + if (zds->hostageByte) { + if (input->pos >= input->size) { + /* can't release hostage (not present) */ + zds->streamStage = zdss_read; + return 1; + } + input->pos++; /* release hostage */ + } /* zds->hostageByte */ + return 0; + } /* zds->outEnd == zds->outStart */ + if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */ + input->pos--; /* note : pos > 0, otherwise, impossible to finish reading last block */ + zds->hostageByte=1; + } + return 1; + } /* nextSrcSizeHint==0 */ + nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block); /* preload header of next block */ + assert(zds->inPos <= nextSrcSizeHint); + nextSrcSizeHint -= zds->inPos; /* part already loaded*/ + return nextSrcSizeHint; + } +} + +size_t ZSTD_decompressStream_simpleArgs ( + ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, size_t* dstPos, + const void* src, size_t srcSize, size_t* srcPos) +{ + ZSTD_outBuffer output = { dst, dstCapacity, *dstPos }; + ZSTD_inBuffer input = { src, srcSize, *srcPos }; + /* ZSTD_compress_generic() will check validity of dstPos and srcPos */ + size_t const cErr = ZSTD_decompressStream(dctx, &output, &input); + *dstPos = output.pos; + *srcPos = input.pos; + return cErr; +} +/**** ended inlining decompress/zstd_decompress.c ****/ +/**** start inlining decompress/zstd_decompress_block.c ****/ +/* + * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +/* zstd_decompress_block : + * this module takes care of decompressing _compressed_ block */ + +/*-******************************************************* +* Dependencies +*********************************************************/ +/**** skipping file: ../common/compiler.h ****/ +/**** skipping file: ../common/cpu.h ****/ +/**** skipping file: ../common/mem.h ****/ +#define FSE_STATIC_LINKING_ONLY +/**** skipping file: ../common/fse.h ****/ +#define HUF_STATIC_LINKING_ONLY +/**** skipping file: ../common/huf.h ****/ +/**** skipping file: ../common/zstd_internal.h ****/ +/**** skipping file: zstd_decompress_internal.h ****/ +/**** skipping file: zstd_ddict.h ****/ +/**** skipping file: zstd_decompress_block.h ****/ + +/*_******************************************************* +* Macros +**********************************************************/ + +/* These two optional macros force the use one way or another of the two + * ZSTD_decompressSequences implementations. You can't force in both directions + * at the same time. + */ +#if defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \ + defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG) +#error "Cannot force the use of the short and the long ZSTD_decompressSequences variants!" +#endif + + +/*_******************************************************* +* Memory operations +**********************************************************/ +static void ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); } + + +/*-************************************************************* + * Block decoding + ***************************************************************/ + +/*! ZSTD_getcBlockSize() : + * Provides the size of compressed block from block header `src` */ +size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, + blockProperties_t* bpPtr) +{ + RETURN_ERROR_IF(srcSize < ZSTD_blockHeaderSize, srcSize_wrong, ""); + + { U32 const cBlockHeader = MEM_readLE24(src); + U32 const cSize = cBlockHeader >> 3; + bpPtr->lastBlock = cBlockHeader & 1; + bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3); + bpPtr->origSize = cSize; /* only useful for RLE */ + if (bpPtr->blockType == bt_rle) return 1; + RETURN_ERROR_IF(bpPtr->blockType == bt_reserved, corruption_detected, ""); + return cSize; + } +} + + +/* Hidden declaration for fullbench */ +size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, + const void* src, size_t srcSize); +/*! ZSTD_decodeLiteralsBlock() : + * @return : nb of bytes read from src (< srcSize ) + * note : symbol not declared but exposed for fullbench */ +size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, + const void* src, size_t srcSize) /* note : srcSize < BLOCKSIZE */ +{ + DEBUGLOG(5, "ZSTD_decodeLiteralsBlock"); + RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, ""); + + { const BYTE* const istart = (const BYTE*) src; + symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3); + + switch(litEncType) + { + case set_repeat: + DEBUGLOG(5, "set_repeat flag : re-using stats from previous compressed literals block"); + RETURN_ERROR_IF(dctx->litEntropy==0, dictionary_corrupted, ""); + /* fall-through */ + + case set_compressed: + RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for case 3"); + { size_t lhSize, litSize, litCSize; + U32 singleStream=0; + U32 const lhlCode = (istart[0] >> 2) & 3; + U32 const lhc = MEM_readLE32(istart); + size_t hufSuccess; + switch(lhlCode) + { + case 0: case 1: default: /* note : default is impossible, since lhlCode into [0..3] */ + /* 2 - 2 - 10 - 10 */ + singleStream = !lhlCode; + lhSize = 3; + litSize = (lhc >> 4) & 0x3FF; + litCSize = (lhc >> 14) & 0x3FF; + break; + case 2: + /* 2 - 2 - 14 - 14 */ + lhSize = 4; + litSize = (lhc >> 4) & 0x3FFF; + litCSize = lhc >> 18; + break; + case 3: + /* 2 - 2 - 18 - 18 */ + lhSize = 5; + litSize = (lhc >> 4) & 0x3FFFF; + litCSize = (lhc >> 22) + ((size_t)istart[4] << 10); + break; + } + RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, ""); + RETURN_ERROR_IF(litCSize + lhSize > srcSize, corruption_detected, ""); + + /* prefetch huffman table if cold */ + if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) { + PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable)); + } + + if (litEncType==set_repeat) { + if (singleStream) { + hufSuccess = HUF_decompress1X_usingDTable_bmi2( + dctx->litBuffer, litSize, istart+lhSize, litCSize, + dctx->HUFptr, dctx->bmi2); + } else { + hufSuccess = HUF_decompress4X_usingDTable_bmi2( + dctx->litBuffer, litSize, istart+lhSize, litCSize, + dctx->HUFptr, dctx->bmi2); + } + } else { + if (singleStream) { +#if defined(HUF_FORCE_DECOMPRESS_X2) + hufSuccess = HUF_decompress1X_DCtx_wksp( + dctx->entropy.hufTable, dctx->litBuffer, litSize, + istart+lhSize, litCSize, dctx->workspace, + sizeof(dctx->workspace)); +#else + hufSuccess = HUF_decompress1X1_DCtx_wksp_bmi2( + dctx->entropy.hufTable, dctx->litBuffer, litSize, + istart+lhSize, litCSize, dctx->workspace, + sizeof(dctx->workspace), dctx->bmi2); +#endif + } else { + hufSuccess = HUF_decompress4X_hufOnly_wksp_bmi2( + dctx->entropy.hufTable, dctx->litBuffer, litSize, + istart+lhSize, litCSize, dctx->workspace, + sizeof(dctx->workspace), dctx->bmi2); + } + } + + RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, ""); + + dctx->litPtr = dctx->litBuffer; + dctx->litSize = litSize; + dctx->litEntropy = 1; + if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable; + memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH); + return litCSize + lhSize; + } + + case set_basic: + { size_t litSize, lhSize; + U32 const lhlCode = ((istart[0]) >> 2) & 3; + switch(lhlCode) + { + case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */ + lhSize = 1; + litSize = istart[0] >> 3; + break; + case 1: + lhSize = 2; + litSize = MEM_readLE16(istart) >> 4; + break; + case 3: + lhSize = 3; + litSize = MEM_readLE24(istart) >> 4; + break; + } + + if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */ + RETURN_ERROR_IF(litSize+lhSize > srcSize, corruption_detected, ""); + memcpy(dctx->litBuffer, istart+lhSize, litSize); + dctx->litPtr = dctx->litBuffer; + dctx->litSize = litSize; + memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH); + return lhSize+litSize; + } + /* direct reference into compressed stream */ + dctx->litPtr = istart+lhSize; + dctx->litSize = litSize; + return lhSize+litSize; + } + + case set_rle: + { U32 const lhlCode = ((istart[0]) >> 2) & 3; + size_t litSize, lhSize; + switch(lhlCode) + { + case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */ + lhSize = 1; + litSize = istart[0] >> 3; + break; + case 1: + lhSize = 2; + litSize = MEM_readLE16(istart) >> 4; + break; + case 3: + lhSize = 3; + litSize = MEM_readLE24(istart) >> 4; + RETURN_ERROR_IF(srcSize<4, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 3; here we need lhSize+1 = 4"); + break; + } + RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, ""); + memset(dctx->litBuffer, istart[lhSize], litSize + WILDCOPY_OVERLENGTH); + dctx->litPtr = dctx->litBuffer; + dctx->litSize = litSize; + return lhSize+1; + } + default: + RETURN_ERROR(corruption_detected, "impossible"); + } + } +} + +/* Default FSE distribution tables. + * These are pre-calculated FSE decoding tables using default distributions as defined in specification : + * https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#default-distributions + * They were generated programmatically with following method : + * - start from default distributions, present in /lib/common/zstd_internal.h + * - generate tables normally, using ZSTD_buildFSETable() + * - printout the content of tables + * - pretify output, report below, test with fuzzer to ensure it's correct */ + +/* Default FSE distribution table for Literal Lengths */ +static const ZSTD_seqSymbol LL_defaultDTable[(1<tableLog = 0; + DTableH->fastMode = 0; + + cell->nbBits = 0; + cell->nextState = 0; + assert(nbAddBits < 255); + cell->nbAdditionalBits = (BYTE)nbAddBits; + cell->baseValue = baseValue; +} + + +/* ZSTD_buildFSETable() : + * generate FSE decoding table for one symbol (ll, ml or off) + * cannot fail if input is valid => + * all inputs are presumed validated at this stage */ +void +ZSTD_buildFSETable(ZSTD_seqSymbol* dt, + const short* normalizedCounter, unsigned maxSymbolValue, + const U32* baseValue, const U32* nbAdditionalBits, + unsigned tableLog) +{ + ZSTD_seqSymbol* const tableDecode = dt+1; + U16 symbolNext[MaxSeq+1]; + + U32 const maxSV1 = maxSymbolValue + 1; + U32 const tableSize = 1 << tableLog; + U32 highThreshold = tableSize-1; + + /* Sanity Checks */ + assert(maxSymbolValue <= MaxSeq); + assert(tableLog <= MaxFSELog); + + /* Init, lay down lowprob symbols */ + { ZSTD_seqSymbol_header DTableH; + DTableH.tableLog = tableLog; + DTableH.fastMode = 1; + { S16 const largeLimit= (S16)(1 << (tableLog-1)); + U32 s; + for (s=0; s= largeLimit) DTableH.fastMode=0; + assert(normalizedCounter[s]>=0); + symbolNext[s] = (U16)normalizedCounter[s]; + } } } + memcpy(dt, &DTableH, sizeof(DTableH)); + } + + /* Spread symbols */ + { U32 const tableMask = tableSize-1; + U32 const step = FSE_TABLESTEP(tableSize); + U32 s, position = 0; + for (s=0; s highThreshold) position = (position + step) & tableMask; /* lowprob area */ + } } + assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */ + } + + /* Build Decoding table */ + { U32 u; + for (u=0; u max, corruption_detected, ""); + { U32 const symbol = *(const BYTE*)src; + U32 const baseline = baseValue[symbol]; + U32 const nbBits = nbAdditionalBits[symbol]; + ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits); + } + *DTablePtr = DTableSpace; + return 1; + case set_basic : + *DTablePtr = defaultTable; + return 0; + case set_repeat: + RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, ""); + /* prefetch FSE table if used */ + if (ddictIsCold && (nbSeq > 24 /* heuristic */)) { + const void* const pStart = *DTablePtr; + size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog)); + PREFETCH_AREA(pStart, pSize); + } + return 0; + case set_compressed : + { unsigned tableLog; + S16 norm[MaxSeq+1]; + size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize); + RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, ""); + RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, ""); + ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog); + *DTablePtr = DTableSpace; + return headerSize; + } + default : + assert(0); + RETURN_ERROR(GENERIC, "impossible"); + } +} + +size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, + const void* src, size_t srcSize) +{ + const BYTE* const istart = (const BYTE* const)src; + const BYTE* const iend = istart + srcSize; + const BYTE* ip = istart; + int nbSeq; + DEBUGLOG(5, "ZSTD_decodeSeqHeaders"); + + /* check */ + RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, ""); + + /* SeqHead */ + nbSeq = *ip++; + if (!nbSeq) { + *nbSeqPtr=0; + RETURN_ERROR_IF(srcSize != 1, srcSize_wrong, ""); + return 1; + } + if (nbSeq > 0x7F) { + if (nbSeq == 0xFF) { + RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, ""); + nbSeq = MEM_readLE16(ip) + LONGNBSEQ, ip+=2; + } else { + RETURN_ERROR_IF(ip >= iend, srcSize_wrong, ""); + nbSeq = ((nbSeq-0x80)<<8) + *ip++; + } + } + *nbSeqPtr = nbSeq; + + /* FSE table descriptors */ + RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */ + { symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6); + symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3); + symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3); + ip++; + + /* Build DTables */ + { size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr, + LLtype, MaxLL, LLFSELog, + ip, iend-ip, + LL_base, LL_bits, + LL_defaultDTable, dctx->fseEntropy, + dctx->ddictIsCold, nbSeq); + RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed"); + ip += llhSize; + } + + { size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr, + OFtype, MaxOff, OffFSELog, + ip, iend-ip, + OF_base, OF_bits, + OF_defaultDTable, dctx->fseEntropy, + dctx->ddictIsCold, nbSeq); + RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed"); + ip += ofhSize; + } + + { size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr, + MLtype, MaxML, MLFSELog, + ip, iend-ip, + ML_base, ML_bits, + ML_defaultDTable, dctx->fseEntropy, + dctx->ddictIsCold, nbSeq); + RETURN_ERROR_IF(ZSTD_isError(mlhSize), corruption_detected, "ZSTD_buildSeqTable failed"); + ip += mlhSize; + } + } + + return ip-istart; +} + + +typedef struct { + size_t litLength; + size_t matchLength; + size_t offset; + const BYTE* match; +} seq_t; + +typedef struct { + size_t state; + const ZSTD_seqSymbol* table; +} ZSTD_fseState; + +typedef struct { + BIT_DStream_t DStream; + ZSTD_fseState stateLL; + ZSTD_fseState stateOffb; + ZSTD_fseState stateML; + size_t prevOffset[ZSTD_REP_NUM]; + const BYTE* prefixStart; + const BYTE* dictEnd; + size_t pos; +} seqState_t; + +/*! ZSTD_overlapCopy8() : + * Copies 8 bytes from ip to op and updates op and ip where ip <= op. + * If the offset is < 8 then the offset is spread to at least 8 bytes. + * + * Precondition: *ip <= *op + * Postcondition: *op - *op >= 8 + */ +HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) { + assert(*ip <= *op); + if (offset < 8) { + /* close range match, overlap */ + static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */ + static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */ + int const sub2 = dec64table[offset]; + (*op)[0] = (*ip)[0]; + (*op)[1] = (*ip)[1]; + (*op)[2] = (*ip)[2]; + (*op)[3] = (*ip)[3]; + *ip += dec32table[offset]; + ZSTD_copy4(*op+4, *ip); + *ip -= sub2; + } else { + ZSTD_copy8(*op, *ip); + } + *ip += 8; + *op += 8; + assert(*op - *ip >= 8); +} + +/*! ZSTD_safecopy() : + * Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer + * and write up to 16 bytes past oend_w (op >= oend_w is allowed). + * This function is only called in the uncommon case where the sequence is near the end of the block. It + * should be fast for a single long sequence, but can be slow for several short sequences. + * + * @param ovtype controls the overlap detection + * - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart. + * - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart. + * The src buffer must be before the dst buffer. + */ +static void ZSTD_safecopy(BYTE* op, BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) { + ptrdiff_t const diff = op - ip; + BYTE* const oend = op + length; + + assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) || + (ovtype == ZSTD_overlap_src_before_dst && diff >= 0)); + + if (length < 8) { + /* Handle short lengths. */ + while (op < oend) *op++ = *ip++; + return; + } + if (ovtype == ZSTD_overlap_src_before_dst) { + /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */ + assert(length >= 8); + ZSTD_overlapCopy8(&op, &ip, diff); + assert(op - ip >= 8); + assert(op <= oend); + } + + if (oend <= oend_w) { + /* No risk of overwrite. */ + ZSTD_wildcopy(op, ip, length, ovtype); + return; + } + if (op <= oend_w) { + /* Wildcopy until we get close to the end. */ + assert(oend > oend_w); + ZSTD_wildcopy(op, ip, oend_w - op, ovtype); + ip += oend_w - op; + op = oend_w; + } + /* Handle the leftovers. */ + while (op < oend) *op++ = *ip++; +} + +/* ZSTD_execSequenceEnd(): + * This version handles cases that are near the end of the output buffer. It requires + * more careful checks to make sure there is no overflow. By separating out these hard + * and unlikely cases, we can speed up the common cases. + * + * NOTE: This function needs to be fast for a single long sequence, but doesn't need + * to be optimized for many small sequences, since those fall into ZSTD_execSequence(). + */ +FORCE_NOINLINE +size_t ZSTD_execSequenceEnd(BYTE* op, + BYTE* const oend, seq_t sequence, + const BYTE** litPtr, const BYTE* const litLimit, + const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd) +{ + BYTE* const oLitEnd = op + sequence.litLength; + size_t const sequenceLength = sequence.litLength + sequence.matchLength; + const BYTE* const iLitEnd = *litPtr + sequence.litLength; + const BYTE* match = oLitEnd - sequence.offset; + BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; + + /* bounds checks : careful of address space overflow in 32-bit mode */ + RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer"); + RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer"); + assert(op < op + sequenceLength); + assert(oLitEnd < op + sequenceLength); + + /* copy literals */ + ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap); + op = oLitEnd; + *litPtr = iLitEnd; + + /* copy Match */ + if (sequence.offset > (size_t)(oLitEnd - prefixStart)) { + /* offset beyond prefix */ + RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, ""); + match = dictEnd - (prefixStart-match); + if (match + sequence.matchLength <= dictEnd) { + memmove(oLitEnd, match, sequence.matchLength); + return sequenceLength; + } + /* span extDict & currentPrefixSegment */ + { size_t const length1 = dictEnd - match; + memmove(oLitEnd, match, length1); + op = oLitEnd + length1; + sequence.matchLength -= length1; + match = prefixStart; + } } + ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst); + return sequenceLength; +} + +HINT_INLINE +size_t ZSTD_execSequence(BYTE* op, + BYTE* const oend, seq_t sequence, + const BYTE** litPtr, const BYTE* const litLimit, + const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd) +{ + BYTE* const oLitEnd = op + sequence.litLength; + size_t const sequenceLength = sequence.litLength + sequence.matchLength; + BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */ + BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH; /* risk : address space underflow on oend=NULL */ + const BYTE* const iLitEnd = *litPtr + sequence.litLength; + const BYTE* match = oLitEnd - sequence.offset; + + assert(op != NULL /* Precondition */); + assert(oend_w < oend /* No underflow */); + /* Handle edge cases in a slow path: + * - Read beyond end of literals + * - Match end is within WILDCOPY_OVERLIMIT of oend + * - 32-bit mode and the match length overflows + */ + if (UNLIKELY( + iLitEnd > litLimit || + oMatchEnd > oend_w || + (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH))) + return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd); + + /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */ + assert(op <= oLitEnd /* No overflow */); + assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */); + assert(oMatchEnd <= oend /* No underflow */); + assert(iLitEnd <= litLimit /* Literal length is in bounds */); + assert(oLitEnd <= oend_w /* Can wildcopy literals */); + assert(oMatchEnd <= oend_w /* Can wildcopy matches */); + + /* Copy Literals: + * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9. + * We likely don't need the full 32-byte wildcopy. + */ + assert(WILDCOPY_OVERLENGTH >= 16); + ZSTD_copy16(op, (*litPtr)); + if (UNLIKELY(sequence.litLength > 16)) { + ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap); + } + op = oLitEnd; + *litPtr = iLitEnd; /* update for next sequence */ + + /* Copy Match */ + if (sequence.offset > (size_t)(oLitEnd - prefixStart)) { + /* offset beyond prefix -> go into extDict */ + RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, ""); + match = dictEnd + (match - prefixStart); + if (match + sequence.matchLength <= dictEnd) { + memmove(oLitEnd, match, sequence.matchLength); + return sequenceLength; + } + /* span extDict & currentPrefixSegment */ + { size_t const length1 = dictEnd - match; + memmove(oLitEnd, match, length1); + op = oLitEnd + length1; + sequence.matchLength -= length1; + match = prefixStart; + } } + /* Match within prefix of 1 or more bytes */ + assert(op <= oMatchEnd); + assert(oMatchEnd <= oend_w); + assert(match >= prefixStart); + assert(sequence.matchLength >= 1); + + /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy + * without overlap checking. + */ + if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) { + /* We bet on a full wildcopy for matches, since we expect matches to be + * longer than literals (in general). In silesia, ~10% of matches are longer + * than 16 bytes. + */ + ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap); + return sequenceLength; + } + assert(sequence.offset < WILDCOPY_VECLEN); + + /* Copy 8 bytes and spread the offset to be >= 8. */ + ZSTD_overlapCopy8(&op, &match, sequence.offset); + + /* If the match length is > 8 bytes, then continue with the wildcopy. */ + if (sequence.matchLength > 8) { + assert(op < oMatchEnd); + ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst); + } + return sequenceLength; +} + +static void +ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt) +{ + const void* ptr = dt; + const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr; + DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog); + DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits", + (U32)DStatePtr->state, DTableH->tableLog); + BIT_reloadDStream(bitD); + DStatePtr->table = dt + 1; +} + +FORCE_INLINE_TEMPLATE void +ZSTD_updateFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD) +{ + ZSTD_seqSymbol const DInfo = DStatePtr->table[DStatePtr->state]; + U32 const nbBits = DInfo.nbBits; + size_t const lowBits = BIT_readBits(bitD, nbBits); + DStatePtr->state = DInfo.nextState + lowBits; +} + +FORCE_INLINE_TEMPLATE void +ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, ZSTD_seqSymbol const DInfo) +{ + U32 const nbBits = DInfo.nbBits; + size_t const lowBits = BIT_readBits(bitD, nbBits); + DStatePtr->state = DInfo.nextState + lowBits; +} + +/* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum + * offset bits. But we can only read at most (STREAM_ACCUMULATOR_MIN_32 - 1) + * bits before reloading. This value is the maximum number of bytes we read + * after reloading when we are decoding long offsets. + */ +#define LONG_OFFSETS_MAX_EXTRA_BITS_32 \ + (ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32 \ + ? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32 \ + : 0) + +typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e; +typedef enum { ZSTD_p_noPrefetch=0, ZSTD_p_prefetch=1 } ZSTD_prefetch_e; + +FORCE_INLINE_TEMPLATE seq_t +ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, const ZSTD_prefetch_e prefetch) +{ + seq_t seq; + ZSTD_seqSymbol const llDInfo = seqState->stateLL.table[seqState->stateLL.state]; + ZSTD_seqSymbol const mlDInfo = seqState->stateML.table[seqState->stateML.state]; + ZSTD_seqSymbol const ofDInfo = seqState->stateOffb.table[seqState->stateOffb.state]; + U32 const llBase = llDInfo.baseValue; + U32 const mlBase = mlDInfo.baseValue; + U32 const ofBase = ofDInfo.baseValue; + BYTE const llBits = llDInfo.nbAdditionalBits; + BYTE const mlBits = mlDInfo.nbAdditionalBits; + BYTE const ofBits = ofDInfo.nbAdditionalBits; + BYTE const totalBits = llBits+mlBits+ofBits; + + /* sequence */ + { size_t offset; + if (ofBits > 1) { + ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1); + ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5); + assert(ofBits <= MaxOff); + if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) { + U32 const extraBits = ofBits - MIN(ofBits, 32 - seqState->DStream.bitsConsumed); + offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits); + BIT_reloadDStream(&seqState->DStream); + if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits); + assert(extraBits <= LONG_OFFSETS_MAX_EXTRA_BITS_32); /* to avoid another reload */ + } else { + offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */ + if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); + } + seqState->prevOffset[2] = seqState->prevOffset[1]; + seqState->prevOffset[1] = seqState->prevOffset[0]; + seqState->prevOffset[0] = offset; + } else { + U32 const ll0 = (llBase == 0); + if (LIKELY((ofBits == 0))) { + if (LIKELY(!ll0)) + offset = seqState->prevOffset[0]; + else { + offset = seqState->prevOffset[1]; + seqState->prevOffset[1] = seqState->prevOffset[0]; + seqState->prevOffset[0] = offset; + } + } else { + offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1); + { size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset]; + temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */ + if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1]; + seqState->prevOffset[1] = seqState->prevOffset[0]; + seqState->prevOffset[0] = offset = temp; + } } } + seq.offset = offset; + } + + seq.matchLength = mlBase; + if (mlBits > 0) + seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/); + + if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32)) + BIT_reloadDStream(&seqState->DStream); + if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog))) + BIT_reloadDStream(&seqState->DStream); + /* Ensure there are enough bits to read the rest of data in 64-bit mode. */ + ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64); + + seq.litLength = llBase; + if (llBits > 0) + seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/); + + if (MEM_32bits()) + BIT_reloadDStream(&seqState->DStream); + + DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u", + (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); + + if (prefetch == ZSTD_p_prefetch) { + size_t const pos = seqState->pos + seq.litLength; + const BYTE* const matchBase = (seq.offset > pos) ? seqState->dictEnd : seqState->prefixStart; + seq.match = matchBase + pos - seq.offset; /* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted. + * No consequence though : no memory access will occur, offset is only used for prefetching */ + seqState->pos = pos + seq.matchLength; + } + + /* ANS state update + * gcc-9.0.0 does 2.5% worse with ZSTD_updateFseStateWithDInfo(). + * clang-9.2.0 does 7% worse with ZSTD_updateFseState(). + * Naturally it seems like ZSTD_updateFseStateWithDInfo() should be the + * better option, so it is the default for other compilers. But, if you + * measure that it is worse, please put up a pull request. + */ + { +#if defined(__GNUC__) && !defined(__clang__) + const int kUseUpdateFseState = 1; +#else + const int kUseUpdateFseState = 0; +#endif + if (kUseUpdateFseState) { + ZSTD_updateFseState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */ + ZSTD_updateFseState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */ + if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */ + ZSTD_updateFseState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */ + } else { + ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llDInfo); /* <= 9 bits */ + ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlDInfo); /* <= 9 bits */ + if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */ + ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofDInfo); /* <= 8 bits */ + } + } + + return seq; +} + +#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION +MEM_STATIC int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd) +{ + size_t const windowSize = dctx->fParams.windowSize; + /* No dictionary used. */ + if (dctx->dictContentEndForFuzzing == NULL) return 0; + /* Dictionary is our prefix. */ + if (prefixStart == dctx->dictContentBeginForFuzzing) return 1; + /* Dictionary is not our ext-dict. */ + if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0; + /* Dictionary is not within our window size. */ + if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0; + /* Dictionary is active. */ + return 1; +} + +MEM_STATIC void ZSTD_assertValidSequence( + ZSTD_DCtx const* dctx, + BYTE const* op, BYTE const* oend, + seq_t const seq, + BYTE const* prefixStart, BYTE const* virtualStart) +{ +#if DEBUGLEVEL >= 1 + size_t const windowSize = dctx->fParams.windowSize; + size_t const sequenceSize = seq.litLength + seq.matchLength; + BYTE const* const oLitEnd = op + seq.litLength; + DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u", + (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); + assert(op <= oend); + assert((size_t)(oend - op) >= sequenceSize); + assert(sequenceSize <= ZSTD_BLOCKSIZE_MAX); + if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) { + size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing); + /* Offset must be within the dictionary. */ + assert(seq.offset <= (size_t)(oLitEnd - virtualStart)); + assert(seq.offset <= windowSize + dictSize); + } else { + /* Offset must be within our window. */ + assert(seq.offset <= windowSize); + } +#else + (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart; +#endif +} +#endif + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG +FORCE_INLINE_TEMPLATE size_t +DONT_VECTORIZE +ZSTD_decompressSequences_body( ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset, + const int frame) +{ + const BYTE* ip = (const BYTE*)seqStart; + const BYTE* const iend = ip + seqSize; + BYTE* const ostart = (BYTE* const)dst; + BYTE* const oend = ostart + maxDstSize; + BYTE* op = ostart; + const BYTE* litPtr = dctx->litPtr; + const BYTE* const litEnd = litPtr + dctx->litSize; + const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart); + const BYTE* const vBase = (const BYTE*) (dctx->virtualStart); + const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd); + DEBUGLOG(5, "ZSTD_decompressSequences_body"); + (void)frame; + + /* Regen sequences */ + if (nbSeq) { + seqState_t seqState; + size_t error = 0; + dctx->fseEntropy = 1; + { U32 i; for (i=0; ientropy.rep[i]; } + RETURN_ERROR_IF( + ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)), + corruption_detected, ""); + ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr); + ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr); + ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr); + assert(dst != NULL); + + ZSTD_STATIC_ASSERT( + BIT_DStream_unfinished < BIT_DStream_completed && + BIT_DStream_endOfBuffer < BIT_DStream_completed && + BIT_DStream_completed < BIT_DStream_overflow); + +#if defined(__GNUC__) && defined(__x86_64__) + /* Align the decompression loop to 32 + 16 bytes. + * + * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression + * speed swings based on the alignment of the decompression loop. This + * performance swing is caused by parts of the decompression loop falling + * out of the DSB. The entire decompression loop should fit in the DSB, + * when it can't we get much worse performance. You can measure if you've + * hit the good case or the bad case with this perf command for some + * compressed file test.zst: + * + * perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \ + * -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst + * + * If you see most cycles served out of the MITE you've hit the bad case. + * If you see most cycles served out of the DSB you've hit the good case. + * If it is pretty even then you may be in an okay case. + * + * I've been able to reproduce this issue on the following CPUs: + * - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9 + * Use Instruments->Counters to get DSB/MITE cycles. + * I never got performance swings, but I was able to + * go from the good case of mostly DSB to half of the + * cycles served from MITE. + * - Coffeelake: Intel i9-9900k + * + * I haven't been able to reproduce the instability or DSB misses on any + * of the following CPUS: + * - Haswell + * - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH + * - Skylake + * + * If you are seeing performance stability this script can help test. + * It tests on 4 commits in zstd where I saw performance change. + * + * https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4 + */ + __asm__(".p2align 5"); + __asm__("nop"); + __asm__(".p2align 4"); +#endif + for ( ; ; ) { + seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_noPrefetch); + size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); +#endif + DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); + BIT_reloadDStream(&(seqState.DStream)); + /* gcc and clang both don't like early returns in this loop. + * gcc doesn't like early breaks either. + * Instead save an error and report it at the end. + * When there is an error, don't increment op, so we don't + * overwrite. + */ + if (UNLIKELY(ZSTD_isError(oneSeqSize))) error = oneSeqSize; + else op += oneSeqSize; + if (UNLIKELY(!--nbSeq)) break; + } + + /* check if reached exact end */ + DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq); + if (ZSTD_isError(error)) return error; + RETURN_ERROR_IF(nbSeq, corruption_detected, ""); + RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, ""); + /* save reps for next block */ + { U32 i; for (i=0; ientropy.rep[i] = (U32)(seqState.prevOffset[i]); } + } + + /* last literal segment */ + { size_t const lastLLSize = litEnd - litPtr; + RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, ""); + if (op != NULL) { + memcpy(op, litPtr, lastLLSize); + op += lastLLSize; + } + } + + return op-ostart; +} + +static size_t +ZSTD_decompressSequences_default(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset, + const int frame) +{ + return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT +FORCE_INLINE_TEMPLATE size_t +ZSTD_decompressSequencesLong_body( + ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset, + const int frame) +{ + const BYTE* ip = (const BYTE*)seqStart; + const BYTE* const iend = ip + seqSize; + BYTE* const ostart = (BYTE* const)dst; + BYTE* const oend = ostart + maxDstSize; + BYTE* op = ostart; + const BYTE* litPtr = dctx->litPtr; + const BYTE* const litEnd = litPtr + dctx->litSize; + const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart); + const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart); + const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd); + (void)frame; + + /* Regen sequences */ + if (nbSeq) { +#define STORED_SEQS 4 +#define STORED_SEQS_MASK (STORED_SEQS-1) +#define ADVANCED_SEQS 4 + seq_t sequences[STORED_SEQS]; + int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS); + seqState_t seqState; + int seqNb; + dctx->fseEntropy = 1; + { int i; for (i=0; ientropy.rep[i]; } + seqState.prefixStart = prefixStart; + seqState.pos = (size_t)(op-prefixStart); + seqState.dictEnd = dictEnd; + assert(dst != NULL); + assert(iend >= ip); + RETURN_ERROR_IF( + ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)), + corruption_detected, ""); + ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr); + ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr); + ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr); + + /* prepare in advance */ + for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNbentropy.rep[i] = (U32)(seqState.prevOffset[i]); } + } + + /* last literal segment */ + { size_t const lastLLSize = litEnd - litPtr; + RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, ""); + if (op != NULL) { + memcpy(op, litPtr, lastLLSize); + op += lastLLSize; + } + } + + return op-ostart; +} + +static size_t +ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset, + const int frame) +{ + return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ + + + +#if DYNAMIC_BMI2 + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG +static TARGET_ATTRIBUTE("bmi2") size_t +DONT_VECTORIZE +ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset, + const int frame) +{ + return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT +static TARGET_ATTRIBUTE("bmi2") size_t +ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset, + const int frame) +{ + return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ + +#endif /* DYNAMIC_BMI2 */ + +typedef size_t (*ZSTD_decompressSequences_t)( + ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset, + const int frame); + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG +static size_t +ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset, + const int frame) +{ + DEBUGLOG(5, "ZSTD_decompressSequences"); +#if DYNAMIC_BMI2 + if (dctx->bmi2) { + return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + } +#endif + return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ + + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT +/* ZSTD_decompressSequencesLong() : + * decompression function triggered when a minimum share of offsets is considered "long", + * aka out of cache. + * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance". + * This function will try to mitigate main memory latency through the use of prefetching */ +static size_t +ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx, + void* dst, size_t maxDstSize, + const void* seqStart, size_t seqSize, int nbSeq, + const ZSTD_longOffset_e isLongOffset, + const int frame) +{ + DEBUGLOG(5, "ZSTD_decompressSequencesLong"); +#if DYNAMIC_BMI2 + if (dctx->bmi2) { + return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + } +#endif + return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); +} +#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ + + + +#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \ + !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG) +/* ZSTD_getLongOffsetsShare() : + * condition : offTable must be valid + * @return : "share" of long offsets (arbitrarily defined as > (1<<23)) + * compared to maximum possible of (1< 22) total += 1; + } + + assert(tableLog <= OffFSELog); + total <<= (OffFSELog - tableLog); /* scale to OffFSELog */ + + return total; +} +#endif + +size_t +ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize, const int frame) +{ /* blockType == blockCompressed */ + const BYTE* ip = (const BYTE*)src; + /* isLongOffset must be true if there are long offsets. + * Offsets are long if they are larger than 2^STREAM_ACCUMULATOR_MIN. + * We don't expect that to be the case in 64-bit mode. + * In block mode, window size is not known, so we have to be conservative. + * (note: but it could be evaluated from current-lowLimit) + */ + ZSTD_longOffset_e const isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (!frame || (dctx->fParams.windowSize > (1ULL << STREAM_ACCUMULATOR_MIN)))); + DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize); + + RETURN_ERROR_IF(srcSize >= ZSTD_BLOCKSIZE_MAX, srcSize_wrong, ""); + + /* Decode literals section */ + { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize); + DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : %u", (U32)litCSize); + if (ZSTD_isError(litCSize)) return litCSize; + ip += litCSize; + srcSize -= litCSize; + } + + /* Build Decoding Tables */ + { + /* These macros control at build-time which decompressor implementation + * we use. If neither is defined, we do some inspection and dispatch at + * runtime. + */ +#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \ + !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG) + int usePrefetchDecoder = dctx->ddictIsCold; +#endif + int nbSeq; + size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize); + if (ZSTD_isError(seqHSize)) return seqHSize; + ip += seqHSize; + srcSize -= seqHSize; + + RETURN_ERROR_IF(dst == NULL && nbSeq > 0, dstSize_tooSmall, "NULL not handled"); + +#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \ + !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG) + if ( !usePrefetchDecoder + && (!frame || (dctx->fParams.windowSize > (1<<24))) + && (nbSeq>ADVANCED_SEQS) ) { /* could probably use a larger nbSeq limit */ + U32 const shareLongOffsets = ZSTD_getLongOffsetsShare(dctx->OFTptr); + U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */ + usePrefetchDecoder = (shareLongOffsets >= minShare); + } +#endif + + dctx->ddictIsCold = 0; + +#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \ + !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG) + if (usePrefetchDecoder) +#endif +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT + return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame); +#endif + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG + /* else */ + return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame); +#endif + } +} + + +void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst) +{ + if (dst != dctx->previousDstEnd) { /* not contiguous */ + dctx->dictEnd = dctx->previousDstEnd; + dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart)); + dctx->prefixStart = dst; + dctx->previousDstEnd = dst; + } +} + + +size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + const void* src, size_t srcSize) +{ + size_t dSize; + ZSTD_checkContinuity(dctx, dst); + dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0); + dctx->previousDstEnd = (char*)dst + dSize; + return dSize; +} +/**** ended inlining decompress/zstd_decompress_block.c ****/ diff --git a/src/acpi.js b/src/acpi.js new file mode 100644 index 0000000..daace1d --- /dev/null +++ b/src/acpi.js @@ -0,0 +1,207 @@ +"use strict"; + +// http://www.uefi.org/sites/default/files/resources/ACPI_6_1.pdf + +/** @const */ +var PMTIMER_FREQ_SECONDS = 3579545; + +/** + * @constructor + * @param {CPU} cpu + */ +function ACPI(cpu) +{ + /** @type {CPU} */ + this.cpu = cpu; + + var io = cpu.io; + + var acpi = { + pci_id: 0x07 << 3, + pci_space: [ + 0x86, 0x80, 0x13, 0x71, 0x07, 0x00, 0x80, 0x02, 0x08, 0x00, 0x80, 0x06, 0x00, 0x00, 0x80, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00, + ], + pci_bars: [], + name: "acpi", + }; + + // 00:07.0 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 08) + cpu.devices.pci.register_device(acpi); + + this.timer_last_value = 0; + this.timer_imprecision_offset = 0; + + this.status = 1; + this.pm1_status = 0; + this.pm1_enable = 0; + this.last_timer = this.get_timer(v86.microtick()); + + this.gpe = new Uint8Array(4); + + io.register_read(0xB000, this, undefined, function() + { + dbg_log("ACPI pm1_status read", LOG_ACPI); + return this.pm1_status; + }); + io.register_write(0xB000, this, undefined, function(value) + { + dbg_log("ACPI pm1_status write: " + h(value, 4), LOG_ACPI); + this.pm1_status &= ~value; + }); + + io.register_read(0xB002, this, undefined, function() + { + dbg_log("ACPI pm1_enable read", LOG_ACPI); + return this.pm1_enable; + }); + io.register_write(0xB002, this, undefined, function(value) + { + dbg_log("ACPI pm1_enable write: " + h(value), LOG_ACPI); + this.pm1_enable = value; + }); + + // ACPI status + io.register_read(0xB004, this, undefined, function() + { + dbg_log("ACPI status read", LOG_ACPI); + return this.status; + }); + io.register_write(0xB004, this, undefined, function(value) + { + dbg_log("ACPI status write: " + h(value), LOG_ACPI); + this.status = value; + }); + + // ACPI, pmtimer + io.register_read(0xB008, this, undefined, undefined, function() + { + var value = this.get_timer(v86.microtick()) & 0xFFFFFF; + //dbg_log("pmtimer read: " + h(value >>> 0), LOG_ACPI); + return value; + }); + + // ACPI, gpe + io.register_read(0xAFE0, this, function() + { + dbg_log("Read gpe#0", LOG_ACPI); + return this.gpe[0]; + }); + io.register_read(0xAFE1, this, function() + { + dbg_log("Read gpe#1", LOG_ACPI); + return this.gpe[1]; + }); + io.register_read(0xAFE2, this, function() + { + dbg_log("Read gpe#2", LOG_ACPI); + return this.gpe[2]; + }); + io.register_read(0xAFE3, this, function() + { + dbg_log("Read gpe#3", LOG_ACPI); + return this.gpe[3]; + }); + + io.register_write(0xAFE0, this, function(value) + { + dbg_log("Write gpe#0: " + h(value), LOG_ACPI); + this.gpe[0] = value; + }); + io.register_write(0xAFE1, this, function(value) + { + dbg_log("Write gpe#1: " + h(value), LOG_ACPI); + this.gpe[1] = value; + }); + io.register_write(0xAFE2, this, function(value) + { + dbg_log("Write gpe#2: " + h(value), LOG_ACPI); + this.gpe[2] = value; + }); + io.register_write(0xAFE3, this, function(value) + { + dbg_log("Write gpe#3: " + h(value), LOG_ACPI); + this.gpe[3] = value; + }); +} + +ACPI.prototype.timer = function(now) +{ + var timer = this.get_timer(now); + var highest_bit_changed = ((timer ^ this.last_timer) & (1 << 23)) !== 0; + + if((this.pm1_enable & 1) && highest_bit_changed) + { + dbg_log("ACPI raise irq", LOG_ACPI); + this.pm1_status |= 1; + this.cpu.device_raise_irq(9); + } + else + { + this.cpu.device_lower_irq(9); + } + + this.last_timer = timer; + return 100; // TODO +}; + +ACPI.prototype.get_timer = function(now) +{ + const t = Math.round(now * (PMTIMER_FREQ_SECONDS / 1000)); + + // Due to the low precision of JavaScript's time functions we increment the + // returned timer value every time it is read + + if(t === this.timer_last_value) + { + // don't go past 1ms + + if(this.timer_imprecision_offset < PMTIMER_FREQ_SECONDS / 1000) + { + this.timer_imprecision_offset++; + } + } + else + { + dbg_assert(t > this.timer_last_value); + + const previous_timer = this.timer_last_value + this.timer_imprecision_offset; + + // don't go back in time + + if(previous_timer <= t) + { + this.timer_imprecision_offset = 0; + this.timer_last_value = t; + } + else + { + dbg_log("Warning: Overshot pmtimer, waiting;" + + " current=" + t + + " last=" + this.timer_last_value + + " offset=" + this.timer_imprecision_offset, LOG_ACPI); + } + } + + return this.timer_last_value + this.timer_imprecision_offset; +}; + +ACPI.prototype.get_state = function() +{ + var state = []; + state[0] = this.status; + state[1] = this.pm1_status; + state[2] = this.pm1_enable; + state[3] = this.gpe; + return state; +}; + +ACPI.prototype.set_state = function(state) +{ + this.status = state[0]; + this.pm1_status = state[1]; + this.pm1_enable = state[2]; + this.gpe = state[3]; +}; diff --git a/src/apic.js b/src/apic.js new file mode 100644 index 0000000..5b33eea --- /dev/null +++ b/src/apic.js @@ -0,0 +1,630 @@ +"use strict"; + +// See Intel's System Programming Guide + + +/** @const */ +var APIC_LOG_VERBOSE = false; + +/** @const */ +var APIC_ADDRESS = 0xFEE00000; + +/** @const */ +var APIC_TIMER_MODE_MASK = 3 << 17; + +/** @const */ +var APIC_TIMER_MODE_ONE_SHOT = 0; + +/** @const */ +var APIC_TIMER_MODE_PERIODIC = 1 << 17; + +/** @const */ +var APIC_TIMER_MODE_TSC = 2 << 17; + + +/** @const */ +var DELIVERY_MODES = [ + "Fixed (0)", + "Lowest Prio (1)", + "SMI (2)", + "Reserved (3)", + "NMI (4)", + "INIT (5)", + "Reserved (6)", + "ExtINT (7)", +]; + +/** @const */ +var DESTINATION_MODES = ["physical", "logical"]; + + +/** + * @constructor + * @param {CPU} cpu + */ +function APIC(cpu) +{ + /** @type {CPU} */ + this.cpu = cpu; + + this.apic_id = 0; + + this.timer_divider = 0; + this.timer_divider_shift = 1; + this.timer_initial_count = 0; + this.timer_current_count = 0; + + this.next_tick = v86.microtick(); + + this.lvt_timer = IOAPIC_CONFIG_MASKED; + this.lvt_perf_counter = IOAPIC_CONFIG_MASKED; + this.lvt_int0 = IOAPIC_CONFIG_MASKED; + this.lvt_int1 = IOAPIC_CONFIG_MASKED; + this.lvt_error = IOAPIC_CONFIG_MASKED; + + this.tpr = 0; + this.icr0 = 0; + this.icr1 = 0; + + this.irr = new Int32Array(8); + this.isr = new Int32Array(8); + this.tmr = new Int32Array(8); + + this.spurious_vector = 0xFE; + this.destination_format = -1; + this.local_destination = 0; + + this.error = 0; + this.read_error = 0; + + cpu.io.mmap_register(APIC_ADDRESS, 0x100000, + (addr) => + { + dbg_log("Unsupported read8 from apic: " + h(addr >>> 0), LOG_APIC); + var off = addr & 3; + addr &= ~3; + return this.read32(addr) >> (off * 8) & 0xFF; + }, + (addr, value) => + { + dbg_log("Unsupported write8 from apic: " + h(addr) + " <- " + h(value), LOG_APIC); + dbg_trace(); + dbg_assert(false); + }, + (addr) => this.read32(addr), + (addr, value) => this.write32(addr, value) + ); +} + +APIC.prototype.read32 = function(addr) +{ + addr = addr - APIC_ADDRESS | 0; + + switch(addr) + { + case 0x20: + dbg_log("APIC read id", LOG_APIC); + return this.apic_id; + + case 0x30: + // version + dbg_log("APIC read version", LOG_APIC); + return 0x50014; + + case 0x80: + APIC_LOG_VERBOSE && dbg_log("APIC read tpr", LOG_APIC); + return this.tpr; + + case 0xD0: + dbg_log("Read local destination", LOG_APIC); + return this.local_destination; + + case 0xE0: + dbg_log("Read destination format", LOG_APIC); + return this.destination_format; + + case 0xF0: + return this.spurious_vector; + + case 0x100: + case 0x110: + case 0x120: + case 0x130: + case 0x140: + case 0x150: + case 0x160: + case 0x170: + var index = addr - 0x100 >> 4; + dbg_log("Read isr " + index + ": " + h(this.isr[index] >>> 0, 8), LOG_APIC); + return this.isr[index]; + + case 0x180: + case 0x190: + case 0x1A0: + case 0x1B0: + case 0x1C0: + case 0x1D0: + case 0x1E0: + case 0x1F0: + var index = addr - 0x180 >> 4; + dbg_log("Read tmr " + index + ": " + h(this.tmr[index] >>> 0, 8), LOG_APIC); + return this.tmr[index]; + + case 0x200: + case 0x210: + case 0x220: + case 0x230: + case 0x240: + case 0x250: + case 0x260: + case 0x270: + var index = addr - 0x200 >> 4; + dbg_log("Read irr " + index + ": " + h(this.irr[index] >>> 0, 8), LOG_APIC); + return this.irr[index]; + + case 0x280: + dbg_log("Read error: " + h(this.read_error >>> 0, 8), LOG_APIC); + return this.read_error; + + case 0x300: + APIC_LOG_VERBOSE && dbg_log("APIC read icr0", LOG_APIC); + return this.icr0; + + case 0x310: + dbg_log("APIC read icr1", LOG_APIC); + return this.icr1; + + case 0x320: + dbg_log("read timer lvt", LOG_APIC); + return this.lvt_timer; + + case 0x340: + dbg_log("read lvt perf counter", LOG_APIC); + return this.lvt_perf_counter; + + case 0x350: + dbg_log("read lvt int0", LOG_APIC); + return this.lvt_int0; + + case 0x360: + dbg_log("read lvt int1", LOG_APIC); + return this.lvt_int1; + + case 0x370: + dbg_log("read lvt error", LOG_APIC); + return this.lvt_error; + + case 0x3E0: + // divider + dbg_log("read timer divider", LOG_APIC); + return this.timer_divider; + + case 0x380: + dbg_log("read timer initial count", LOG_APIC); + return this.timer_initial_count; + + case 0x390: + dbg_log("read timer current count: " + h(this.timer_current_count >>> 0, 8), LOG_APIC); + return this.timer_current_count; + + default: + dbg_log("APIC read " + h(addr), LOG_APIC); + dbg_assert(false); + return 0; + } +}; + +APIC.prototype.write32 = function(addr, value) +{ + addr = addr - APIC_ADDRESS | 0; + + switch(addr) + { + case 0x30: + // version + dbg_log("APIC write version: " + h(value >>> 0, 8) + ", ignored", LOG_APIC); + break; + + case 0x80: + APIC_LOG_VERBOSE && dbg_log("Set tpr: " + h(value & 0xFF, 2), LOG_APIC); + this.tpr = value & 0xFF; + this.check_vector(); + break; + + case 0xB0: + var highest_isr = this.highest_isr(); + if(highest_isr !== -1) + { + APIC_LOG_VERBOSE && dbg_log("eoi: " + h(value >>> 0, 8) + " for vector " + h(highest_isr), LOG_APIC); + this.register_clear_bit(this.isr, highest_isr); + if(this.register_get_bit(this.tmr, highest_isr)) + { + // Send eoi to all IO APICs + this.cpu.devices.ioapic.remote_eoi(highest_isr); + } + this.check_vector(); + } + else + { + dbg_log("Bad eoi: No isr set", LOG_APIC); + } + break; + + case 0xD0: + dbg_log("Set local destination: " + h(value >>> 0, 8), LOG_APIC); + this.local_destination = value & 0xFF000000; + break; + + case 0xE0: + dbg_log("Set destination format: " + h(value >>> 0, 8), LOG_APIC); + this.destination_format = value | 0xFFFFFF; + break; + + case 0xF0: + dbg_log("Set spurious vector: " + h(value >>> 0, 8), LOG_APIC); + this.spurious_vector = value; + break; + + case 0x280: + // updated readable error register with real error + dbg_log("Write error: " + h(value >>> 0, 8), LOG_APIC); + this.read_error = this.error; + this.error = 0; + break; + + case 0x300: + var vector = value & 0xFF; + var delivery_mode = value >> 8 & 7; + var destination_mode = value >> 11 & 1; + var is_level = value >> 15 & 1; + var destination_shorthand = value >> 18 & 3; + var destination = this.icr1 >>> 24; + dbg_log("APIC write icr0: " + h(value, 8) + " vector=" + h(vector, 2) + " " + + "destination_mode=" + DESTINATION_MODES[destination_mode] + " delivery_mode=" + DELIVERY_MODES[delivery_mode] + " " + + "destination_shorthand=" + ["no", "self", "all with self", "all without self"][destination_shorthand], LOG_APIC); + + value &= ~(1 << 12); + this.icr0 = value; + + if(destination_shorthand === 0) + { + // no shorthand + this.route(vector, delivery_mode, is_level, destination, destination_mode); + } + else if(destination_shorthand === 1) + { + // self + this.deliver(vector, IOAPIC_DELIVERY_FIXED, is_level); + } + else if(destination_shorthand === 2) + { + // all including self + this.deliver(vector, delivery_mode, is_level); + } + else if(destination_shorthand === 3) + { + // all but self + } + else + { + dbg_assert(false); + } + break; + + case 0x310: + dbg_log("APIC write icr1: " + h(value >>> 0, 8), LOG_APIC); + this.icr1 = value; + break; + + case 0x320: + dbg_log("timer lvt: " + h(value >>> 0, 8), LOG_APIC); + this.lvt_timer = value; + break; + + case 0x340: + dbg_log("lvt perf counter: " + h(value >>> 0, 8), LOG_APIC); + this.lvt_perf_counter = value; + break; + + case 0x350: + dbg_log("lvt int0: " + h(value >>> 0, 8), LOG_APIC); + this.lvt_int0 = value; + break; + + case 0x360: + dbg_log("lvt int1: " + h(value >>> 0, 8), LOG_APIC); + this.lvt_int1 = value; + break; + + case 0x370: + dbg_log("lvt error: " + h(value >>> 0, 8), LOG_APIC); + this.lvt_error = value; + break; + + case 0x3E0: + dbg_log("timer divider: " + h(value >>> 0, 8), LOG_APIC); + this.timer_divider = value; + + var divide_shift = value & 0b11 | (value & 0b1000) >> 1; + this.timer_divider_shift = divide_shift === 0b111 ? 0 : divide_shift + 1; + break; + + case 0x380: + dbg_log("timer initial: " + h(value >>> 0, 8), LOG_APIC); + this.timer_initial_count = value >>> 0; + this.timer_current_count = value >>> 0; + + this.next_tick = v86.microtick(); + this.timer_active = true; + break; + + case 0x390: + dbg_log("timer current: " + h(value >>> 0, 8), LOG_APIC); + dbg_assert(false, "read-only register"); + break; + + default: + dbg_log("APIC write32 " + h(addr) + " <- " + h(value >>> 0, 8), LOG_APIC); + dbg_assert(false); + } +}; + +APIC.prototype.timer = function(now) +{ + if(this.timer_current_count === 0) + { + return 100; + } + + const freq = APIC_TIMER_FREQ / (1 << this.timer_divider_shift); + + const steps = (now - this.next_tick) * freq >>> 0; + + this.next_tick += steps / freq; + this.timer_current_count -= steps; + + if(this.timer_current_count <= 0) + { + var mode = this.lvt_timer & APIC_TIMER_MODE_MASK; + + if(mode === APIC_TIMER_MODE_PERIODIC) + { + this.timer_current_count = this.timer_current_count % this.timer_initial_count; + + if(this.timer_current_count <= 0) + { + this.timer_current_count += this.timer_initial_count; + } + dbg_assert(this.timer_current_count !== 0); + + if((this.lvt_timer & IOAPIC_CONFIG_MASKED) === 0) + { + this.deliver(this.lvt_timer & 0xFF, IOAPIC_DELIVERY_FIXED, false); + } + } + else if(mode === APIC_TIMER_MODE_ONE_SHOT) + { + this.timer_current_count = 0; + dbg_log("APIC timer one shot end", LOG_APIC); + + if((this.lvt_timer & IOAPIC_CONFIG_MASKED) === 0) + { + this.deliver(this.lvt_timer & 0xFF, IOAPIC_DELIVERY_FIXED, false); + } + } + } + + return Math.max(0, this.timer_current_count / freq); +}; + +APIC.prototype.route = function(vector, mode, is_level, destination, destination_mode) +{ + // TODO + this.deliver(vector, mode, is_level); +}; + +APIC.prototype.deliver = function(vector, mode, is_level) +{ + APIC_LOG_VERBOSE && dbg_log("Deliver " + h(vector, 2) + " mode=" + mode + " level=" + is_level, LOG_APIC); + + if(mode === IOAPIC_DELIVERY_INIT) + { + // TODO + return; + } + + if(mode === IOAPIC_DELIVERY_NMI) + { + // TODO + return; + } + + if(vector < 0x10 || vector === 0xFF) + { + dbg_assert(false, "TODO: Invalid vector"); + } + + if(this.register_get_bit(this.irr, vector)) + { + dbg_log("Not delivered: irr already set, vector=" + h(vector, 2), LOG_APIC); + return; + } + + this.register_set_bit(this.irr, vector); + + if(is_level) + { + this.register_set_bit(this.tmr, vector); + } + else + { + this.register_clear_bit(this.tmr, vector); + } + + this.check_vector(); +}; + +APIC.prototype.highest_irr = function() +{ + var highest = this.register_get_highest_bit(this.irr); + dbg_assert(highest !== 0xFF); + dbg_assert(highest >= 0x10 || highest === -1); + return highest; +}; + +APIC.prototype.highest_isr = function() +{ + var highest = this.register_get_highest_bit(this.isr); + dbg_assert(highest !== 0xFF); + dbg_assert(highest >= 0x10 || highest === -1); + return highest; +}; + +APIC.prototype.check_vector = function() +{ + var highest_irr = this.highest_irr(); + + if(highest_irr === -1) + { + return; + } + + var highest_isr = this.highest_isr(); + + if(highest_isr >= highest_irr) + { + APIC_LOG_VERBOSE && dbg_log("Higher isr, isr=" + h(highest_isr) + " irr=" + h(highest_irr), LOG_APIC); + return; + } + + if((highest_irr & 0xF0) <= (this.tpr & 0xF0)) + { + APIC_LOG_VERBOSE && dbg_log("Higher tpr, tpr=" + h(this.tpr & 0xF0) + " irr=" + h(highest_irr), LOG_APIC); + return; + } + + this.cpu.handle_irqs(); +}; + +APIC.prototype.acknowledge_irq = function() +{ + var highest_irr = this.highest_irr(); + + if(highest_irr === -1) + { + //dbg_log("Spurious", LOG_APIC); + return; + } + + var highest_isr = this.highest_isr(); + + if(highest_isr >= highest_irr) + { + APIC_LOG_VERBOSE && dbg_log("Higher isr, isr=" + h(highest_isr) + " irr=" + h(highest_irr), LOG_APIC); + return; + } + + if((highest_irr & 0xF0) <= (this.tpr & 0xF0)) + { + APIC_LOG_VERBOSE && dbg_log("Higher tpr, tpr=" + h(this.tpr & 0xF0) + " irr=" + h(highest_irr), LOG_APIC); + return; + } + + this.register_clear_bit(this.irr, highest_irr); + this.register_set_bit(this.isr, highest_irr); + + APIC_LOG_VERBOSE && dbg_log("Calling vector " + h(highest_irr), LOG_APIC); + this.cpu.pic_call_irq(highest_irr); + + this.check_vector(); +}; + +APIC.prototype.get_state = function() +{ + var state = []; + + state[0] = this.apic_id; + state[1] = this.timer_divider; + state[2] = this.timer_divider_shift; + state[3] = this.timer_initial_count; + state[4] = this.timer_current_count; + state[5] = this.next_tick; + state[6] = this.lvt_timer; + state[7] = this.lvt_perf_counter; + state[8] = this.lvt_int0; + state[9] = this.lvt_int1; + state[10] = this.lvt_error; + state[11] = this.tpr; + state[12] = this.icr0; + state[13] = this.icr1; + state[14] = this.irr; + state[15] = this.isr; + state[16] = this.tmr; + state[17] = this.spurious_vector; + state[18] = this.destination_format; + state[19] = this.local_destination; + state[20] = this.error; + state[21] = this.read_error; + + return state; +}; + +APIC.prototype.set_state = function(state) +{ + this.apic_id = state[0]; + this.timer_divider = state[1]; + this.timer_divider_shift = state[2]; + this.timer_initial_count = state[3]; + this.timer_current_count = state[4]; + this.next_tick = state[5]; + this.lvt_timer = state[6]; + this.lvt_perf_counter = state[7]; + this.lvt_int0 = state[8]; + this.lvt_int1 = state[9]; + this.lvt_error = state[10]; + this.tpr = state[11]; + this.icr0 = state[12]; + this.icr1 = state[13]; + this.irr = state[14]; + this.isr = state[15]; + this.tmr = state[16]; + this.spurious_vector = state[17]; + this.destination_format = state[18]; + this.local_destination = state[19]; + this.error = state[20]; + this.read_error = state[21]; +}; + +// functions operating on 256-bit registers (for irr, isr, tmr) +APIC.prototype.register_get_bit = function(v, bit) +{ + dbg_assert(bit >= 0 && bit < 256); + return v[bit >> 5] >> (bit & 31) & 1; +}; + +APIC.prototype.register_set_bit = function(v, bit) +{ + dbg_assert(bit >= 0 && bit < 256); + v[bit >> 5] |= 1 << (bit & 31); +}; + +APIC.prototype.register_clear_bit = function(v, bit) +{ + dbg_assert(bit >= 0 && bit < 256); + v[bit >> 5] &= ~(1 << (bit & 31)); +}; + +APIC.prototype.register_get_highest_bit = function(v) +{ + for(var i = 7; i >= 0; i--) + { + var word = v[i]; + + if(word) + { + return v86util.int_log2(word >>> 0) | i << 5; + } + } + + return -1; +}; diff --git a/src/browser/dummy_screen.js b/src/browser/dummy_screen.js new file mode 100644 index 0000000..5731a4b --- /dev/null +++ b/src/browser/dummy_screen.js @@ -0,0 +1,180 @@ +"use strict"; + +/** + * @constructor + * + * @param {BusConnector} bus + */ +function DummyScreenAdapter(bus) +{ + var + graphic_image_data, + + /** @type {number} */ + cursor_row, + + /** @type {number} */ + cursor_col, + + graphical_mode_width, + graphical_mode_height, + + // are we in graphical mode now? + is_graphical = false, + + // Index 0: ASCII code + // Index 1: Background color + // Index 2: Foreground color + text_mode_data, + + // number of columns + text_mode_width, + + // number of rows + text_mode_height; + + this.bus = bus; + + bus.register("screen-set-mode", function(data) + { + this.set_mode(data); + }, this); + + bus.register("screen-fill-buffer-end", function(data) + { + var min = data[0]; + var max = data[1]; + + this.update_buffer(min, max); + }, this); + + bus.register("screen-put-char", function(data) + { + //console.log(data); + this.put_char(data[0], data[1], data[2], data[3], data[4]); + }, this); + + bus.register("screen-text-scroll", function(rows) + { + console.log("scroll", rows); + }, this); + + bus.register("screen-update-cursor", function(data) + { + this.update_cursor(data[0], data[1]); + }, this); + bus.register("screen-update-cursor-scanline", function(data) + { + this.update_cursor_scanline(data[0], data[1]); + }, this); + + bus.register("screen-set-size-text", function(data) + { + this.set_size_text(data[0], data[1]); + }, this); + bus.register("screen-set-size-graphical", function(data) + { + this.set_size_graphical(data[0], data[1]); + }, this); + + this.put_char = function(row, col, chr, bg_color, fg_color) + { + if(row < text_mode_height && col < text_mode_width) + { + var p = 3 * (row * text_mode_width + col); + + text_mode_data[p] = chr; + text_mode_data[p + 1] = bg_color; + text_mode_data[p + 2] = fg_color; + } + }; + + this.destroy = function() + { + }; + + this.set_mode = function(graphical) + { + is_graphical = graphical; + }; + + this.clear_screen = function() + { + }; + + /** + * @param {number} cols + * @param {number} rows + */ + this.set_size_text = function(cols, rows) + { + if(cols === text_mode_width && rows === text_mode_height) + { + return; + } + + text_mode_data = new Int32Array(cols * rows * 3); + + text_mode_width = cols; + text_mode_height = rows; + }; + + this.set_size_graphical = function(width, height) + { + graphical_mode_width = width; + graphical_mode_height = height; + }; + + this.set_scale = function(s_x, s_y) + { + }; + + this.update_cursor_scanline = function(start, end) + { + }; + + this.update_cursor = function(row, col) + { + if(row !== cursor_row || col !== cursor_col) + { + cursor_row = row; + cursor_col = col; + } + }; + + this.update_buffer = function(min, max) + { + if(max < min) + { + return; + } + + var min_y = min / graphical_mode_width | 0; + var max_y = max / graphical_mode_width | 0; + }; + + this.get_text_screen = function() + { + var screen = []; + + for(var i = 0; i < text_mode_height; i++) + { + screen.push(this.get_text_row(i)); + } + + return screen; + }; + + this.get_text_row = function(i) + { + var row = ""; + var offset = 3 * i * text_mode_width; + + for(var j = 0; j < text_mode_width; j++) + { + row += String.fromCharCode(text_mode_data[offset + 3 * j]); + } + + return row; + }; +} diff --git a/src/browser/filestorage.js b/src/browser/filestorage.js new file mode 100644 index 0000000..2a5c526 --- /dev/null +++ b/src/browser/filestorage.js @@ -0,0 +1,161 @@ +"use strict"; + +/** @interface */ +function FileStorageInterface() {} + +/** + * Read a portion of a file. + * @param {string} sha256sum + * @param {number} offset + * @param {number} count + * @return {!Promise} null if file does not exist. + */ +FileStorageInterface.prototype.read = function(sha256sum, offset, count) {}; + +/** + * Add a read-only file to the filestorage. + * @param {string} sha256sum + * @param {!Uint8Array} data + * @return {!Promise} + */ +FileStorageInterface.prototype.cache = function(sha256sum, data) {}; + +/** + * Call this when the file won't be used soon, e.g. when a file closes or when this immutable + * version is already out of date. It is used to help prevent accumulation of unused files in + * memory in the long run for some FileStorage mediums. + */ +FileStorageInterface.prototype.uncache = function(sha256sum) {}; + +/** + * @constructor + * @implements {FileStorageInterface} + */ +function MemoryFileStorage() +{ + /** + * From sha256sum to file data. + * @type {Map} + */ + this.filedata = new Map(); +} + +/** + * @param {string} sha256sum + * @param {number} offset + * @param {number} count + * @return {!Promise} null if file does not exist. + */ +MemoryFileStorage.prototype.read = async function(sha256sum, offset, count) +{ + dbg_assert(sha256sum, "MemoryFileStorage read: sha256sum should be a non-empty string"); + const data = this.filedata.get(sha256sum); + + if(!data) + { + return null; + } + + return data.subarray(offset, offset + count); +}; + +/** + * @param {string} sha256sum + * @param {!Uint8Array} data + */ +MemoryFileStorage.prototype.cache = async function(sha256sum, data) +{ + dbg_assert(sha256sum, "MemoryFileStorage cache: sha256sum should be a non-empty string"); + this.filedata.set(sha256sum, data); +}; + +/** + * @param {string} sha256sum + */ +MemoryFileStorage.prototype.uncache = function(sha256sum) +{ + this.filedata.delete(sha256sum); +}; + +/** + * @constructor + * @implements {FileStorageInterface} + * @param {FileStorageInterface} file_storage + * @param {string} baseurl + */ +function ServerFileStorageWrapper(file_storage, baseurl) +{ + dbg_assert(baseurl, "ServerMemoryFileStorage: baseurl should not be empty"); + + this.storage = file_storage; + this.baseurl = baseurl; +} + +/** + * @param {string} sha256sum + * @return {!Promise} + */ +ServerFileStorageWrapper.prototype.load_from_server = function(sha256sum) +{ + return new Promise((resolve, reject) => + { + v86util.load_file(this.baseurl + sha256sum, { done: async buffer => + { + const data = new Uint8Array(buffer); + await this.cache(sha256sum, data); + resolve(data); + }}); + }); +}; + +/** + * @param {string} sha256sum + * @param {number} offset + * @param {number} count + * @return {!Promise} + */ +ServerFileStorageWrapper.prototype.read = async function(sha256sum, offset, count) +{ + const data = await this.storage.read(sha256sum, offset, count); + if(!data) + { + const full_file = await this.load_from_server(sha256sum); + return full_file.subarray(offset, offset + count); + } + return data; +}; + +/** + * @param {string} sha256sum + * @param {!Uint8Array} data + */ +ServerFileStorageWrapper.prototype.cache = async function(sha256sum, data) +{ + return await this.storage.cache(sha256sum, data); +}; + +/** + * @param {string} sha256sum + */ +ServerFileStorageWrapper.prototype.uncache = function(sha256sum) +{ + this.storage.uncache(sha256sum); +}; + +// Closure Compiler's way of exporting +if(typeof window !== "undefined") +{ + window["MemoryFileStorage"] = MemoryFileStorage; + window["ServerFileStorageWrapper"] = ServerFileStorageWrapper; +} +else if(typeof module !== "undefined" && typeof module.exports !== "undefined") +{ + module.exports["MemoryFileStorage"] = MemoryFileStorage; + module.exports["ServerFileStorageWrapper"] = ServerFileStorageWrapper; +} +else if(typeof importScripts === "function") +{ + // web worker + self["MemoryFileStorage"] = MemoryFileStorage; + self["ServerFileStorageWrapper"] = ServerFileStorageWrapper; +} diff --git a/src/browser/keyboard.js b/src/browser/keyboard.js new file mode 100644 index 0000000..97a1ff5 --- /dev/null +++ b/src/browser/keyboard.js @@ -0,0 +1,445 @@ +"use strict"; + +/** @const */ +var SHIFT_SCAN_CODE = 0x2A; + +/** @const */ +var SCAN_CODE_RELEASE = 0x80; + +/** + * @constructor + * + * @param {BusConnector} bus + */ +function KeyboardAdapter(bus) +{ + var + /** + * @type {!Object.} + */ + keys_pressed = {}, + + keyboard = this; + + /** + * Set by emulator + * @type {boolean} + */ + this.emu_enabled = true; + + /** + * Format: + * Javascript event.keyCode -> make code + * @const + */ + var charmap = new Uint16Array([ + 0, 0, 0, 0, 0, 0, 0, 0, + // 0x08: backspace, tab, enter + 0x0E, 0x0F, 0, 0, 0, 0x1C, 0, 0, + + // 0x10: shift, ctrl, alt, pause, caps lock + 0x2A, 0x1D, 0x38, 0, 0x3A, 0, 0, 0, + + // 0x18: escape + 0, 0, 0, 0x01, 0, 0, 0, 0, + + // 0x20: spacebar, page down/up, end, home, arrow keys, ins, del + 0x39, 0xE049, 0xE051, 0xE04F, 0xE047, 0xE04B, 0xE048, 0xE04D, + 0x50, 0, 0, 0, 0, 0x52, 0x53, 0, + + // 0x30: numbers + 0x0B, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0A, + + // 0x3B: ;= (firefox only) + 0, 0x27, 0, 0x0D, 0, 0, + + // 0x40 + 0, + + // 0x41: letters + 0x1E, 0x30, 0x2E, 0x20, 0x12, 0x21, 0x22, 0x23, 0x17, 0x24, 0x25, 0x26, 0x32, + 0x31, 0x18, 0x19, 0x10, 0x13, 0x1F, 0x14, 0x16, 0x2F, 0x11, 0x2D, 0x15, 0x2C, + + // 0x5B: Left Win, Right Win, Menu + 0xE05B, 0xE05C, 0xE05D, 0, 0, + + // 0x60: keypad + 0x52, 0x4F, 0x50, 0x51, 0x4B, 0x4C, 0x4D, 0x47, + 0x48, 0x49, 0, 0, 0, 0, 0, 0, + + // 0x70: F1 to F12 + 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x57, 0x58, + + 0, 0, 0, 0, + + // 0x80 + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + + // 0x90: Numlock + 0x45, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + + // 0xA0: - (firefox only) + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0x0C, 0, 0, + + // 0xB0 + // , + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0x27, 0x0D, 0x33, 0x0C, 0x34, 0x35, + + // 0xC0 + // ` + 0x29, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + + // 0xD0 + // [']\ + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0x1A, 0x2B, 0x1B, 0x28, 0, + + // 0xE0 + // Apple key on Gecko, Right alt + 0xE05B, 0xE038, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + ]); + + + /** + * ascii -> javascript event code (US layout) + * @const + */ + var asciimap = {8: 8, 10: 13, 32: 32, 39: 222, 44: 188, 45: 189, 46: 190, 47: 191, 48: 48, 49: 49, 50: 50, 51: 51, 52: 52, 53: 53, 54: 54, 55: 55, 56: 56, 57: 57, 59: 186, 61: 187, 91: 219, 92: 220, 93: 221, 96: 192, 97: 65, 98: 66, 99: 67, 100: 68, 101: 69, 102: 70, 103: 71, 104: 72, 105: 73, 106: 74, 107: 75, 108: 76, 109: 77, 110: 78, 111: 79, 112: 80, 113: 81, 114: 82, 115: 83, 116: 84, 117: 85, 118: 86, 119: 87, 120: 88, 121: 89, 122: 90}; + var asciimap_shift = {33: 49, 34: 222, 35: 51, 36: 52, 37: 53, 38: 55, 40: 57, 41: 48, 42: 56, 43: 187, 58: 186, 60: 188, 62: 190, 63: 191, 64: 50, 65: 65, 66: 66, 67: 67, 68: 68, 69: 69, 70: 70, 71: 71, 72: 72, 73: 73, 74: 74, 75: 75, 76: 76, 77: 77, 78: 78, 79: 79, 80: 80, 81: 81, 82: 82, 83: 83, 84: 84, 85: 85, 86: 86, 87: 87, 88: 88, 89: 89, 90: 90, 94: 54, 95: 189, 123: 219, 124: 220, 125: 221, 126: 192}; + + // From: + // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code#Code_values_on_Linux_%28X11%29_%28When_scancode_is_available%29 + // http://stanislavs.org/helppc/make_codes.html + // http://www.computer-engineering.org/ps2keyboard/scancodes1.html + // + // Mapping from event.code to scancode + var codemap = { + "Escape": 0x0001, + "Digit1": 0x0002, + "Digit2": 0x0003, + "Digit3": 0x0004, + "Digit4": 0x0005, + "Digit5": 0x0006, + "Digit6": 0x0007, + "Digit7": 0x0008, + "Digit8": 0x0009, + "Digit9": 0x000a, + "Digit0": 0x000b, + "Minus": 0x000c, + "Equal": 0x000d, + "Backspace": 0x000e, + "Tab": 0x000f, + "KeyQ": 0x0010, + "KeyW": 0x0011, + "KeyE": 0x0012, + "KeyR": 0x0013, + "KeyT": 0x0014, + "KeyY": 0x0015, + "KeyU": 0x0016, + "KeyI": 0x0017, + "KeyO": 0x0018, + "KeyP": 0x0019, + "BracketLeft": 0x001a, + "BracketRight": 0x001b, + "Enter": 0x001c, + "ControlLeft": 0x001d, + "KeyA": 0x001e, + "KeyS": 0x001f, + "KeyD": 0x0020, + "KeyF": 0x0021, + "KeyG": 0x0022, + "KeyH": 0x0023, + "KeyJ": 0x0024, + "KeyK": 0x0025, + "KeyL": 0x0026, + "Semicolon": 0x0027, + "Quote": 0x0028, + "Backquote": 0x0029, + "ShiftLeft": 0x002a, + "Backslash": 0x002b, + "KeyZ": 0x002c, + "KeyX": 0x002d, + "KeyC": 0x002e, + "KeyV": 0x002f, + "KeyB": 0x0030, + "KeyN": 0x0031, + "KeyM": 0x0032, + "Comma": 0x0033, + "Period": 0x0034, + "Slash": 0x0035, + "ShiftRight": 0x0036, + "NumpadMultiply": 0x0037, + "AltLeft": 0x0038, + "Space": 0x0039, + "CapsLock": 0x003a, + "F1": 0x003b, + "F2": 0x003c, + "F3": 0x003d, + "F4": 0x003e, + "F5": 0x003f, + "F6": 0x0040, + "F7": 0x0041, + "F8": 0x0042, + "F9": 0x0043, + "F10": 0x0044, + "NumLock": 0x0045, + "ScrollLock": 0x0046, + "Numpad7": 0x0047, + "Numpad8": 0x0048, + "Numpad9": 0x0049, + "NumpadSubtract": 0x004a, + "Numpad4": 0x004b, + "Numpad5": 0x004c, + "Numpad6": 0x004d, + "NumpadAdd": 0x004e, + "Numpad1": 0x004f, + "Numpad2": 0x0050, + "Numpad3": 0x0051, + "Numpad0": 0x0052, + "NumpadDecimal": 0x0053, + "IntlBackslash": 0x0056, + "F11": 0x0057, + "F12": 0x0058, + + "NumpadEnter": 0xe01c, + "ControlRight": 0xe01d, + "NumpadDivide": 0xe035, + //"PrintScreen": 0x0063, + "AltRight": 0xe038, + "Home": 0xe047, + "ArrowUp": 0xe048, + "PageUp": 0xe049, + "ArrowLeft": 0xe04b, + "ArrowRight": 0xe04d, + "End": 0xe04f, + "ArrowDown": 0xe050, + "PageDown": 0xe051, + "Insert": 0xe052, + "Delete": 0xe053, + + "OSLeft": 0xe05b, + "OSRight": 0xe05c, + "ContextMenu": 0xe05d, + }; + + this.bus = bus; + + this.destroy = function() + { + if(typeof window !== "undefined") + { + window.removeEventListener("keyup", keyup_handler, false); + window.removeEventListener("keydown", keydown_handler, false); + window.removeEventListener("blur", blur_handler, false); + } + }; + + this.init = function() + { + if(typeof window === "undefined") + { + return; + } + this.destroy(); + + window.addEventListener("keyup", keyup_handler, false); + window.addEventListener("keydown", keydown_handler, false); + window.addEventListener("blur", blur_handler, false); + }; + this.init(); + + this.simulate_press = function(code) + { + var ev = { keyCode: code }; + handler(ev, true); + handler(ev, false); + }; + + this.simulate_char = function(chr) + { + var code = chr.charCodeAt(0); + + if(code in asciimap) + { + this.simulate_press(asciimap[code]); + } + else if(code in asciimap_shift) + { + send_to_controller(SHIFT_SCAN_CODE); + this.simulate_press(asciimap_shift[code]); + send_to_controller(SHIFT_SCAN_CODE | SCAN_CODE_RELEASE); + } + else + { + console.log("ascii -> keyCode not found: ", code, chr); + } + }; + + function may_handle(e) + { + if(e.shiftKey && e.ctrlKey && (e.keyCode === 73 || e.keyCode === 74 || e.keyCode === 75)) + { + // don't prevent opening chromium dev tools + // maybe add other important combinations here, too + return false; + } + + if(!keyboard.emu_enabled) + { + return false; + } + + if(e.target) + { + // className shouldn't be hardcoded here + return e.target.classList.contains("phone_keyboard") || + (e.target.nodeName !== "INPUT" && e.target.nodeName !== "TEXTAREA"); + } + else + { + return true; + } + } + + function translate(e) + { + if(e.code !== undefined) + { + var code = codemap[e.code]; + + if(code !== undefined) + { + return code; + } + } + + return charmap[e.keyCode]; + } + + function keyup_handler(e) + { + if(!e.altKey && keys_pressed[0x38]) + { + // trigger ALT keyup manually - some browsers don't + // see issue #165 + handle_code(0x38, false); + } + return handler(e, false); + } + + function keydown_handler(e) + { + if(!e.altKey && keys_pressed[0x38]) + { + // trigger ALT keyup manually - some browsers don't + // see issue #165 + handle_code(0x38, false); + } + return handler(e, true); + } + + function blur_handler(e) + { + // trigger keyup for all pressed keys + var keys = Object.keys(keys_pressed), + key; + + for(var i = 0; i < keys.length; i++) + { + key = +keys[i]; + + if(keys_pressed[key]) + { + handle_code(key, false); + } + } + + keys_pressed = {}; + } + + /** + * @param {boolean} keydown + */ + function handler(e, keydown) + { + if(!keyboard.bus) + { + return; + } + + if(!may_handle(e)) + { + return; + } + + var code = translate(e); + + if(!code) + { + console.log("Missing char in map: keyCode=" + (e.keyCode || -1).toString(16) + " code=" + e.code); + return; + } + + handle_code(code, keydown, e.repeat); + + e.preventDefault && e.preventDefault(); + + return false; + } + + /** + * @param {number} code + * @param {boolean} keydown + * @param {boolean=} is_repeat + */ + function handle_code(code, keydown, is_repeat) + { + if(keydown) + { + if(keys_pressed[code] && !is_repeat) + { + handle_code(code, false); + } + } + else + { + if(!keys_pressed[code]) + { + // stray keyup + return; + } + } + + keys_pressed[code] = keydown; + + if(!keydown) + { + code |= 0x80; + } + //console.log("Key: " + code.toString(16) + " from " + chr.toString(16) + " down=" + keydown); + + if(code > 0xFF) + { + // prefix + send_to_controller(code >> 8); + send_to_controller(code & 0xFF); + } + else + { + send_to_controller(code); + } + } + + function send_to_controller(code) + { + keyboard.bus.send("keyboard-code", code); + } +} + diff --git a/src/browser/main.js b/src/browser/main.js new file mode 100644 index 0000000..075a6a6 --- /dev/null +++ b/src/browser/main.js @@ -0,0 +1,2096 @@ +"use strict"; + +(function() +{ + /** @const */ + var ON_LOCALHOST = !location.hostname.endsWith("copy.sh"); + + /** + * @return {Object.} + */ + function get_query_arguments() + { + var query = location.search.substr(1).split("&"); + var parameters = {}; + + for(var i = 0; i < query.length; i++) + { + var param = query[i].split("="); + parameters[param[0]] = decodeURIComponent(param.slice(1).join("=")); + } + + return parameters; + } + + function set_title(text) + { + document.title = text + " - Virtual x86" + (DEBUG ? " - debug" : ""); + const description = document.querySelector("meta[name=description]"); + description && (description.content = "Running " + text); + } + + function format_timestamp(time) + { + if(time < 60) + { + return time + "s"; + } + else if(time < 3600) + { + return (time / 60 | 0) + "m " + v86util.pad0(time % 60, 2) + "s"; + } + else + { + return (time / 3600 | 0) + "h " + + v86util.pad0((time / 60 | 0) % 60, 2) + "m " + + v86util.pad0(time % 60, 2) + "s"; + } + } + + var progress_ticks = 0; + + function show_progress(e) + { + var el = $("loading"); + el.style.display = "block"; + + if(e.file_name.endsWith(".wasm")) + { + const parts = e.file_name.split("/"); + el.textContent = "Fetching " + parts[parts.length - 1] + " ..."; + return; + } + + if(e.file_index === e.file_count - 1 && e.loaded >= e.total - 2048) + { + // last file is (almost) loaded + el.textContent = "Done downloading. Starting now ..."; + return; + } + + var line = "Downloading images "; + + if(typeof e.file_index === "number" && e.file_count) + { + line += "[" + (e.file_index + 1) + "/" + e.file_count + "] "; + } + + if(e.total && typeof e.loaded === "number") + { + var per100 = Math.floor(e.loaded / e.total * 100); + per100 = Math.min(100, Math.max(0, per100)); + + var per50 = Math.floor(per100 / 2); + + line += per100 + "% ["; + line += "#".repeat(per50); + line += " ".repeat(50 - per50) + "]"; + } + else + { + line += ".".repeat(progress_ticks++ % 50); + } + + el.textContent = line; + } + + function $(id) + { + return document.getElementById(id); + } + + function onload() + { + if(!window.WebAssembly) + { + alert("Your browser is not supported because it doesn't support WebAssembly"); + return; + } + + const script = document.createElement("script"); + script.src = "build/xterm.js"; + script.async = true; + document.body.appendChild(script); + + var settings = {}; + + $("start_emulation").onclick = function() + { + $("boot_options").style.display = "none"; + set_profile("custom"); + + var images = []; + var last_file; + + var floppy_file = $("floppy_image").files[0]; + if(floppy_file) + { + last_file = floppy_file; + settings.fda = { buffer: floppy_file }; + } + + var cd_file = $("cd_image").files[0]; + if(cd_file) + { + last_file = cd_file; + settings.cdrom = { buffer: cd_file }; + } + + var hda_file = $("hda_image").files[0]; + if(hda_file) + { + last_file = hda_file; + settings.hda = { buffer: hda_file }; + } + + var hdb_file = $("hdb_image") && $("hdb_image").files[0]; + if(hdb_file) + { + last_file = hdb_file; + settings.hdb = { buffer: hdb_file }; + } + + if($("multiboot_image")) + { + var multiboot_file = $("multiboot_image").files[0]; + if(multiboot_file) + { + last_file = multiboot_file; + settings.multiboot = { buffer: multiboot_file }; + } + } + + if(last_file) + { + set_title(last_file.name); + } + + start_emulation(settings); + }; + + if(DEBUG) + { + debug_onload(settings); + } + + const query_args = get_query_arguments(); + const host = query_args["cdn"] || (ON_LOCALHOST ? "images/" : "//k.copy.sh/"); + + // Abandonware OS images are from https://winworldpc.com/library/operating-systems + var oses = [ + { + id: "archlinux", + name: "Arch Linux", + memory_size: 512 * 1024 * 1024, + vga_memory_size: 8 * 1024 * 1024, + state: { + url: host + "arch_state.bin.zst", + }, + filesystem: { + baseurl: host + "arch/", + }, + }, + { + id: "archlinux-boot", + name: "Arch Linux", + memory_size: 512 * 1024 * 1024, + vga_memory_size: 8 * 1024 * 1024, + filesystem: { + baseurl: host + "arch/", + basefs: { url: host + "fs.json", }, + }, + cmdline: [ + "rw apm=off vga=0x344 video=vesafb:ypan,vremap:8", + "root=host9p rootfstype=9p rootflags=trans=virtio,cache=loose", + "mitigations=off audit=0", + "init_on_free=on", + "tsc=reliable", + "random.trust_cpu=on", + "nowatchdog", + "init=/usr/bin/init-openrc net.ifnames=0 biosdevname=0", + ].join(" "), + bzimage_initrd_from_filesystem: true, + }, + { + id: "copy/skiffos", + name: "SkiffOS", + cdrom: { + url: host + "skiffos.iso", + size: 124672000, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + memory_size: 512 * 1024 * 1024, + }, + { + id: "serenity", + name: "SerenityOS", + hda: { + url: host + "serenity-v2.img", + size: 700448768, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + memory_size: 512 * 1024 * 1024, + state: { url: host + "serenity_state-v3.bin.zst", }, + homepage: "https://serenityos.org/", + mac_address_translation: true, + }, + { + id: "serenity-boot", + name: "SerenityOS", + hda: { + url: host + "serenity-v2.img", + size: 700448768, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + memory_size: 512 * 1024 * 1024, + homepage: "https://serenityos.org/", + }, + { + id: "serenity-old", + name: "SerenityOS", + hda: { + url: host + "serenity.img", + size: 876 * 1024 * 1024, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + memory_size: 512 * 1024 * 1024, + state: { url: host + "serenity_state-v2.bin.zst", }, + homepage: "https://serenityos.org/", + }, + { + id: "serenity-old-boot", + name: "SerenityOS", + hda: { + url: host + "serenity.img", + size: 876 * 1024 * 1024, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + memory_size: 512 * 1024 * 1024, + homepage: "https://serenityos.org/", + }, + { + id: "redox", + name: "Redox", + hda: { + url: host + "redox_demo_i686_2022-11-26_643_harddrive.img", + size: 512 * 1024 * 1024, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + memory_size: 512 * 1024 * 1024, + state: { url: host + "redox_state.bin.zst" }, + homepage: "https://www.redox-os.org/", + acpi: true, + }, + { + id: "redox-boot", + name: "Redox", + hda: { + url: host + "redox_demo_i686_2022-11-26_643_harddrive.img", + size: 512 * 1024 * 1024, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + memory_size: 512 * 1024 * 1024, + homepage: "https://www.redox-os.org/", + acpi: true, + }, + { + id: "helenos", + memory_size: 256 * 1024 * 1024, + cdrom: { + url: host + "HelenOS-0.11.2-ia32.iso", + size: 25765888, + async: false, + }, + name: "HelenOS", + homepage: "http://www.helenos.org/", + }, + { + id: "fiwix", + memory_size: 256 * 1024 * 1024, + hda: { + url: host + "fiwixos-3.2-i386.img", + size: 1024 * 1024 * 1024, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "FiwixOS", + homepage: "https://www.fiwix.org/", + }, + { + id: "haiku", + memory_size: 512 * 1024 * 1024, + hda: { + url: host + "haiku-v2.img", + size: 1 * 1024 * 1024 * 1024, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + state: { + url: host + "haiku_state-v2.bin.zst", + }, + name: "Haiku", + homepage: "https://www.haiku-os.org/", + }, + { + id: "haiku-boot", + memory_size: 512 * 1024 * 1024, + hda: { + url: host + "haiku-v2.img", + size: 1 * 1024 * 1024 * 1024, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Haiku", + homepage: "https://www.haiku-os.org/", + }, + { + id: "msdos", + hda: { + url: host + "msdos.img", + size: 8 * 1024 * 1024, + async: false, + }, + boot_order: 0x132, + name: "MS-DOS", + }, + { + id: "freedos", + fda: { + url: host + "freedos722.img", + size: 737280, + async: false, + }, + name: "FreeDOS", + }, + { + id: "psychdos", + hda: { + url: host + "psychdos.img", + size: 549453824, + async: true, + fixed_chunk_size: 256 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "PsychDOS", + homepage: "https://psychoslinux.gitlab.io/DOS/INDEX.HTM", + }, + { + id: "oberon", + hda: { + url: host + "oberon.img", + size: 24 * 1024 * 1024, + async: false, + }, + name: "Oberon", + }, + { + id: "windows1", + fda: { + url: host + "windows101.img", + size: 1474560, + async: false, + }, + name: "Windows", + }, + { + id: "linux26", + cdrom: { + url: host + "linux.iso", + size: 6547456, + async: false, + }, + name: "Linux", + }, + { + id: "linux3", + cdrom: { + url: host + "linux3.iso", + size: 8624128, + async: false, + }, + name: "Linux", + }, + { + id: "linux4", + cdrom: { + url: host + "linux4.iso", + size: 7731200, + async: false, + }, + name: "Linux", + filesystem: {}, + }, + { + id: "buildroot", + bzimage: { + url: host + "buildroot-bzimage.bin", + size: 5166352, + async: false, + }, + name: "Buildroot Linux", + filesystem: {}, + cmdline: "tsc=reliable mitigations=off random.trust_cpu=on", + }, + { + id: "nodeos", + bzimage: { + url: host + "nodeos-kernel.bin", + size: 14452000, + async: false, + }, + name: "NodeOS", + cmdline: "tsc=reliable mitigations=off random.trust_cpu=on", + }, + { + id: "dsl", + memory_size: 256 * 1024 * 1024, + cdrom: { + url: host + "dsl-4.11.rc2.iso", + size: 52824064, + async: false, + }, + name: "Damn Small Linux", + homepage: "http://www.damnsmalllinux.org/", + }, + { + id: "minix", + name: "Minix", + memory_size: 256 * 1024 * 1024, + cdrom: { + url: host + "minix-3.3.0.iso", + size: 605581312, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + homepage: "https://www.minix3.org/", + }, + { + id: "kolibrios", + fda: { + url: ON_LOCALHOST ? + host + "kolibri.img" : + "//builds.kolibrios.org/eng/data/data/kolibri.img", + size: 1474560, + async: false, + }, + name: "KolibriOS", + homepage: "https://kolibrios.org/en/", + }, + { + id: "kolibrios-fallback", + fda: { + url: host + "kolibri.img", + size: 1474560, + async: false, + }, + name: "KolibriOS", + }, + { + id: "openbsd", + hda: { + url: host + "openbsd.img", + size: 1073741824, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + state: { + url: host + "openbsd_state.bin.zst", + }, + memory_size: 256 * 1024 * 1024, + name: "OpenBSD", + }, + { + id: "openbsd-boot", + hda: { + url: host + "openbsd.img", + size: 1073741824, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + memory_size: 256 * 1024 * 1024, + name: "OpenBSD", + //acpi: true, // doesn't seem to work + }, + { + id: "netbsd", + hda: { + url: host + "netbsd.img", + size: 511000064, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + memory_size: 256 * 1024 * 1024, + name: "NetBSD", + }, + { + id: "solos", + fda: { + url: host + "os8.img", + async: false, + size: 1474560, + }, + name: "Sol OS", + homepage: "http://oby.ro/os/", + }, + { + id: "bootchess", + fda: { + url: host + "bootchess.img", + async: false, + size: 1474560, + }, + name: "BootChess", + homepage: "http://www.pouet.net/prod.php?which=64962", + }, + { + id: "bootbasic", + fda: { + url: host + "bootbasic.img", + async: false, + size: 1474560, + }, + name: "bootBASIC", + homepage: "https://github.com/nanochess/bootBASIC", + }, + { + id: "sectorlisp", + fda: { + url: host + "sectorlisp-friendly.bin", + async: false, + size: 512, + }, + name: "SectorLISP", + homepage: "https://justine.lol/sectorlisp2/", + }, + { + id: "sectorforth", + fda: { + url: host + "sectorforth.img", + async: false, + size: 512, + }, + name: "sectorforth", + homepage: "https://github.com/cesarblum/sectorforth", + }, + { + id: "floppybird", + fda: { + url: host + "floppybird.img", + async: false, + size: 1474560, + }, + name: "Floppy Bird", + homepage: "http://mihail.co/floppybird", + }, + { + id: "windows2000", + memory_size: 512 * 1024 * 1024, + hda: { + url: host + "windows2k.img", + size: 2 * 1024 * 1024 * 1024, + async: true, + fixed_chunk_size: 256 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Windows 2000", + state: { + url: host + "windows2k_state-v2.bin.zst", + }, + mac_address_translation: true, + }, + { + id: "windows2000-boot", + memory_size: 512 * 1024 * 1024, + hda: { + url: host + "windows2k.img", + size: 2 * 1024 * 1024 * 1024, + async: true, + fixed_chunk_size: 256 * 1024, + use_parts: !ON_LOCALHOST, + }, + boot_order: 0x132, + name: "Windows 2000", + }, + { + id: "windowsnt4", + memory_size: 512 * 1024 * 1024, + hda: { + url: host + "winnt4_noacpi.img", + size: 523837440, + async: true, + fixed_chunk_size: 256 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Windows NT 4.0", + cpuid_level: 2, + }, + { + id: "windowsnt3", + memory_size: 256 * 1024 * 1024, + hda: { + url: host + "winnt31.img", + size: 87 * 1024 * 1024, + async: true, + fixed_chunk_size: 256 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Windows NT 3.1", + }, + { + id: "windows98", + memory_size: 128 * 1024 * 1024, + hda: { + url: host + "windows98.img", + size: 300 * 1024 * 1024, + async: true, + fixed_chunk_size: 256 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Windows 98", + state: { + url: host + "windows98_state.bin.zst", + }, + mac_address_translation: true, + }, + { + id: "windows98-boot", + memory_size: 128 * 1024 * 1024, + hda: { + url: host + "windows98.img", + size: 300 * 1024 * 1024, + async: true, + fixed_chunk_size: 256 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Windows 98", + }, + { + id: "windows95", + memory_size: 32 * 1024 * 1024, + hda: { + url: host + "w95.img", + size: 242049024, + async: true, + fixed_chunk_size: 256 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Windows 95", + state: { + url: host + "windows95_state.bin.zst", + }, + }, + { + id: "windows95-boot", + memory_size: 32 * 1024 * 1024, + hda: { + url: host + "w95.img", + size: 242049024, + async: true, + fixed_chunk_size: 256 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Windows 95", + }, + { + id: "windows30", + memory_size: 64 * 1024 * 1024, + cdrom: { + url: host + "Win30.iso", + async: false, + }, + name: "Windows 3.0", + }, + { + id: "windows31", + memory_size: 64 * 1024 * 1024, + hda: { + url: host + "win31.img", + async: false, + size: 34463744, + }, + name: "Windows 3.1", + }, + { + id: "freebsd", + memory_size: 256 * 1024 * 1024, + hda: { + url: host + "freebsd.img", + size: 2147483648, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + state: { + url: host + "freebsd_state.bin.zst", + }, + name: "FreeBSD", + }, + { + id: "freebsd-boot", + memory_size: 256 * 1024 * 1024, + hda: { + url: host + "freebsd.img", + size: 2147483648, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "FreeBSD", + }, + { + id: "reactos-livecd", + memory_size: 256 * 1024 * 1024, + hda: { + url: host + "reactos-livecd-0.4.15-dev-73-g03c09c9-x86-gcc-lin-dbg.iso", + size: 250609664, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "ReactOS", + homepage: "https://reactos.org/", + }, + { + id: "reactos", + memory_size: 512 * 1024 * 1024, + hda: { + url: host + "reactos.img", + size: 500 * 1024 * 1024, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + state: { + url: host + "reactos_state.bin.zst", + }, + mac_address_translation: true, + name: "ReactOS", + homepage: "https://reactos.org/", + }, + { + id: "reactos-boot", + memory_size: 512 * 1024 * 1024, + hda: { + url: host + "reactos.img", + size: 500 * 1024 * 1024, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "ReactOS", + homepage: "https://reactos.org/", + }, + { + id: "skift", + cdrom: { + url: host + "skift-20200910.iso", + size: 64452608, + async: false, + }, + name: "Skift", + homepage: "https://skiftos.org/", + }, + { + id: "snowdrop", + fda: { + url: host + "snowdrop.img", + size: 1440 * 1024, + async: false, + }, + name: "Snowdrop", + homepage: "http://www.sebastianmihai.com/snowdrop/", + }, + { + id: "openwrt", + hda: { + url: host + "openwrt-18.06.1-x86-legacy-combined-squashfs.img", + size: 19846474, + async: false, + }, + name: "OpenWrt", + }, + { + id: "qnx", + fda: { + url: host + "qnx-demo-network-4.05.img", + size: 1474560, + async: false + }, + name: "QNX 4.05", + }, + { + id: "9front", + memory_size: 128 * 1024 * 1024, + hda: { + url: host + "9front-8963.f84cf1e60427675514fb056cc1723e45da01e043.386.iso", + size: 477452288, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + state: { + url: host + "9front_state-v2.bin.zst", + }, + acpi: true, + name: "9front", + homepage: "https://9front.org/", + }, + { + id: "9front-boot", + memory_size: 128 * 1024 * 1024, + hda: { + url: host + "9front-8963.f84cf1e60427675514fb056cc1723e45da01e043.386.iso", + size: 477452288, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + acpi: true, + name: "9front", + homepage: "https://9front.org/", + }, + { + id: "mobius", + fda: { + url: host + "mobius-fd-release5.img", + size: 1474560, + async: false, + }, + name: "Mobius", + }, + { + id: "android", + memory_size: 512 * 1024 * 1024, + cdrom: { + url: host + "android-x86-1.6-r2.iso", + size: 54661120, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Android", + }, + { + id: "android4", + memory_size: 512 * 1024 * 1024, + cdrom: { + url: host + "android_x86_nonsse3_4.4r1_20140904.iso", + size: 247463936, + async: true, + fixed_chunk_size: 1024 * 1024, + use_parts: !ON_LOCALHOST, + }, + name: "Android", + }, + { + id: "tinycore", + memory_size: 256 * 1024 * 1024, + hda: { + url: host + "TinyCore-11.0.iso", + async: false, + }, + name: "Tinycore", + homepage: "http://www.tinycorelinux.net/", + }, + { + id: "freenos", + memory_size: 256 * 1024 * 1024, + cdrom: { + url: host + "FreeNOS-1.0.3.iso", + async: false, + size: 11014144, + }, + name: "FreeNOS", + acpi: true, + homepage: "http://www.freenos.org/", + }, + ]; + + if(DEBUG) + { + // see tests/kvm-unit-tests/x86/ + var tests = [ + "realmode", + // All tests below require an APIC + "cmpxchg8b", + "port80", + "setjmp", + "sieve", + "hypercall", // crashes + "init", // stops execution + "msr", // TODO: Expects 64 bit msrs + "smap", // test stops, SMAP not enabled + "tsc_adjust", // TODO: IA32_TSC_ADJUST + "tsc", // TODO: rdtscp + "rmap_chain", // crashes + "memory", // missing mfence (uninteresting) + "taskswitch", // TODO: Jump + "taskswitch2", // TODO: Call TSS + "eventinj", // Missing #nt + "ioapic", + "apic", + ]; + + for(let test of tests) + { + oses.push({ + name: "Test case: " + test, + id: "test-" + test, + memory_size: 128 * 1024 * 1024, + multiboot: { url: "tests/kvm-unit-tests/x86/" + test + ".flat", } + }); + } + } + + var profile = query_args["profile"]; + + if(!profile && !DEBUG) + { + const link = document.createElement("link"); + link.rel = "prefetch"; + link.href = "build/v86.wasm"; + document.head.appendChild(link); + } + + if(query_args["use_bochs_bios"]) + { + settings.use_bochs_bios = true; + } + + const m = parseInt(query_args["m"], 10); + if(m > 0) + { + settings.memory_size = Math.max(16, m) * 1024 * 1024; + } + + const vram = parseInt(query_args["vram"], 10); + if(vram > 0) + { + settings.vga_memory_size = vram * 1024 * 1024; + } + + settings.networking_proxy = query_args["networking_proxy"]; + settings.audio = query_args["audio"] !== "0"; + settings.acpi = query_args["acpi"]; + + for(var i = 0; i < oses.length; i++) + { + var infos = oses[i]; + + if(profile === infos.id) + { + start_profile(infos); + return; + } + + var element = $("start_" + infos.id); + + if(element) + { + element.onclick = function(infos, element, e) + { + e.preventDefault(); + set_profile(infos.id); + element.blur(); + + start_profile(infos); + }.bind(this, infos, element); + } + } + + if(profile === "custom") + { + if(query_args["hda.url"]) + { + settings.hda = { + size: parseInt(query_args["hda.size"], 10) || undefined, + url: query_args["hda.url"], + async: true, + }; + } + + if(query_args["cdrom.url"]) + { + settings.cdrom = { + size: parseInt(query_args["cdrom.size"], 10) || undefined, + url: query_args["cdrom.url"], + async: true, + }; + } + + if(query_args["fda.url"]) + { + settings.fda = { + size: parseInt(query_args["fda.size"], 10) || undefined, + url: query_args["fda.url"], + async: false, + }; + } + + if(settings.fda || settings.cdrom || settings.hda) + { + $("boot_options").style.display = "none"; + + start_emulation(settings, done); + } + } + else if(/^[a-zA-Z0-9\-_]+\/[a-zA-Z0-9\-_]+$/g.test(profile)) + { + // experimental: server that allows user-uploaded images + + const base = "https://v86-user-images.b-cdn.net/" + profile; + + fetch(base + "/profile.json") + .then(response => response.json()) + .then(p => { + function handle_image(o) + { + return o && { url: base + "/" + o["url"], async: o["async"], size: o["size"] }; + } + + start_profile({ + id: p["id"], + name: p["name"], + memory_size: p["memory_size"], + vga_memory_size: p["vga_memory_size"], + acpi: p["acpi"], + boot_order: p["boot_order"], + hda: handle_image(p["hda"]), + cdrom: handle_image(p["cdrom"]), + fda: handle_image(p["fda"]), + multiboot: handle_image(p["multiboot"]), + bzimage: handle_image(p["bzimage"]), + initrd: handle_image(p["initrd"]), + }); + }) + .catch(e => alert("Profile not found: " + profile)); + } + + function start_profile(infos) + { + $("boot_options").style.display = "none"; + set_title(infos.name); + + settings.filesystem = infos.filesystem; + + if(infos.state) + { + $("reset").style.display = "none"; + settings.initial_state = infos.state; + } + + settings.fda = infos.fda; + settings.cdrom = infos.cdrom; + settings.hda = infos.hda; + settings.multiboot = infos.multiboot; + settings.bzimage = infos.bzimage; + settings.initrd = infos.initrd; + settings.cmdline = infos.cmdline; + settings.bzimage_initrd_from_filesystem = infos.bzimage_initrd_from_filesystem; + settings.mac_address_translation = infos.mac_address_translation; + settings.cpuid_level = infos.cpuid_level; + + settings.acpi = (!infos.state && settings.acpi !== undefined) ? settings.acpi : infos.acpi; + settings.memory_size = (!infos.state && settings.memory_size) ? settings.memory_size : infos.memory_size; + settings.vga_memory_size = (!infos.state && settings.vga_memory_size) ? settings.vga_memory_size : infos.vga_memory_size; + + settings.id = infos.id; + + if(infos.boot_order !== undefined) + { + settings.boot_order = infos.boot_order; + } + + let chunk_size = parseInt(query_args["chunk_size"], 10); + if(chunk_size >= 0) + { + if(chunk_size) + { + chunk_size = Math.min(4 * 1024 * 1024, Math.max(512, chunk_size)); + chunk_size = 1 << Math.ceil(Math.log2(chunk_size)); + } + else + { + chunk_size = undefined; + } + + if(settings.hda) + { + settings.hda.fixed_chunk_size = chunk_size; + } + + if(settings.cdrom) + { + settings.cdrom.fixed_chunk_size = chunk_size; + } + } + + if(!DEBUG && infos.homepage) + { + $("description").style.display = "block"; + const link = document.createElement("a"); + link.href = infos.homepage; + link.textContent = infos.name; + link.target = "_blank"; + $("description").appendChild(document.createTextNode("Running ")); + $("description").appendChild(link); + } + + start_emulation(settings, done); + } + + function done(emulator) + { + if(query_args["c"]) + { + setTimeout(function() + { + //emulator.serial0_send(query_args["c"] + "\n"); + emulator.keyboard_send_text(query_args["c"] + "\n"); + }, 25); + } + } + } + + function debug_onload(settings) + { + // called on window.onload, in debug mode + + var log_levels = $("log_levels"); + + if(log_levels) + { + for(var i = 0; i < LOG_NAMES.length; i++) + { + var mask = LOG_NAMES[i][0]; + + if(mask === 1) + continue; + + var name = LOG_NAMES[i][1].toLowerCase(), + input = document.createElement("input"), + label = document.createElement("label"); + + input.type = "checkbox"; + + label.htmlFor = input.id = "log_" + name; + + if(LOG_LEVEL & mask) + { + input.checked = true; + } + input.mask = mask; + + label.appendChild(input); + label.appendChild(document.createTextNode(v86util.pads(name, 4) + " ")); + log_levels.appendChild(label); + + if(i === Math.floor(LOG_NAMES.length / 2)) + { + log_levels.appendChild(document.createTextNode("\n")); + } + } + + log_levels.onchange = function(e) + { + var target = e.target, + mask = target.mask; + + if(target.checked) + { + LOG_LEVEL |= mask; + } + else + { + LOG_LEVEL &= ~mask; + } + + target.blur(); + }; + } + } + + window.addEventListener("load", onload, false); + + // old webkit fires popstate on every load, fuck webkit + // https://code.google.com/p/chromium/issues/detail?id=63040 + window.addEventListener("load", function() + { + setTimeout(function() + { + window.addEventListener("popstate", onpopstate); + }, 0); + }); + + // works in firefox and chromium + if(document.readyState === "complete") + { + onload(); + } + + /** @param {?=} done */ + function start_emulation(settings, done) + { + /** @const */ + var MB = 1024 * 1024; + + var memory_size = settings.memory_size; + + if(!memory_size) + { + memory_size = parseInt($("memory_size").value, 10) * MB; + + if(!memory_size) + { + alert("Invalid memory size - reset to 128MB"); + memory_size = 128 * MB; + } + } + + var vga_memory_size = settings.vga_memory_size; + + if(!vga_memory_size) + { + vga_memory_size = parseInt($("video_memory_size").value, 10) * MB; + + if(!vga_memory_size) + { + alert("Invalid video memory size - reset to 8MB"); + vga_memory_size = 8 * MB; + } + } + + if(!settings.fda) + { + var floppy_file = $("floppy_image").files[0]; + if(floppy_file) + { + settings.fda = { buffer: floppy_file }; + } + } + + if(!settings.bzimage) + { + var bzimage = $("bzimage").files[0]; + if(bzimage) + { + settings.bzimage = { buffer: bzimage }; + } + } + + if(!settings.initrd) + { + var initrd = $("initrd").files[0]; + if(initrd) + { + settings.initrd = { buffer: initrd }; + } + } + + const networking_proxy = settings.networking_proxy === undefined ? $("networking_proxy").value : settings.networking_proxy; + const disable_audio = settings.audio === undefined ? $("disable_audio").checked : !settings.audio; + const enable_acpi = settings.acpi === undefined ? $("enable_acpi").checked : settings.acpi; + + /** @const */ + var BIOSPATH = "bios/"; + + if(settings.use_bochs_bios) + { + var biosfile = "bochs-bios.bin"; + var vgabiosfile = "bochs-vgabios.bin"; + } + else + { + var biosfile = DEBUG ? "seabios-debug.bin" : "seabios.bin"; + var vgabiosfile = DEBUG ? "vgabios-debug.bin" : "vgabios.bin"; + } + + var bios; + var vga_bios; + + // a bios is only needed if the machine is booted + if(!settings.initial_state) + { + bios = { + url: BIOSPATH + biosfile, + }; + vga_bios = { + url: BIOSPATH + vgabiosfile, + }; + } + + var emulator = new V86Starter({ + "memory_size": memory_size, + "vga_memory_size": vga_memory_size, + + "screen_container": $("screen_container"), + "serial_container_xtermjs": $("terminal"), + + "boot_order": settings.boot_order || parseInt($("boot_order").value, 16) || 0, + + "network_relay_url": ON_LOCALHOST ? "ws://localhost:8080/" : networking_proxy, + + "bios": bios, + "vga_bios": vga_bios, + + "fda": settings.fda, + "hda": settings.hda, + "hdb": settings.hdb, + "cdrom": settings.cdrom, + + "multiboot": settings.multiboot, + "bzimage": settings.bzimage, + "initrd": settings.initrd, + "cmdline": settings.cmdline, + "bzimage_initrd_from_filesystem": settings.bzimage_initrd_from_filesystem, + + "acpi": enable_acpi, + "initial_state": settings.initial_state, + "filesystem": settings.filesystem || {}, + "disable_speaker": disable_audio, + "mac_address_translation": settings.mac_address_translation, + "cpuid_level": settings.cpuid_level, + + "autostart": true, + }); + + if(DEBUG) window["emulator"] = emulator; + + emulator.add_listener("emulator-ready", function() + { + if(DEBUG) + { + debug_start(emulator); + } + + if(emulator.v86.cpu.wm.exports["profiler_is_enabled"]()) + { + const CLEAR_STATS = false; + + var panel = document.createElement("pre"); + document.body.appendChild(panel); + + setInterval(function() + { + if(!emulator.is_running()) + { + return; + } + + const text = print_stats.stats_to_string(emulator.v86.cpu); + panel.textContent = text; + + CLEAR_STATS && emulator.v86.cpu.clear_opstats(); + }, CLEAR_STATS ? 5000 : 1000); + } + + if(settings.id === "dsl" || settings.id === "helenos") + { + setTimeout(() => { + // hack: Start automatically + emulator.keyboard_send_text("\n"); + }, 3000); + } + else if(settings.id === "android" || settings.id === "android4") + { + setTimeout(() => { + // hack: select vesa mode and start automatically + emulator.keyboard_send_scancodes([0xe050, 0xe050 | 0x80]); + emulator.keyboard_send_text("\n"); + }, 3000); + } + + init_ui(settings, emulator); + + done && done(emulator); + }); + + emulator.add_listener("download-progress", function(e) + { + show_progress(e); + }); + + emulator.add_listener("download-error", function(e) + { + var el = $("loading"); + el.style.display = "block"; + el.textContent = "Loading " + e.file_name + " failed. Check your connection " + + "and reload the page to try again."; + }); + } + + /** + * @param {Object} settings + * @param {V86Starter} emulator + */ + function init_ui(settings, emulator) + { + $("boot_options").style.display = "none"; + $("loading").style.display = "none"; + $("runtime_options").style.display = "block"; + $("runtime_infos").style.display = "block"; + $("screen_container").style.display = "block"; + + if(settings.filesystem) + { + init_filesystem_panel(emulator); + } + else + { + emulator.add_listener("9p-attach", function() + { + init_filesystem_panel(emulator); + }); + } + + $("run").onclick = function() + { + if(emulator.is_running()) + { + $("run").value = "Run"; + emulator.stop(); + } + else + { + $("run").value = "Pause"; + emulator.run(); + } + + $("run").blur(); + }; + + $("exit").onclick = function() + { + emulator.stop(); + location.href = location.pathname; + }; + + $("lock_mouse").onclick = function() + { + if(!mouse_is_enabled) + { + $("toggle_mouse").onclick(); + } + + emulator.lock_mouse(); + $("lock_mouse").blur(); + }; + + var mouse_is_enabled = true; + + $("toggle_mouse").onclick = function() + { + mouse_is_enabled = !mouse_is_enabled; + + emulator.mouse_set_status(mouse_is_enabled); + $("toggle_mouse").value = (mouse_is_enabled ? "Dis" : "En") + "able mouse"; + $("toggle_mouse").blur(); + }; + + + var last_tick = 0; + var running_time = 0; + var last_instr_counter = 0; + var interval = null; + var os_uses_mouse = false; + var total_instructions = 0; + + function update_info() + { + var now = Date.now(); + + var instruction_counter = emulator.get_instruction_counter(); + + if(instruction_counter < last_instr_counter) + { + // 32-bit wrap-around + last_instr_counter -= 0x100000000; + } + + var last_ips = instruction_counter - last_instr_counter; + last_instr_counter = instruction_counter; + total_instructions += last_ips; + + var delta_time = now - last_tick; + + if(delta_time) + { + running_time += delta_time; + last_tick = now; + + $("speed").textContent = (last_ips / 1000 / delta_time).toFixed(1); + $("avg_speed").textContent = (total_instructions / 1000 / running_time).toFixed(1); + $("running_time").textContent = format_timestamp(running_time / 1000 | 0); + } + } + + emulator.add_listener("emulator-started", function() + { + last_tick = Date.now(); + interval = setInterval(update_info, 1000); + }); + + emulator.add_listener("emulator-stopped", function() + { + update_info(); + if(interval !== null) + { + clearInterval(interval); + } + }); + + var stats_9p = { + read: 0, + write: 0, + files: [], + }; + + emulator.add_listener("9p-read-start", function(args) + { + const file = args[0]; + stats_9p.files.push(file); + $("info_filesystem").style.display = "block"; + $("info_filesystem_status").textContent = "Loading ..."; + $("info_filesystem_last_file").textContent = file; + }); + emulator.add_listener("9p-read-end", function(args) + { + stats_9p.read += args[1]; + $("info_filesystem_bytes_read").textContent = stats_9p.read; + + const file = args[0]; + stats_9p.files = stats_9p.files.filter(f => f !== file); + + if(stats_9p.files[0]) + { + $("info_filesystem_last_file").textContent = stats_9p.files[0]; + } + else + { + $("info_filesystem_status").textContent = "Idle"; + } + }); + emulator.add_listener("9p-write-end", function(args) + { + stats_9p.write += args[1]; + $("info_filesystem_bytes_written").textContent = stats_9p.write; + + if(!stats_9p.files[0]) + { + $("info_filesystem_last_file").textContent = args[0]; + } + }); + + var stats_storage = { + read: 0, + read_sectors: 0, + write: 0, + write_sectors: 0, + }; + + emulator.add_listener("ide-read-start", function() + { + $("info_storage").style.display = "block"; + $("info_storage_status").textContent = "Loading ..."; + }); + emulator.add_listener("ide-read-end", function(args) + { + stats_storage.read += args[1]; + stats_storage.read_sectors += args[2]; + + $("info_storage_status").textContent = "Idle"; + $("info_storage_bytes_read").textContent = stats_storage.read; + $("info_storage_sectors_read").textContent = stats_storage.read_sectors; + }); + emulator.add_listener("ide-write-end", function(args) + { + stats_storage.write += args[1]; + stats_storage.write_sectors += args[2]; + + $("info_storage_bytes_written").textContent = stats_storage.write; + $("info_storage_sectors_written").textContent = stats_storage.write_sectors; + }); + + var stats_net = { + bytes_transmitted: 0, + bytes_received: 0, + }; + + emulator.add_listener("eth-receive-end", function(args) + { + stats_net.bytes_received += args[0]; + + $("info_network").style.display = "block"; + $("info_network_bytes_received").textContent = stats_net.bytes_received; + }); + emulator.add_listener("eth-transmit-end", function(args) + { + stats_net.bytes_transmitted += args[0]; + + $("info_network").style.display = "block"; + $("info_network_bytes_transmitted").textContent = stats_net.bytes_transmitted; + }); + + + emulator.add_listener("mouse-enable", function(is_enabled) + { + os_uses_mouse = is_enabled; + $("info_mouse_enabled").textContent = is_enabled ? "Yes" : "No"; + }); + + emulator.add_listener("screen-set-mode", function(is_graphical) + { + if(is_graphical) + { + $("info_vga_mode").textContent = "Graphical"; + } + else + { + $("info_vga_mode").textContent = "Text"; + $("info_res").textContent = "-"; + $("info_bpp").textContent = "-"; + } + }); + emulator.add_listener("screen-set-size-graphical", function(args) + { + $("info_res").textContent = args[0] + "x" + args[1]; + $("info_bpp").textContent = args[4]; + }); + + + $("reset").onclick = function() + { + emulator.restart(); + $("reset").blur(); + }; + + add_image_download_button(settings.hda, "hda"); + add_image_download_button(settings.hdb, "hdb"); + add_image_download_button(settings.fda, "fda"); + add_image_download_button(settings.fdb, "fdb"); + add_image_download_button(settings.cdrom, "cdrom"); + + function add_image_download_button(obj, type) + { + var elem = $("get_" + type + "_image"); + + if(!obj || obj.size > 100 * 1024 * 1024) + { + elem.style.display = "none"; + return; + } + + elem.onclick = function(e) + { + let buffer = emulator.disk_images[type]; + let filename = buffer.file && buffer.file.name || (settings.id + (type === "cdrom" ? ".iso" : ".img")); + + if(buffer.get_as_file) + { + var file = buffer.get_as_file(filename); + download(file, filename); + } + else + { + buffer.get_buffer(function(b) + { + if(b) + { + dump_file(b, filename); + } + else + { + alert("The file could not be loaded. Maybe it's too big?"); + } + }); + } + + elem.blur(); + }; + } + + $("memory_dump").onclick = function() + { + const mem8 = emulator.v86.cpu.mem8; + dump_file(new Uint8Array(mem8.buffer, mem8.byteOffset, mem8.length), "v86memory.bin"); + $("memory_dump").blur(); + }; + + //$("memory_dump_dmp").onclick = function() + //{ + // var memory = emulator.v86.cpu.mem8; + // var memory_size = memory.length; + // var page_size = 4096; + // var header = new Uint8Array(4096); + // var header32 = new Int32Array(header.buffer); + + // header32[0] = 0x45474150; // 'PAGE' + // header32[1] = 0x504D5544; // 'DUMP' + + // header32[0x10 >> 2] = emulator.v86.cpu.cr[3]; // DirectoryTableBase + // header32[0x24 >> 2] = 1; // NumberProcessors + // header32[0xf88 >> 2] = 1; // DumpType: full dump + // header32[0xfa0 >> 2] = header.length + memory_size; // RequiredDumpSpace + + // header32[0x064 + 0 >> 2] = 1; // NumberOfRuns + // header32[0x064 + 4 >> 2] = memory_size / page_size; // NumberOfPages + // header32[0x064 + 8 >> 2] = 0; // BasePage + // header32[0x064 + 12 >> 2] = memory_size / page_size; // PageCount + + // dump_file([header, memory], "v86memory.dmp"); + + // $("memory_dump_dmp").blur(); + //}; + + $("capture_network_traffic").onclick = function() + { + this.value = "0 packets"; + + let capture = []; + + function do_capture(direction, data) + { + capture.push({ direction, time: performance.now() / 1000, hex_dump: hex_dump(data) }); + $("capture_network_traffic").value = capture.length + " packets"; + } + + emulator.emulator_bus.register("net0-receive", do_capture.bind(this, "I")); + emulator.add_listener("net0-send", do_capture.bind(this, "O")); + + this.onclick = function() + { + const capture_raw = capture.map(({ direction, time, hex_dump }) => { + // https://www.wireshark.org/docs/wsug_html_chunked/ChIOImportSection.html + // In wireshark: file -> import from hex -> tick direction indication, timestamp %s.%f + return direction + " " + time.toFixed(6) + hex_dump + "\n"; + }).join(""); + dump_file(capture_raw, "traffic.hex"); + capture = []; + this.value = "0 packets"; + }; + }; + + + $("save_state").onclick = async function() + { + const result = await emulator.save_state(); + dump_file(result, "v86state.bin"); + + $("save_state").blur(); + }; + + $("load_state").onclick = function() + { + $("load_state_input").click(); + $("load_state").blur(); + }; + + $("load_state_input").onchange = async function() + { + var file = this.files[0]; + + if(!file) + { + return; + } + + var was_running = emulator.is_running(); + + if(was_running) + { + await emulator.stop(); + } + + var filereader = new FileReader(); + filereader.onload = async function(e) + { + try + { + await emulator.restore_state(e.target.result); + } + catch(err) + { + alert("Something bad happened while restoring the state:\n" + err + "\n\n" + + "Note that the current configuration must be the same as the original"); + throw err; + } + + if(was_running) + { + emulator.run(); + } + }; + filereader.readAsArrayBuffer(file); + + this.value = ""; + }; + + $("ctrlaltdel").onclick = function() + { + emulator.keyboard_send_scancodes([ + 0x1D, // ctrl + 0x38, // alt + 0x53, // delete + + // break codes + 0x1D | 0x80, + 0x38 | 0x80, + 0x53 | 0x80, + ]); + + $("ctrlaltdel").blur(); + }; + + $("alttab").onclick = function() + { + emulator.keyboard_send_scancodes([ + 0x38, // alt + 0x0F, // tab + ]); + + setTimeout(function() + { + emulator.keyboard_send_scancodes([ + 0x38 | 0x80, + 0x0F | 0x80, + ]); + }, 100); + + $("alttab").blur(); + }; + + $("scale").onchange = function() + { + var n = parseFloat(this.value); + + if(n || n > 0) + { + emulator.screen_set_scale(n, n); + } + }; + + $("fullscreen").onclick = function() + { + emulator.screen_go_fullscreen(); + }; + + $("screen_container").onclick = function() + { + if(mouse_is_enabled && os_uses_mouse) + { + emulator.lock_mouse(); + $("lock_mouse").blur(); + } + else + { + // allow text selection + if(window.getSelection().isCollapsed) + { + let phone_keyboard = document.getElementsByClassName("phone_keyboard")[0]; + + // stop mobile browser from scrolling into view when the keyboard is shown + phone_keyboard.style.top = document.body.scrollTop + 100 + "px"; + phone_keyboard.style.left = document.body.scrollLeft + 100 + "px"; + + phone_keyboard.focus(); + } + } + }; + + const phone_keyboard = document.getElementsByClassName("phone_keyboard")[0]; + + phone_keyboard.setAttribute("autocorrect", "off"); + phone_keyboard.setAttribute("autocapitalize", "off"); + phone_keyboard.setAttribute("spellcheck", "false"); + phone_keyboard.tabIndex = 0; + + $("screen_container").addEventListener("mousedown", e => + { + phone_keyboard.focus(); + }, false); + + $("take_screenshot").onclick = function() + { + emulator.screen_make_screenshot(); + $("take_screenshot").blur(); + }; + + if(emulator.speaker_adapter) + { + let is_muted = false; + + $("mute").onclick = function() + { + if(is_muted) + { + emulator.speaker_adapter.mixer.set_volume(1, undefined); + is_muted = false; + $("mute").value = "Mute"; + } + else + { + emulator.speaker_adapter.mixer.set_volume(0, undefined); + is_muted = true; + $("mute").value = "Unmute"; + } + + $("mute").blur(); + }; + } + else + { + $("mute").remove(); + } + + window.addEventListener("keydown", ctrl_w_rescue, false); + window.addEventListener("keyup", ctrl_w_rescue, false); + window.addEventListener("blur", ctrl_w_rescue, false); + + function ctrl_w_rescue(e) + { + if(e.ctrlKey) + { + window.onbeforeunload = function() + { + window.onbeforeunload = null; + return "CTRL-W cannot be sent to the emulator."; + }; + } + else + { + window.onbeforeunload = null; + } + } + } + + function init_filesystem_panel(emulator) + { + $("filesystem_panel").style.display = "block"; + + $("filesystem_send_file").onchange = function() + { + Array.prototype.forEach.call(this.files, function(file) + { + var loader = new v86util.SyncFileBuffer(file); + loader.onload = function() + { + loader.get_buffer(async function(buffer) + { + await emulator.create_file("/" + file.name, new Uint8Array(buffer)); + }); + }; + loader.load(); + }, this); + + this.value = ""; + this.blur(); + }; + + $("filesystem_get_file").onkeypress = async function(e) + { + if(e.which !== 13) + { + return; + } + + this.disabled = true; + + let result; + try + { + result = await emulator.read_file(this.value); + } + catch(err) + { + console.log(err); + } + + this.disabled = false; + + if(result) + { + var filename = this.value.replace(/\/$/, "").split("/"); + filename = filename[filename.length - 1] || "root"; + + dump_file(result, filename); + this.value = ""; + } + else + { + alert("Can't read file"); + } + }; + } + + function debug_start(emulator) + { + if(!emulator.v86) + { + return; + } + + // called as soon as soon as emulation is started, in debug mode + var debug = emulator.v86.cpu.debug; + + $("dump_gdt").onclick = debug.dump_gdt_ldt.bind(debug); + $("dump_idt").onclick = debug.dump_idt.bind(debug); + $("dump_regs").onclick = debug.dump_regs.bind(debug); + $("dump_pt").onclick = debug.dump_page_structures.bind(debug); + + $("dump_log").onclick = function() + { + dump_file(log_data.join(""), "v86.log"); + }; + + var cpu = emulator.v86.cpu; + + $("debug_panel").style.display = "block"; + setInterval(function() + { + $("debug_panel").textContent = + cpu.debug.get_regs_short().join("\n") + "\n" + cpu.debug.get_state(); + + $("dump_log").value = "Dump log" + (log_data.length ? " (" + log_data.length + " lines)" : ""); + }, 1000); + + // helps debugging + window.emulator = emulator; + window.cpu = cpu; + window.dump_file = dump_file; + } + + function onpopstate(e) + { + location.reload(); + } + + function set_profile(prof) + { + if(window.history.pushState) + { + window.history.pushState({ profile: prof }, "", "?profile=" + prof); + } + } + +})(); diff --git a/src/browser/mouse.js b/src/browser/mouse.js new file mode 100644 index 0000000..644200f --- /dev/null +++ b/src/browser/mouse.js @@ -0,0 +1,297 @@ +"use strict"; + +/** + * @constructor + * + * @param {BusConnector} bus + */ +function MouseAdapter(bus, screen_container) +{ + /** @const */ + var SPEED_FACTOR = 0.15; + + var left_down = false, + right_down = false, + middle_down = false, + + last_x = 0, + last_y = 0, + + mouse = this; + + // set by controller + this.enabled = false; + + // set by emulator + this.emu_enabled = true; + + this.bus = bus; + + this.bus.register("mouse-enable", function(enabled) + { + this.enabled = enabled; + }, this); + + // TODO: Should probably not use bus for this + this.is_running = false; + this.bus.register("emulator-stopped", function() + { + this.is_running = false; + }, this); + this.bus.register("emulator-started", function() + { + this.is_running = true; + }, this); + + this.destroy = function() + { + if(typeof window === "undefined") + { + return; + } + window.removeEventListener("touchstart", touch_start_handler, false); + window.removeEventListener("touchend", touch_end_handler, false); + window.removeEventListener("touchmove", mousemove_handler, false); + window.removeEventListener("mousemove", mousemove_handler, false); + window.removeEventListener("mousedown", mousedown_handler, false); + window.removeEventListener("mouseup", mouseup_handler, false); + window.removeEventListener("wheel", mousewheel_handler, { passive: false }); + }; + + this.init = function() + { + if(typeof window === "undefined") + { + return; + } + this.destroy(); + + window.addEventListener("touchstart", touch_start_handler, false); + window.addEventListener("touchend", touch_end_handler, false); + window.addEventListener("touchmove", mousemove_handler, false); + window.addEventListener("mousemove", mousemove_handler, false); + window.addEventListener("mousedown", mousedown_handler, false); + window.addEventListener("mouseup", mouseup_handler, false); + window.addEventListener("wheel", mousewheel_handler, { passive: false }); + }; + this.init(); + + function is_child(child, parent) + { + while(child.parentNode) + { + if(child === parent) + { + return true; + } + child = child.parentNode; + } + + return false; + } + + function may_handle(e) + { + if(!mouse.enabled || !mouse.emu_enabled) + { + return false; + } + + const MOVE_MOUSE_WHEN_OVER_SCREEN_ONLY = true; + + if(MOVE_MOUSE_WHEN_OVER_SCREEN_ONLY) + { + var parent = screen_container || document.body; + return document.pointerLockElement || is_child(e.target, parent); + } + else + { + if(e.type === "mousemove" || e.type === "touchmove") + { + return true; + } + + if(e.type === "mousewheel" || e.type === "DOMMouseScroll") + { + return is_child(e.target, parent); + } + + return !e.target || e.target.nodeName !== "INPUT" && e.target.nodeName !== "TEXTAREA"; + } + } + + function touch_start_handler(e) + { + if(may_handle(e)) + { + var touches = e["changedTouches"]; + + if(touches && touches.length) + { + var touch = touches[touches.length - 1]; + last_x = touch.clientX; + last_y = touch.clientY; + } + } + } + + function touch_end_handler(e) + { + if(left_down || middle_down || right_down) + { + mouse.bus.send("mouse-click", [false, false, false]); + left_down = middle_down = right_down = false; + } + } + + function mousemove_handler(e) + { + if(!mouse.bus) + { + return; + } + + if(!may_handle(e)) + { + return; + } + + if(!mouse.is_running) + { + return; + } + + var delta_x = 0; + var delta_y = 0; + + var touches = e["changedTouches"]; + + if(touches) + { + if(touches.length) + { + var touch = touches[touches.length - 1]; + delta_x = touch.clientX - last_x; + delta_y = touch.clientY - last_y; + + last_x = touch.clientX; + last_y = touch.clientY; + + e.preventDefault(); + } + } + else + { + if(typeof e["movementX"] === "number") + { + delta_x = e["movementX"]; + delta_y = e["movementY"]; + } + else if(typeof e["webkitMovementX"] === "number") + { + delta_x = e["webkitMovementX"]; + delta_y = e["webkitMovementY"]; + } + else if(typeof e["mozMovementX"] === "number") + { + delta_x = e["mozMovementX"]; + delta_y = e["mozMovementY"]; + } + else + { + // Fallback for other browsers? + delta_x = e.clientX - last_x; + delta_y = e.clientY - last_y; + + last_x = e.clientX; + last_y = e.clientY; + } + } + + delta_x *= SPEED_FACTOR; + delta_y *= SPEED_FACTOR; + + //if(Math.abs(delta_x) > 100 || Math.abs(delta_y) > 100) + //{ + // // Large mouse delta, drop? + //} + + delta_y = -delta_y; + + mouse.bus.send("mouse-delta", [delta_x, delta_y]); + + if(screen_container) + { + let absolute_x = e.pageX - screen_container.offsetLeft; + let absolute_y = e.pageY - screen_container.offsetTop; + mouse.bus.send("mouse-absolute", [ + absolute_x, absolute_y, screen_container.offsetWidth, screen_container.offsetHeight]); + } + } + + function mousedown_handler(e) + { + if(may_handle(e)) + { + click_event(e, true); + } + } + + function mouseup_handler(e) + { + if(may_handle(e)) + { + click_event(e, false); + } + } + + function click_event(e, down) + { + if(!mouse.bus) + { + return; + } + + if(e.which === 1) + { + left_down = down; + } + else if(e.which === 2) + { + middle_down = down; + } + else if(e.which === 3) + { + right_down = down; + } + else + { + dbg_log("Unknown event.which: " + e.which); + } + mouse.bus.send("mouse-click", [left_down, middle_down, right_down]); + e.preventDefault(); + } + + function mousewheel_handler(e) + { + if(!may_handle(e)) + { + return; + } + + var delta_x = e.wheelDelta || -e.detail; + var delta_y = 0; + + if(delta_x < 0) + { + delta_x = -1; + } + else if(delta_x > 0) + { + delta_x = 1; + } + + mouse.bus.send("mouse-wheel", [delta_x, delta_y]); + e.preventDefault(); + } +} diff --git a/src/browser/network.js b/src/browser/network.js new file mode 100644 index 0000000..b1b77f2 --- /dev/null +++ b/src/browser/network.js @@ -0,0 +1,142 @@ +"use strict"; + +/** + * An ethernet-through-websocket adapter, to be used with + * https://github.com/benjamincburns/websockproxy + * + * emulated ethernet card <--> this <--> websocket proxy <--> network + * + * @constructor + * + * @param {string} url + * @param {BusConnector} bus + */ +function NetworkAdapter(url, bus) +{ + this.bus = bus; + this.socket = undefined; + + // TODO: circular buffer? + this.send_queue = []; + this.url = url; + + this.reconnect_interval = 10000; + this.last_connect_attempt = Date.now() - this.reconnect_interval; + this.send_queue_limit = 64; + + this.bus.register("net0-send", function(data) + { + this.send(data); + }, this); +} + +NetworkAdapter.prototype.handle_message = function(e) +{ + if(this.bus) + { + this.bus.send("net0-receive", new Uint8Array(e.data)); + } +}; + +NetworkAdapter.prototype.handle_close = function(e) +{ + //console.log("onclose", e); + + this.connect(); + setTimeout(this.connect.bind(this), this.reconnect_interval); +}; + +NetworkAdapter.prototype.handle_open = function(e) +{ + //console.log("open", e); + + for(var i = 0; i < this.send_queue.length; i++) + { + this.send(this.send_queue[i]); + } + + this.send_queue = []; +}; + +NetworkAdapter.prototype.handle_error = function(e) +{ + //console.log("onerror", e); +}; + +NetworkAdapter.prototype.destroy = function() +{ + if(this.socket) + { + this.socket.close(); + } +}; + +NetworkAdapter.prototype.connect = function() +{ + if(typeof WebSocket === "undefined") + { + return; + } + + if(this.socket) + { + var state = this.socket.readyState; + + if(state === 0 || state === 1) + { + // already or almost there + return; + } + } + + var now = Date.now(); + + if(this.last_connect_attempt + this.reconnect_interval > now) + { + return; + } + + this.last_connect_attempt = Date.now(); + + this.socket = new WebSocket(this.url); + this.socket.binaryType = "arraybuffer"; + + this.socket.onopen = this.handle_open.bind(this); + this.socket.onmessage = this.handle_message.bind(this); + this.socket.onclose = this.handle_close.bind(this); + this.socket.onerror = this.handle_error.bind(this); +}; + +NetworkAdapter.prototype.send = function(data) +{ + //console.log("send", data); + + if(!this.socket || this.socket.readyState !== 1) + { + this.send_queue.push(data); + + if(this.send_queue.length > 2 * this.send_queue_limit) + { + this.send_queue = this.send_queue.slice(-this.send_queue_limit); + } + + this.connect(); + } + else + { + this.socket.send(data); + } +}; + +NetworkAdapter.prototype.change_proxy = function(url) +{ + this.url = url; + + if(this.socket) + { + this.socket.onclose = function() {}; + this.socket.onerror = function() {}; + this.socket.close(); + this.socket = undefined; + } +}; diff --git a/src/browser/print_stats.js b/src/browser/print_stats.js new file mode 100644 index 0000000..d8f72a7 --- /dev/null +++ b/src/browser/print_stats.js @@ -0,0 +1,287 @@ +"use strict"; + +const print_stats = { + stats_to_string: function(cpu) + { + return print_stats.print_misc_stats(cpu) + + print_stats.print_instruction_counts(cpu); + }, + + print_misc_stats: function(cpu) + { + let text = ""; + + const stat_names = [ + "COMPILE", + "COMPILE_SKIPPED_NO_NEW_ENTRY_POINTS", + "COMPILE_WRONG_ADDRESS_SPACE", + "COMPILE_CUT_OFF_AT_END_OF_PAGE", + "COMPILE_WITH_LOOP_SAFETY", + "COMPILE_PAGE", + "COMPILE_PAGE/COMPILE", + "COMPILE_BASIC_BLOCK", + "COMPILE_DUPLICATED_BASIC_BLOCK", + "COMPILE_WASM_BLOCK", + "COMPILE_WASM_LOOP", + "COMPILE_DISPATCHER", + "COMPILE_ENTRY_POINT", + "COMPILE_WASM_TOTAL_BYTES", + "COMPILE_WASM_TOTAL_BYTES/COMPILE_PAGE", + "RUN_INTERPRETED", + "RUN_INTERPRETED_NEW_PAGE", + "RUN_INTERPRETED_PAGE_HAS_CODE", + "RUN_INTERPRETED_PAGE_HAS_ENTRY_AFTER_PAGE_WALK", + "RUN_INTERPRETED_NEAR_END_OF_PAGE", + "RUN_INTERPRETED_DIFFERENT_STATE", + "RUN_INTERPRETED_DIFFERENT_STATE_CPL3", + "RUN_INTERPRETED_DIFFERENT_STATE_FLAT", + "RUN_INTERPRETED_DIFFERENT_STATE_IS32", + "RUN_INTERPRETED_DIFFERENT_STATE_SS32", + "RUN_INTERPRETED_MISSED_COMPILED_ENTRY_RUN_INTERPRETED", + "RUN_INTERPRETED_STEPS", + "RUN_FROM_CACHE", + "RUN_FROM_CACHE_STEPS", + "RUN_FROM_CACHE_STEPS/RUN_FROM_CACHE", + "RUN_FROM_CACHE_STEPS/RUN_INTERPRETED_STEPS", + "DIRECT_EXIT", + "INDIRECT_JUMP", + "INDIRECT_JUMP_NO_ENTRY", + "NORMAL_PAGE_CHANGE", + "NORMAL_FALLTHRU", + "NORMAL_FALLTHRU_WITH_TARGET_BLOCK", + "NORMAL_BRANCH", + "NORMAL_BRANCH_WITH_TARGET_BLOCK", + "CONDITIONAL_JUMP", + "CONDITIONAL_JUMP_PAGE_CHANGE", + "CONDITIONAL_JUMP_EXIT", + "CONDITIONAL_JUMP_FALLTHRU", + "CONDITIONAL_JUMP_FALLTHRU_WITH_TARGET_BLOCK", + "CONDITIONAL_JUMP_BRANCH", + "CONDITIONAL_JUMP_BRANCH_WITH_TARGET_BLOCK", + "DISPATCHER_SMALL", + "DISPATCHER_LARGE", + "LOOP", + "LOOP_SAFETY", + "CONDITION_OPTIMISED", + "CONDITION_UNOPTIMISED", + "CONDITION_UNOPTIMISED_PF", + "CONDITION_UNOPTIMISED_UNHANDLED_L", + "CONDITION_UNOPTIMISED_UNHANDLED_LE", + "FAILED_PAGE_CHANGE", + "SAFE_READ_FAST", + "SAFE_READ_SLOW_PAGE_CROSSED", + "SAFE_READ_SLOW_NOT_VALID", + "SAFE_READ_SLOW_NOT_USER", + "SAFE_READ_SLOW_IN_MAPPED_RANGE", + "SAFE_WRITE_FAST", + "SAFE_WRITE_SLOW_PAGE_CROSSED", + "SAFE_WRITE_SLOW_NOT_VALID", + "SAFE_WRITE_SLOW_NOT_USER", + "SAFE_WRITE_SLOW_IN_MAPPED_RANGE", + "SAFE_WRITE_SLOW_READ_ONLY", + "SAFE_WRITE_SLOW_HAS_CODE", + "SAFE_READ_WRITE_FAST", + "SAFE_READ_WRITE_SLOW_PAGE_CROSSED", + "SAFE_READ_WRITE_SLOW_NOT_VALID", + "SAFE_READ_WRITE_SLOW_NOT_USER", + "SAFE_READ_WRITE_SLOW_IN_MAPPED_RANGE", + "SAFE_READ_WRITE_SLOW_READ_ONLY", + "SAFE_READ_WRITE_SLOW_HAS_CODE", + "PAGE_FAULT", + "TLB_MISS", + "DO_MANY_CYCLES", + "CYCLE_INTERNAL", + "INVALIDATE_ALL_MODULES_NO_FREE_WASM_INDICES", + "INVALIDATE_MODULE_WRITTEN_WHILE_COMPILED", + "INVALIDATE_MODULE_UNUSED_AFTER_OVERWRITE", + "INVALIDATE_MODULE_DIRTY_PAGE", + "INVALIDATE_PAGE_HAD_CODE", + "INVALIDATE_PAGE_HAD_ENTRY_POINTS", + "DIRTY_PAGE_DID_NOT_HAVE_CODE", + "RUN_FROM_CACHE_EXIT_SAME_PAGE", + "RUN_FROM_CACHE_EXIT_NEAR_END_OF_PAGE", + "RUN_FROM_CACHE_EXIT_DIFFERENT_PAGE", + "CLEAR_TLB", + "FULL_CLEAR_TLB", + "TLB_FULL", + "TLB_GLOBAL_FULL", + "MODRM_SIMPLE_REG", + "MODRM_SIMPLE_REG_WITH_OFFSET", + "MODRM_SIMPLE_CONST_OFFSET", + "MODRM_COMPLEX", + "SEG_OFFSET_OPTIMISED", + "SEG_OFFSET_NOT_OPTIMISED", + "SEG_OFFSET_NOT_OPTIMISED_ES", + "SEG_OFFSET_NOT_OPTIMISED_FS", + "SEG_OFFSET_NOT_OPTIMISED_GS", + "SEG_OFFSET_NOT_OPTIMISED_NOT_FLAT", + ]; + + let j = 0; + const stat_values = {}; + for(let i = 0; i < stat_names.length; i++) + { + const name = stat_names[i]; + let value; + if(name.includes("/")) + { + j++; // skip profiler_stat_get + const [left, right] = name.split("/"); + value = stat_values[left] / stat_values[right]; + } + else + { + let stat = stat_values[name] = cpu.wm.exports["profiler_stat_get"](i - j); + value = stat >= 100e6 ? Math.round(stat / 1e6) + "m" : stat >= 100e3 ? Math.round(stat / 1e3) + "k" : stat; + } + text += name + "=" + value + "\n"; + } + + text += "\n"; + + const tlb_entries = cpu.wm.exports["get_valid_tlb_entries_count"](); + const global_tlb_entries = cpu.wm.exports["get_valid_global_tlb_entries_count"](); + const nonglobal_tlb_entries = tlb_entries - global_tlb_entries; + + text += "TLB_ENTRIES=" + tlb_entries + " (" + global_tlb_entries + " global, " + nonglobal_tlb_entries + " non-global)\n"; + text += "WASM_TABLE_FREE=" + cpu.wm.exports["jit_get_wasm_table_index_free_list_count"]() + "\n"; + text += "JIT_CACHE_SIZE=" + cpu.wm.exports["jit_get_cache_size"]() + "\n"; + text += "FLAT_SEGMENTS=" + cpu.wm.exports["has_flat_segmentation"]() + "\n"; + + text += "do_many_cycles avg: " + (cpu.do_many_cycles_total / cpu.do_many_cycles_count || 0) + "\n"; + text += "wasm memory size: " + (cpu.wasm_memory.buffer.byteLength >> 20) + "m\n"; + + text += "Config:\n"; + text += "MAX_PAGES=" + cpu.wm.exports["get_jit_config"](0) + "\n"; + text += "JIT_USE_LOOP_SAFETY=" + Boolean(cpu.wm.exports["get_jit_config"](1)) + "\n"; + text += "MAX_EXTRA_BASIC_BLOCKS=" + cpu.wm.exports["get_jit_config"](2) + "\n"; + + return text; + }, + + print_instruction_counts: function(cpu) + { + return [ + print_stats.print_instruction_counts_offset(cpu, false, false, false, false), + print_stats.print_instruction_counts_offset(cpu, true, false, false, false), + print_stats.print_instruction_counts_offset(cpu, false, true, false, false), + print_stats.print_instruction_counts_offset(cpu, false, false, true, false), + print_stats.print_instruction_counts_offset(cpu, false, false, false, true), + ].join("\n\n"); + }, + + print_instruction_counts_offset: function(cpu, compiled, jit_exit, unguarded_register, wasm_size) + { + let text = ""; + + const counts = []; + + const label = + compiled ? "compiled" : + jit_exit ? "jit exit" : + unguarded_register ? "unguarded register" : + wasm_size ? "wasm size" : + "executed"; + + for(let opcode = 0; opcode < 0x100; opcode++) + { + for(let fixed_g = 0; fixed_g < 8; fixed_g++) + { + for(let is_mem of [false, true]) + { + const count = cpu.wm.exports["get_opstats_buffer"](compiled, jit_exit, unguarded_register, wasm_size, opcode, false, is_mem, fixed_g); + counts.push({ opcode, count, is_mem, fixed_g }); + + const count_0f = cpu.wm.exports["get_opstats_buffer"](compiled, jit_exit, unguarded_register, wasm_size, opcode, true, is_mem, fixed_g); + counts.push({ opcode: 0x0f00 | opcode, count: count_0f, is_mem, fixed_g }); + } + } + } + + let total = 0; + const prefixes = new Set([ + 0x26, 0x2E, 0x36, 0x3E, + 0x64, 0x65, 0x66, 0x67, + 0xF0, 0xF2, 0xF3, + ]); + for(let { count, opcode } of counts) + { + if(!prefixes.has(opcode)) + { + total += count; + } + } + + if(total === 0) + { + return ""; + } + + const per_opcode = new Uint32Array(0x100); + const per_opcode0f = new Uint32Array(0x100); + + for(let { opcode, count } of counts) + { + if((opcode & 0xFF00) == 0x0F00) + { + per_opcode0f[opcode & 0xFF] += count; + } + else + { + per_opcode[opcode & 0xFF] += count; + } + } + + text += "------------------\n"; + text += "Total: " + total + "\n"; + + const factor = total > 1e7 ? 1000 : 1; + + const max_count = Math.max.apply(Math, + counts.map(({ count }) => Math.round(count / factor)) + ); + const pad_length = String(max_count).length; + + text += `Instruction counts ${label} (in ${factor}):\n`; + + for(let i = 0; i < 0x100; i++) + { + text += i.toString(16).padStart(2, "0") + ":" + v86util.pads(Math.round(per_opcode[i] / factor), pad_length); + + if(i % 16 == 15) + text += "\n"; + else + text += " "; + } + + text += "\n"; + text += `Instruction counts ${label} (0f, in ${factor}):\n`; + + for(let i = 0; i < 0x100; i++) + { + text += (i & 0xFF).toString(16).padStart(2, "0") + ":" + v86util.pads(Math.round(per_opcode0f[i] / factor), pad_length); + + if(i % 16 == 15) + text += "\n"; + else + text += " "; + } + text += "\n"; + + const top_counts = counts.filter(({ count }) => count).sort(({ count: count1 }, { count: count2 }) => count2 - count1); + + for(let { opcode, is_mem, fixed_g, count } of top_counts.slice(0, 200)) + { + let opcode_description = opcode.toString(16) + "_" + fixed_g + (is_mem ? "_m" : "_r"); + text += opcode_description + ":" + (count / total * 100).toFixed(2) + " "; + } + text += "\n"; + + return text; + }, +}; + +if(typeof module !== "undefined" && typeof module.exports !== "undefined") +{ + module.exports["print_stats"] = print_stats; +} diff --git a/src/browser/screen.js b/src/browser/screen.js new file mode 100644 index 0000000..4667519 --- /dev/null +++ b/src/browser/screen.js @@ -0,0 +1,565 @@ +"use strict"; + +/** + * Adapter to use visual screen in browsers (in contrast to node) + * @constructor + * + * @param {BusConnector} bus + */ +function ScreenAdapter(screen_container, bus) +{ + console.assert(screen_container, "1st argument must be a DOM container"); + + var + graphic_screen = screen_container.getElementsByTagName("canvas")[0], + graphic_context = graphic_screen.getContext("2d", { alpha: false }), + + text_screen = screen_container.getElementsByTagName("div")[0], + cursor_element = document.createElement("div"); + + var + /** @type {number} */ + cursor_row, + + /** @type {number} */ + cursor_col, + + /** @type {number} */ + scale_x = 1, + + /** @type {number} */ + scale_y = 1, + + base_scale = 1, + + changed_rows, + + // are we in graphical mode now? + is_graphical = false, + + // Index 0: ASCII code + // Index 1: Background color + // Index 2: Foreground color + text_mode_data, + + // number of columns + text_mode_width, + + // number of rows + text_mode_height; + + var stopped = false; + + var screen = this; + + // 0x12345 -> "#012345" + function number_as_color(n) + { + n = n.toString(16); + return "#" + "0".repeat(6 - n.length) + n; + } + + + /** + * Charmaps that constraint unicode sequences for the default dospage + * @const + */ + var charmap_high = new Uint16Array([ + 0xC7, 0xFC, 0xE9, 0xE2, 0xE4, 0xE0, 0xE5, 0xE7, + 0xEA, 0xEB, 0xE8, 0xEF, 0xEE, 0xEC, 0xC4, 0xC5, + 0xC9, 0xE6, 0xC6, 0xF4, 0xF6, 0xF2, 0xFB, 0xF9, + 0xFF, 0xD6, 0xDC, 0xA2, 0xA3, 0xA5, 0x20A7, 0x192, + 0xE1, 0xED, 0xF3, 0xFA, 0xF1, 0xD1, 0xAA, 0xBA, + 0xBF, 0x2310, 0xAC, 0xBD, 0xBC, 0xA1, 0xAB, 0xBB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, + 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, + 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, + 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x3B1, 0xDF, 0x393, 0x3C0, 0x3A3, 0x3C3, 0xB5, 0x3C4, + 0x3A6, 0x398, 0x3A9, 0x3B4, 0x221E, 0x3C6, 0x3B5, 0x2229, + 0x2261, 0xB1, 0x2265, 0x2264, 0x2320, 0x2321, 0xF7, + 0x2248, 0xB0, 0x2219, 0xB7, 0x221A, 0x207F, 0xB2, 0x25A0, 0xA0 + ]); + + /** @const */ + var charmap_low = new Uint16Array([ + 0x20, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022, + 0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C, + 0x25BA, 0x25C4, 0x2195, 0x203C, 0xB6, 0xA7, 0x25AC, 0x21A8, + 0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC + ]); + + var charmap = [], + chr; + + for(var i = 0; i < 256; i++) + { + if(i > 127) + { + chr = charmap_high[i - 0x80]; + } + else if(i < 32) + { + chr = charmap_low[i]; + } + else + { + chr = i; + } + + charmap[i] = String.fromCharCode(chr); + } + + graphic_context.imageSmoothingEnabled = false; + + cursor_element.style.position = "absolute"; + cursor_element.style.backgroundColor = "#ccc"; + cursor_element.style.width = "7px"; + cursor_element.style.display = "inline-block"; + + text_screen.style.display = "block"; + graphic_screen.style.display = "none"; + + this.bus = bus; + + bus.register("screen-set-mode", function(data) + { + this.set_mode(data); + }, this); + + bus.register("screen-fill-buffer-end", function(data) + { + this.update_buffer(data); + }, this); + + bus.register("screen-put-char", function(data) + { + //console.log(data); + this.put_char(data[0], data[1], data[2], data[3], data[4]); + }, this); + + bus.register("screen-update-cursor", function(data) + { + this.update_cursor(data[0], data[1]); + }, this); + bus.register("screen-update-cursor-scanline", function(data) + { + this.update_cursor_scanline(data[0], data[1]); + }, this); + + bus.register("screen-clear", function() + { + this.clear_screen(); + }, this); + + bus.register("screen-set-size-text", function(data) + { + this.set_size_text(data[0], data[1]); + }, this); + bus.register("screen-set-size-graphical", function(data) + { + this.set_size_graphical(data[0], data[1], data[2], data[3]); + }, this); + + + this.init = function() + { + // not necessary, because this gets initialized by the bios early, + // but nicer to look at + this.set_size_text(80, 25); + + this.timer(); + }; + + this.make_screenshot = function() + { + const image = new Image(); + + if(is_graphical) + { + image.src = graphic_screen.toDataURL("image/png"); + } + else + { + // Default 720x400, but can be [8, 16] at 640x400 + const char_size = [9, 16]; + + const canvas = document.createElement("canvas"); + canvas.width = text_mode_width * char_size[0]; + canvas.height = text_mode_height * char_size[1]; + const context = canvas.getContext("2d"); + context.imageSmoothingEnabled = false; + context.font = window.getComputedStyle(text_screen).font; + context.textBaseline = "top"; + + for(let x = 0; x < text_mode_width; x++) + { + for(let y = 0; y < text_mode_height; y++) + { + const index = (y * text_mode_width + x) * 3; + context.fillStyle = number_as_color(text_mode_data[index + 1]); + context.fillRect(x * char_size[0], y * char_size[1], char_size[0], char_size[1]); + context.fillStyle = number_as_color(text_mode_data[index + 2]); + context.fillText(charmap[text_mode_data[index]], x * char_size[0], y * char_size[1]); + } + } + + if(cursor_element.style.display !== "none") + { + context.fillStyle = cursor_element.style.backgroundColor; + context.fillRect( + cursor_col * char_size[0], + cursor_row * char_size[1] + parseInt(cursor_element.style.marginTop, 10) - 1, + parseInt(cursor_element.style.width, 10), + parseInt(cursor_element.style.height, 10) + ); + } + + image.src = canvas.toDataURL("image/png"); + } + + try { + const w = window.open(""); + w.document.write(image.outerHTML); + } + catch(e) {} + }; + + this.put_char = function(row, col, chr, bg_color, fg_color) + { + if(row < text_mode_height && col < text_mode_width) + { + var p = 3 * (row * text_mode_width + col); + + dbg_assert(chr >= 0 && chr < 0x100); + text_mode_data[p] = chr; + text_mode_data[p + 1] = bg_color; + text_mode_data[p + 2] = fg_color; + + changed_rows[row] = 1; + } + }; + + this.timer = function() + { + if(!stopped) + { + requestAnimationFrame(is_graphical ? update_graphical : update_text); + } + }; + + var update_text = function() + { + for(var i = 0; i < text_mode_height; i++) + { + if(changed_rows[i]) + { + screen.text_update_row(i); + changed_rows[i] = 0; + } + } + + this.timer(); + }.bind(this); + + var update_graphical = function() + { + this.bus.send("screen-fill-buffer"); + this.timer(); + }.bind(this); + + this.destroy = function() + { + stopped = true; + }; + + this.set_mode = function(graphical) + { + is_graphical = graphical; + + if(graphical) + { + text_screen.style.display = "none"; + graphic_screen.style.display = "block"; + } + else + { + text_screen.style.display = "block"; + graphic_screen.style.display = "none"; + } + }; + + this.clear_screen = function() + { + graphic_context.fillStyle = "#000"; + graphic_context.fillRect(0, 0, graphic_screen.width, graphic_screen.height); + }; + + /** + * @param {number} cols + * @param {number} rows + */ + this.set_size_text = function(cols, rows) + { + if(cols === text_mode_width && rows === text_mode_height) + { + return; + } + + changed_rows = new Int8Array(rows); + text_mode_data = new Int32Array(cols * rows * 3); + + text_mode_width = cols; + text_mode_height = rows; + + while(text_screen.childNodes.length > rows) + { + text_screen.removeChild(text_screen.firstChild); + } + + while(text_screen.childNodes.length < rows) + { + text_screen.appendChild(document.createElement("div")); + } + + for(var i = 0; i < rows; i++) + { + this.text_update_row(i); + } + + update_scale_text(); + }; + + this.set_size_graphical = function(width, height, buffer_width, buffer_height) + { + if(DEBUG_SCREEN_LAYERS) + { + // Draw the entire buffer. Useful for debugging + // panning / page flipping / screen splitting code for both + // v86 developers and os developers + width = buffer_width; + height = buffer_height; + } + + graphic_screen.style.display = "block"; + + graphic_screen.width = width; + graphic_screen.height = height; + + // add some scaling to tiny resolutions + if(width <= 640 && width * 2 < window.innerWidth && width * 2 < window.innerHeight) + { + base_scale = 2; + } + else + { + base_scale = 1; + } + + update_scale_graphic(); + }; + + this.set_scale = function(s_x, s_y) + { + scale_x = s_x; + scale_y = s_y; + + update_scale_text(); + update_scale_graphic(); + }; + this.set_scale(scale_x, scale_y); + + function update_scale_text() + { + elem_set_scale(text_screen, scale_x, scale_y, true); + } + + function update_scale_graphic() + { + elem_set_scale(graphic_screen, scale_x * base_scale, scale_y * base_scale, false); + } + + function elem_set_scale(elem, scale_x, scale_y, use_scale) + { + elem.style.width = ""; + elem.style.height = ""; + + if(use_scale) + { + elem.style.transform = ""; + } + + var rectangle = elem.getBoundingClientRect(); + + if(use_scale) + { + var scale_str = ""; + + scale_str += scale_x === 1 ? "" : " scaleX(" + scale_x + ")"; + scale_str += scale_y === 1 ? "" : " scaleY(" + scale_y + ")"; + + elem.style.transform = scale_str; + } + else + { + // unblur non-fractional scales + if(scale_x % 1 === 0 && scale_y % 1 === 0) + { + graphic_screen.style["imageRendering"] = "crisp-edges"; // firefox + graphic_screen.style["imageRendering"] = "pixelated"; + graphic_screen.style["-ms-interpolation-mode"] = "nearest-neighbor"; + } + else + { + graphic_screen.style.imageRendering = ""; + graphic_screen.style["-ms-interpolation-mode"] = ""; + } + + // undo fractional css-to-device pixel ratios + var device_pixel_ratio = window.devicePixelRatio || 1; + if(device_pixel_ratio % 1 !== 0) + { + scale_x /= device_pixel_ratio; + scale_y /= device_pixel_ratio; + } + } + + if(scale_x !== 1) + { + elem.style.width = rectangle.width * scale_x + "px"; + } + if(scale_y !== 1) + { + elem.style.height = rectangle.height * scale_y + "px"; + } + } + + this.update_cursor_scanline = function(start, end) + { + if(start & 0x20) + { + cursor_element.style.display = "none"; + } + else + { + cursor_element.style.display = "inline"; + + cursor_element.style.height = Math.min(15, end - start) + "px"; + cursor_element.style.marginTop = Math.min(15, start) + "px"; + } + }; + + this.update_cursor = function(row, col) + { + if(row !== cursor_row || col !== cursor_col) + { + changed_rows[row] = 1; + changed_rows[cursor_row] = 1; + + cursor_row = row; + cursor_col = col; + } + }; + + this.text_update_row = function(row) + { + var offset = 3 * row * text_mode_width, + row_element, + color_element, + fragment; + + var bg_color, + fg_color, + text; + + row_element = text_screen.childNodes[row]; + fragment = document.createElement("div"); + + for(var i = 0; i < text_mode_width; ) + { + color_element = document.createElement("span"); + + bg_color = text_mode_data[offset + 1]; + fg_color = text_mode_data[offset + 2]; + + color_element.style.backgroundColor = number_as_color(bg_color); + color_element.style.color = number_as_color(fg_color); + + text = ""; + + // put characters of the same color in one element + while(i < text_mode_width && + text_mode_data[offset + 1] === bg_color && + text_mode_data[offset + 2] === fg_color) + { + var ascii = text_mode_data[offset]; + + text += charmap[ascii]; + dbg_assert(charmap[ascii]); + + i++; + offset += 3; + + if(row === cursor_row) + { + if(i === cursor_col) + { + // next row will be cursor + // create new element + break; + } + else if(i === cursor_col + 1) + { + // found the cursor + fragment.appendChild(cursor_element); + break; + } + } + } + + color_element.textContent = text; + fragment.appendChild(color_element); + } + + row_element.parentNode.replaceChild(fragment, row_element); + }; + + this.update_buffer = function(layers) + { + if(DEBUG_SCREEN_LAYERS) + { + // For each visible layer that would've been drawn, draw a + // rectangle to visualise the layer instead. + graphic_context.strokeStyle = "#0F0"; + graphic_context.lineWidth = 4; + layers.forEach(layer => + { + graphic_context.strokeRect( + layer.buffer_x, + layer.buffer_y, + layer.buffer_width, + layer.buffer_height + ); + }); + graphic_context.lineWidth = 1; + return; + } + + layers.forEach(layer => + { + graphic_context.putImageData( + layer.image_data, + layer.screen_x - layer.buffer_x, + layer.screen_y - layer.buffer_y, + layer.buffer_x, + layer.buffer_y, + layer.buffer_width, + layer.buffer_height + ); + }); + }; + + this.init(); +} diff --git a/src/browser/serial.js b/src/browser/serial.js new file mode 100644 index 0000000..7c59050 --- /dev/null +++ b/src/browser/serial.js @@ -0,0 +1,251 @@ +"use strict"; + +/** + * @constructor + * + * @param {BusConnector} bus + */ +function SerialAdapter(element, bus) +{ + var serial = this; + + this.enabled = true; + this.bus = bus; + this.text = ""; + this.text_new_line = false; + + this.last_update = 0; + + + this.bus.register("serial0-output-char", function(chr) + { + this.show_char(chr); + }, this); + + + this.destroy = function() + { + element.removeEventListener("keypress", keypress_handler, false); + element.removeEventListener("keydown", keydown_handler, false); + element.removeEventListener("paste", paste_handler, false); + window.removeEventListener("mousedown", window_click_handler, false); + }; + + this.init = function() + { + this.destroy(); + + element.style.display = "block"; + element.addEventListener("keypress", keypress_handler, false); + element.addEventListener("keydown", keydown_handler, false); + element.addEventListener("paste", paste_handler, false); + window.addEventListener("mousedown", window_click_handler, false); + }; + this.init(); + + + this.show_char = function(chr) + { + if(chr === "\x08") + { + this.text = this.text.slice(0, -1); + this.update(); + } + else if(chr === "\r") + { + // do nothing + } + else + { + this.text += chr; + + if(chr === "\n") + { + this.text_new_line = true; + } + + this.update(); + } + }; + + this.update = function() + { + var now = Date.now(); + var delta = now - this.last_update; + + if(delta < 16) + { + if(this.update_timer === undefined) + { + this.update_timer = setTimeout(() => { + this.update_timer = undefined; + var now = Date.now(); + dbg_assert(now - this.last_update >= 15); + this.last_update = now; + this.render(); + }, 16 - delta); + } + } + else + { + if(this.update_timer !== undefined) + { + clearTimeout(this.update_timer); + this.update_timer = undefined; + } + + this.last_update = now; + this.render(); + } + }; + + this.render = function() + { + element.value = this.text; + + if(this.text_new_line) + { + this.text_new_line = false; + element.scrollTop = 1e9; + } + }; + + /** + * @param {number} chr_code + */ + this.send_char = function(chr_code) + { + if(serial.bus) + { + serial.bus.send("serial0-input", chr_code); + } + }; + + function may_handle(e) + { + if(!serial.enabled) + { + return false; + } + + // Something here? + + return true; + } + + function keypress_handler(e) + { + if(!serial.bus) + { + return; + } + if(!may_handle(e)) + { + return; + } + + var chr = e.which; + + serial.send_char(chr); + e.preventDefault(); + } + + function keydown_handler(e) + { + var chr = e.which; + + if(chr === 8) + { + // supress backspace + serial.send_char(127); + e.preventDefault(); + } + else if(chr === 9) + { + // tab + serial.send_char(9); + e.preventDefault(); + } + } + + function paste_handler(e) + { + if(!may_handle(e)) + { + return; + } + + var data = e.clipboardData.getData("text/plain"); + + for(var i = 0; i < data.length; i++) + { + serial.send_char(data.charCodeAt(i)); + } + + e.preventDefault(); + } + + function window_click_handler(e) + { + if(e.target !== element) + { + element.blur(); + } + } +} + +/** + * @constructor + * + * @param {BusConnector} bus + */ +function SerialRecordingAdapter(bus) +{ + var serial = this; + this.text = ""; + + bus.register("serial0-output-char", function(chr) + { + this.text += chr; + }, this); +} + +/** + * @constructor + * @param {BusConnector} bus + */ +function SerialAdapterXtermJS(element, bus) +{ + this.element = element; + + if(!window["Terminal"]) + { + return; + } + + var term = this.term = new window["Terminal"](); + term["setOption"]("logLevel", "off"); + term.write("This is the serial console. Whatever you type or paste here will be sent to COM1"); + + const on_data_disposable = term["onData"](function(data) { + for(let i = 0; i < data.length; i++) + { + bus.send("serial0-input", data.charCodeAt(i)); + } + }); + + bus.register("serial0-output-char", function(chr) + { + term.write(chr); + }, this); + + this.destroy = function() { + on_data_disposable["dispose"](); + term["dispose"](); + }; +} + +SerialAdapterXtermJS.prototype.show = function() +{ + this.term && this.term.open(this.element); +}; diff --git a/src/browser/speaker.js b/src/browser/speaker.js new file mode 100644 index 0000000..3039ad3 --- /dev/null +++ b/src/browser/speaker.js @@ -0,0 +1,1119 @@ +"use strict"; + +/** @const */ +var DAC_QUEUE_RESERVE = 0.2; + +/** @const */ +var AUDIOBUFFER_MINIMUM_SAMPLING_RATE = 8000; + +/** + * @constructor + * @param {!BusConnector} bus + */ +function SpeakerAdapter(bus) +{ + if(typeof window === "undefined") + { + return; + } + if(!window.AudioContext && !window["webkitAudioContext"]) + { + console.warn("Web browser doesn't support Web Audio API"); + return; + } + + var SpeakerDAC = window.AudioWorklet ? SpeakerWorkletDAC : SpeakerBufferSourceDAC; + + /** @const */ + this.bus = bus; + + /** @const */ + this.audio_context = window.AudioContext ? new AudioContext() : new webkitAudioContext(); + + /** @const */ + this.mixer = new SpeakerMixer(bus, this.audio_context); + + /** @const */ + this.pcspeaker = new PCSpeaker(bus, this.audio_context, this.mixer); + + /** @const */ + this.dac = new SpeakerDAC(bus, this.audio_context, this.mixer); + + this.pcspeaker.start(); + + bus.register("emulator-stopped", function() + { + this.audio_context.suspend(); + }, this); + + bus.register("emulator-started", function() + { + this.audio_context.resume(); + }, this); + + bus.register("speaker-confirm-initialized", function() + { + bus.send("speaker-has-initialized"); + }, this); + bus.send("speaker-has-initialized"); +} + +SpeakerAdapter.prototype.destroy = function() +{ + this.audio_context && this.audio_context.close(); + this.dac && this.dac.node_processor && this.dac.node_processor.port.close(); +}; + +/** + * @constructor + * @param {!BusConnector} bus + * @param {!AudioContext} audio_context + */ +function SpeakerMixer(bus, audio_context) +{ + /** @const */ + this.audio_context = audio_context; + + this.sources = new Map(); + + // States + + this.volume_both = 1; + this.volume_left = 1; + this.volume_right = 1; + this.gain_left = 1; + this.gain_right = 1; + + // Nodes + // TODO: Find / calibrate / verify the filter frequencies + + this.node_treble_left = this.audio_context.createBiquadFilter(); + this.node_treble_right = this.audio_context.createBiquadFilter(); + this.node_treble_left.type = "highshelf"; + this.node_treble_right.type = "highshelf"; + this.node_treble_left.frequency.setValueAtTime(2000, this.audio_context.currentTime); + this.node_treble_right.frequency.setValueAtTime(2000, this.audio_context.currentTime); + + this.node_bass_left = this.audio_context.createBiquadFilter(); + this.node_bass_right = this.audio_context.createBiquadFilter(); + this.node_bass_left.type = "lowshelf"; + this.node_bass_right.type = "lowshelf"; + this.node_bass_left.frequency.setValueAtTime(200, this.audio_context.currentTime); + this.node_bass_right.frequency.setValueAtTime(200, this.audio_context.currentTime); + + this.node_gain_left = this.audio_context.createGain(); + this.node_gain_right = this.audio_context.createGain(); + + this.node_merger = this.audio_context.createChannelMerger(2); + + // Graph + + this.input_left = this.node_treble_left; + this.input_right = this.node_treble_right; + + this.node_treble_left.connect(this.node_bass_left); + this.node_bass_left.connect(this.node_gain_left); + this.node_gain_left.connect(this.node_merger, 0, 0); + + this.node_treble_right.connect(this.node_bass_right); + this.node_bass_right.connect(this.node_gain_right); + this.node_gain_right.connect(this.node_merger, 0, 1); + + this.node_merger.connect(this.audio_context.destination); + + // Interface + + bus.register("mixer-connect", function(data) + { + var source_id = data[0]; + var channel = data[1]; + this.connect_source(source_id, channel); + }, this); + + bus.register("mixer-disconnect", function(data) + { + var source_id = data[0]; + var channel = data[1]; + this.disconnect_source(source_id, channel); + }, this); + + bus.register("mixer-volume", function(data) + { + var source_id = data[0]; + var channel = data[1]; + var decibels = data[2]; + + var gain = Math.pow(10, decibels / 20); + + var source = source_id === MIXER_SRC_MASTER ? this : this.sources.get(source_id); + + if(source === undefined) + { + dbg_assert(false, "Mixer set volume - cannot set volume for undefined source: " + source_id); + return; + } + + source.set_volume(gain, channel); + }, this); + + bus.register("mixer-gain-left", function(/** number */ decibels) + { + this.gain_left = Math.pow(10, decibels / 20); + this.update(); + }, this); + + bus.register("mixer-gain-right", function(/** number */ decibels) + { + this.gain_right = Math.pow(10, decibels / 20); + this.update(); + }, this); + + function create_gain_handler(audio_node) + { + return function(decibels) + { + audio_node.gain.setValueAtTime(decibels, this.audio_context.currentTime); + }; + } + bus.register("mixer-treble-left", create_gain_handler(this.node_treble_left), this); + bus.register("mixer-treble-right", create_gain_handler(this.node_treble_right), this); + bus.register("mixer-bass-left", create_gain_handler(this.node_bass_left), this); + bus.register("mixer-bass-right", create_gain_handler(this.node_bass_right), this); +} + +/** + * @param {!AudioNode} source_node + * @param {number} source_id + * @return {SpeakerMixerSource} + */ +SpeakerMixer.prototype.add_source = function(source_node, source_id) +{ + var source = new SpeakerMixerSource( + this.audio_context, + source_node, + this.input_left, + this.input_right + ); + + dbg_assert(!this.sources.has(source_id), "Mixer add source - overwritting source: " + source_id); + + this.sources.set(source_id, source); + return source; +}; + +/** + * @param {number} source_id + * @param {number=} channel + */ +SpeakerMixer.prototype.connect_source = function(source_id, channel) +{ + var source = this.sources.get(source_id); + + if(source === undefined) + { + dbg_assert(false, "Mixer connect - cannot connect undefined source: " + source_id); + return; + } + + source.connect(channel); +}; + +/** + * @param {number} source_id + * @param {number=} channel + */ +SpeakerMixer.prototype.disconnect_source = function(source_id, channel) +{ + var source = this.sources.get(source_id); + + if(source === undefined) + { + dbg_assert(false, "Mixer disconnect - cannot disconnect undefined source: " + source_id); + return; + } + + source.disconnect(channel); +}; + +/** + * @param {number} value + * @param {number=} channel + */ +SpeakerMixer.prototype.set_volume = function(value, channel) +{ + if(channel === undefined) + { + channel = MIXER_CHANNEL_BOTH; + } + + switch(channel) + { + case MIXER_CHANNEL_LEFT: + this.volume_left = value; + break; + case MIXER_CHANNEL_RIGHT: + this.volume_right = value; + break; + case MIXER_CHANNEL_BOTH: + this.volume_both = value; + break; + default: + dbg_assert(false, "Mixer set master volume - unknown channel: " + channel); + return; + } + + this.update(); +}; + +SpeakerMixer.prototype.update = function() +{ + var net_gain_left = this.volume_both * this.volume_left * this.gain_left; + var net_gain_right = this.volume_both * this.volume_right * this.gain_right; + + this.node_gain_left.gain.setValueAtTime(net_gain_left, this.audio_context.currentTime); + this.node_gain_right.gain.setValueAtTime(net_gain_right, this.audio_context.currentTime); +}; + +/** + * @constructor + * @param {!AudioContext} audio_context + * @param {!AudioNode} source_node + * @param {!AudioNode} destination_left + * @param {!AudioNode} destination_right + */ +function SpeakerMixerSource(audio_context, source_node, destination_left, destination_right) +{ + /** @const */ + this.audio_context = audio_context; + + // States + + this.connected_left = true; + this.connected_right = true; + this.gain_hidden = 1; + this.volume_both = 1; + this.volume_left = 1; + this.volume_right = 1; + + // Nodes + + this.node_splitter = audio_context.createChannelSplitter(2); + this.node_gain_left = audio_context.createGain(); + this.node_gain_right = audio_context.createGain(); + + // Graph + + source_node.connect(this.node_splitter); + + this.node_splitter.connect(this.node_gain_left, 0); + this.node_gain_left.connect(destination_left); + + this.node_splitter.connect(this.node_gain_right, 1); + this.node_gain_right.connect(destination_right); +} + +SpeakerMixerSource.prototype.update = function() +{ + var net_gain_left = this.connected_left * this.gain_hidden * this.volume_both * this.volume_left; + var net_gain_right = this.connected_right * this.gain_hidden * this.volume_both * this.volume_right; + + this.node_gain_left.gain.setValueAtTime(net_gain_left, this.audio_context.currentTime); + this.node_gain_right.gain.setValueAtTime(net_gain_right, this.audio_context.currentTime); +}; + +/** @param {number=} channel */ +SpeakerMixerSource.prototype.connect = function(channel) +{ + var both = !channel || channel === MIXER_CHANNEL_BOTH; + if(both || channel === MIXER_CHANNEL_LEFT) + { + this.connected_left = true; + } + if(both || channel === MIXER_CHANNEL_RIGHT) + { + this.connected_right = true; + } + this.update(); +}; + +/** @param {number=} channel */ +SpeakerMixerSource.prototype.disconnect = function(channel) +{ + var both = !channel || channel === MIXER_CHANNEL_BOTH; + if(both || channel === MIXER_CHANNEL_LEFT) + { + this.connected_left = false; + } + if(both || channel === MIXER_CHANNEL_RIGHT) + { + this.connected_right = false; + } + this.update(); +}; + +/** + * @param {number} value + * @param {number=} channel + */ +SpeakerMixerSource.prototype.set_volume = function(value, channel) +{ + if(channel === undefined) + { + channel = MIXER_CHANNEL_BOTH; + } + + switch(channel) + { + case MIXER_CHANNEL_LEFT: + this.volume_left = value; + break; + case MIXER_CHANNEL_RIGHT: + this.volume_right = value; + break; + case MIXER_CHANNEL_BOTH: + this.volume_both = value; + break; + default: + dbg_assert(false, "Mixer set volume - unknown channel: " + channel); + return; + } + + this.update(); +}; + +SpeakerMixerSource.prototype.set_gain_hidden = function(value) +{ + this.gain_hidden = value; +}; + +/** + * @constructor + * @param {!BusConnector} bus + * @param {!AudioContext} audio_context + * @param {!SpeakerMixer} mixer + */ +function PCSpeaker(bus, audio_context, mixer) +{ + // Nodes + + this.node_oscillator = audio_context.createOscillator(); + this.node_oscillator.type = "square"; + this.node_oscillator.frequency.setValueAtTime(440, audio_context.currentTime); + + // Interface + + this.mixer_connection = mixer.add_source(this.node_oscillator, MIXER_SRC_PCSPEAKER); + this.mixer_connection.disconnect(); + + bus.register("pcspeaker-enable", function() + { + mixer.connect_source(MIXER_SRC_PCSPEAKER); + }, this); + + bus.register("pcspeaker-disable", function() + { + mixer.disconnect_source(MIXER_SRC_PCSPEAKER); + }, this); + + bus.register("pcspeaker-update", function(data) + { + var counter_mode = data[0]; + var counter_reload = data[1]; + + var frequency = 0; + var beep_enabled = counter_mode === 3; + + if(beep_enabled) + { + frequency = OSCILLATOR_FREQ * 1000 / counter_reload; + frequency = Math.min(frequency, this.node_oscillator.frequency.maxValue); + frequency = Math.max(frequency, 0); + } + + this.node_oscillator.frequency.setValueAtTime(frequency, audio_context.currentTime); + }, this); +} + +PCSpeaker.prototype.start = function() +{ + this.node_oscillator.start(); +}; + +/** + * @constructor + * @param {!BusConnector} bus + * @param {!AudioContext} audio_context + * @param {!SpeakerMixer} mixer + */ +function SpeakerWorkletDAC(bus, audio_context, mixer) +{ + /** @const */ + this.bus = bus; + + /** @const */ + this.audio_context = audio_context; + + // State + + this.enabled = false; + this.sampling_rate = 48000; + + // Worklet + + function worklet() + { + /** @const */ + var RENDER_QUANTUM = 128; + + /** @const */ + var MINIMUM_BUFFER_SIZE = 2 * RENDER_QUANTUM; + + /** @const */ + var QUEUE_RESERVE = 1024; + + function sinc(x) + { + if(x === 0) return 1; + x *= Math.PI; + return Math.sin(x) / x; + } + + var EMPTY_BUFFER = + [ + new Float32Array(MINIMUM_BUFFER_SIZE), + new Float32Array(MINIMUM_BUFFER_SIZE), + ]; + + /** + * @constructor + * @extends AudioWorkletProcessor + */ + function DACProcessor() + { + var self = Reflect.construct(AudioWorkletProcessor, [], DACProcessor); + + // Params + + self.kernel_size = 3; + + // States + + // Buffers waiting for their turn to be consumed + self.queue_data = new Array(1024); + self.queue_start = 0; + self.queue_end = 0; + self.queue_length = 0; + self.queue_size = self.queue_data.length; + self.queued_samples = 0; + + // Buffers being actively consumed + /** @type{Array} */ + self.source_buffer_previous = EMPTY_BUFFER; + /** @type{Array} */ + self.source_buffer_current = EMPTY_BUFFER; + + // Ratio of alienland sample rate to homeland sample rate. + self.source_samples_per_destination = 1.0; + + // Integer representing the position of the first destination sample + // for the current block, relative to source_buffer_current. + self.source_block_start = 0; + + // Real number representing the position of the current destination + // sample relative to source_buffer_current, since source_block_start. + self.source_time = 0.0; + + // Same as source_time but rounded down to an index. + self.source_offset = 0; + + // Interface + + self.port.onmessage = (event) => + { + switch(event.data.type) + { + case "queue": + self.queue_push(event.data.value); + break; + case "sampling-rate": + self.source_samples_per_destination = event.data.value / sampleRate; + break; + } + }; + + return self; + } + + Reflect.setPrototypeOf(DACProcessor.prototype, AudioWorkletProcessor.prototype); + Reflect.setPrototypeOf(DACProcessor, AudioWorkletProcessor); + + DACProcessor.prototype["process"] = + DACProcessor.prototype.process = function(inputs, outputs, parameters) + { + for(var i = 0; i < outputs[0][0].length; i++) + { + // Lanczos resampling + var sum0 = 0; + var sum1 = 0; + + var start = this.source_offset - this.kernel_size + 1; + var end = this.source_offset + this.kernel_size; + + for(var j = start; j <= end; j++) + { + var convolute_index = this.source_block_start + j; + sum0 += this.get_sample(convolute_index, 0) * this.kernel(this.source_time - j); + sum1 += this.get_sample(convolute_index, 1) * this.kernel(this.source_time - j); + } + + if(isNaN(sum0) || isNaN(sum1)) + { + // NaN values cause entire audio graph to cease functioning. + sum0 = sum1 = 0; + this.dbg_log("ERROR: NaN values! Ignoring for now."); + } + + outputs[0][0][i] = sum0; + outputs[0][1][i] = sum1; + + this.source_time += this.source_samples_per_destination; + this.source_offset = Math.floor(this.source_time); + } + + // +2 to safeguard against rounding variations + var samples_needed_per_block = this.source_offset; + samples_needed_per_block += this.kernel_size + 2; + + this.source_time -= this.source_offset; + this.source_block_start += this.source_offset; + this.source_offset = 0; + + // Note: This needs to be done after source_block_start is updated. + this.ensure_enough_data(samples_needed_per_block); + + return true; + }; + + DACProcessor.prototype.kernel = function(x) + { + return sinc(x) * sinc(x / this.kernel_size); + }; + + DACProcessor.prototype.get_sample = function(index, channel) + { + if(index < 0) + { + // -ve index represents previous buffer + // <-------| + // [Previous buffer][Current buffer] + index += this.source_buffer_previous[0].length; + return this.source_buffer_previous[channel][index]; + } + else + { + return this.source_buffer_current[channel][index]; + } + }; + + DACProcessor.prototype.ensure_enough_data = function(needed) + { + var current_length = this.source_buffer_current[0].length; + var remaining = current_length - this.source_block_start; + + if(remaining < needed) + { + this.prepare_next_buffer(); + this.source_block_start -= current_length; + } + }; + + DACProcessor.prototype.prepare_next_buffer = function() + { + if(this.queued_samples < MINIMUM_BUFFER_SIZE && this.queue_length) + { + this.dbg_log("Not enough samples - should not happen during midway of playback"); + } + + this.source_buffer_previous = this.source_buffer_current; + this.source_buffer_current = this.queue_shift(); + + var sample_count = this.source_buffer_current[0].length; + + if(sample_count < MINIMUM_BUFFER_SIZE) + { + // Unfortunately, this single buffer is too small :( + + var queue_pos = this.queue_start; + var buffer_count = 0; + + // Figure out how many small buffers to combine. + while(sample_count < MINIMUM_BUFFER_SIZE && buffer_count < this.queue_length) + { + sample_count += this.queue_data[queue_pos][0].length; + + queue_pos = queue_pos + 1 & this.queue_size - 1; + buffer_count++; + } + + // Note: if not enough buffers, this will be end-padded with zeros: + var new_big_buffer_size = Math.max(sample_count, MINIMUM_BUFFER_SIZE); + var new_big_buffer = + [ + new Float32Array(new_big_buffer_size), + new Float32Array(new_big_buffer_size), + ]; + + // Copy the first, already-shifted, small buffer into the new buffer. + new_big_buffer[0].set(this.source_buffer_current[0]); + new_big_buffer[1].set(this.source_buffer_current[1]); + var new_big_buffer_pos = this.source_buffer_current[0].length; + + // Copy the rest. + for(var i = 0; i < buffer_count; i++) + { + var small_buffer = this.queue_shift(); + new_big_buffer[0].set(small_buffer[0], new_big_buffer_pos); + new_big_buffer[1].set(small_buffer[1], new_big_buffer_pos); + new_big_buffer_pos += small_buffer[0].length; + } + + // Pretend that everything's just fine. + this.source_buffer_current = new_big_buffer; + } + + this.pump(); + }; + + DACProcessor.prototype.pump = function() + { + if(this.queued_samples / this.source_samples_per_destination < QUEUE_RESERVE) + { + this.port.postMessage( + { + type: "pump", + }); + } + }; + + DACProcessor.prototype.queue_push = function(item) + { + if(this.queue_length < this.queue_size) + { + this.queue_data[this.queue_end] = item; + this.queue_end = this.queue_end + 1 & this.queue_size - 1; + this.queue_length++; + + this.queued_samples += item[0].length; + + this.pump(); + } + }; + + DACProcessor.prototype.queue_shift = function() + { + if(!this.queue_length) + { + return EMPTY_BUFFER; + } + + var item = this.queue_data[this.queue_start]; + + this.queue_data[this.queue_start] = null; + this.queue_start = this.queue_start + 1 & this.queue_size - 1; + this.queue_length--; + + this.queued_samples -= item[0].length; + + return item; + }; + + DACProcessor.prototype.dbg_log = function(message) + { + if(DEBUG) + { + this.port.postMessage( + { + type: "debug-log", + value: message, + }); + } + }; + + registerProcessor("dac-processor", DACProcessor); + } + + var worklet_string = worklet.toString(); + + var worklet_code_start = worklet_string.indexOf("{") + 1; + var worklet_code_end = worklet_string.lastIndexOf("}"); + var worklet_code = worklet_string.substring(worklet_code_start, worklet_code_end); + + if(DEBUG) + { + worklet_code = "var DEBUG = true;\n" + worklet_code; + } + + var worklet_blob = new Blob([worklet_code], { type: "application/javascript" }); + var worklet_url = URL.createObjectURL(worklet_blob); + + /** @type {AudioWorkletNode} */ + this.node_processor = null; + + // Placeholder pass-through node to connect to, when worklet node is not ready yet. + this.node_output = this.audio_context.createGain(); + + this.audio_context + .audioWorklet + .addModule(worklet_url) + .then(() => + { + URL.revokeObjectURL(worklet_url); + + this.node_processor = new AudioWorkletNode(this.audio_context, "dac-processor", + { + numberOfInputs: 0, + numberOfOutputs: 1, + outputChannelCount: [2], + parameterData: {}, + processorOptions: {}, + }); + + this.node_processor.port.postMessage( + { + type: "sampling-rate", + value: this.sampling_rate, + }); + + this.node_processor.port.onmessage = (event) => + { + switch(event.data.type) + { + case "pump": + this.pump(); + break; + case "debug-log": + dbg_log("SpeakerWorkletDAC - Worklet: " + event.data.value); + break; + } + }; + + // Graph + + this.node_processor.connect(this.node_output); + }); + + // Interface + + this.mixer_connection = mixer.add_source(this.node_output, MIXER_SRC_DAC); + this.mixer_connection.set_gain_hidden(3); + + bus.register("dac-send-data", function(data) + { + this.queue(data); + }, this); + + bus.register("dac-enable", function(enabled) + { + this.enabled = true; + }, this); + + bus.register("dac-disable", function() + { + this.enabled = false; + }, this); + + bus.register("dac-tell-sampling-rate", function(/** number */ rate) + { + dbg_assert(rate > 0, "Sampling rate should be nonzero"); + this.sampling_rate = rate; + + if(!this.node_processor) + { + return; + } + + this.node_processor.port.postMessage( + { + type: "sampling-rate", + value: rate, + }); + }, this); + + if(DEBUG) + { + this.debugger = new SpeakerDACDebugger(this.audio_context, this.node_output); + } +} + +SpeakerWorkletDAC.prototype.queue = function(data) +{ + if(!this.node_processor) + { + return; + } + + if(DEBUG) + { + this.debugger.push_queued_data(data); + } + + this.node_processor.port.postMessage( + { + type: "queue", + value: data, + }, [data[0].buffer, data[1].buffer]); +}; + +SpeakerWorkletDAC.prototype.pump = function() +{ + if(!this.enabled) + { + return; + } + this.bus.send("dac-request-data"); +}; + +/** + * @constructor + * @param {!BusConnector} bus + * @param {!AudioContext} audio_context + * @param {!SpeakerMixer} mixer + */ +function SpeakerBufferSourceDAC(bus, audio_context, mixer) +{ + /** @const */ + this.bus = bus; + + /** @const */ + this.audio_context = audio_context; + + // States + + this.enabled = false; + this.sampling_rate = 22050; + this.buffered_time = 0; + this.rate_ratio = 1; + + // Nodes + + this.node_lowpass = this.audio_context.createBiquadFilter(); + this.node_lowpass.type = "lowpass"; + + // Interface + + this.node_output = this.node_lowpass; + + this.mixer_connection = mixer.add_source(this.node_output, MIXER_SRC_DAC); + this.mixer_connection.set_gain_hidden(3); + + bus.register("dac-send-data", function(data) + { + this.queue(data); + }, this); + + bus.register("dac-enable", function(enabled) + { + this.enabled = true; + this.pump(); + }, this); + + bus.register("dac-disable", function() + { + this.enabled = false; + }, this); + + bus.register("dac-tell-sampling-rate", function(/** number */ rate) + { + dbg_assert(rate > 0, "Sampling rate should be nonzero"); + this.sampling_rate = rate; + this.rate_ratio = Math.ceil(AUDIOBUFFER_MINIMUM_SAMPLING_RATE / rate); + this.node_lowpass.frequency.setValueAtTime(rate / 2, this.audio_context.currentTime); + }, this); + + if(DEBUG) + { + this.debugger = new SpeakerDACDebugger(this.audio_context, this.node_output); + } +} + +SpeakerBufferSourceDAC.prototype.queue = function(data) +{ + if(DEBUG) + { + this.debugger.push_queued_data(data); + } + + var sample_count = data[0].length; + var block_duration = sample_count / this.sampling_rate; + + var buffer; + if(this.rate_ratio > 1) + { + var new_sample_count = sample_count * this.rate_ratio; + var new_sampling_rate = this.sampling_rate * this.rate_ratio; + buffer = this.audio_context.createBuffer(2, new_sample_count, new_sampling_rate); + var buffer_data0 = buffer.getChannelData(0); + var buffer_data1 = buffer.getChannelData(1); + + var buffer_index = 0; + for(var i = 0; i < sample_count; i++) + { + for(var j = 0; j < this.rate_ratio; j++, buffer_index++) + { + buffer_data0[buffer_index] = data[0][i]; + buffer_data1[buffer_index] = data[1][i]; + } + } + } + else + { + // Allocating new AudioBuffer every block + // - Memory profiles show insignificant improvements if recycling old buffers. + buffer = this.audio_context.createBuffer(2, sample_count, this.sampling_rate); + if(buffer.copyToChannel) + { + buffer.copyToChannel(data[0], 0); + buffer.copyToChannel(data[1], 1); + } + else + { + // Safari doesn't support copyToChannel yet. See #286 + buffer.getChannelData(0).set(data[0]); + buffer.getChannelData(1).set(data[1]); + } + } + + var source = this.audio_context.createBufferSource(); + source.buffer = buffer; + source.connect(this.node_lowpass); + source.addEventListener("ended", this.pump.bind(this)); + + var current_time = this.audio_context.currentTime; + + if(this.buffered_time < current_time) + { + dbg_log("Speaker DAC - Creating/Recreating reserve - shouldn't occur frequently during playback"); + + // Schedule pump() to queue evenly, starting from current time + this.buffered_time = current_time; + var target_silence_duration = DAC_QUEUE_RESERVE - block_duration; + var current_silence_duration = 0; + while(current_silence_duration <= target_silence_duration) + { + current_silence_duration += block_duration; + this.buffered_time += block_duration; + setTimeout(() => this.pump(), current_silence_duration * 1000); + } + } + + source.start(this.buffered_time); + this.buffered_time += block_duration; + + // Chase the schedule - ensure reserve is full + setTimeout(() => this.pump(), 0); +}; + +SpeakerBufferSourceDAC.prototype.pump = function() +{ + if(!this.enabled) + { + return; + } + if(this.buffered_time - this.audio_context.currentTime > DAC_QUEUE_RESERVE) + { + return; + } + this.bus.send("dac-request-data"); +}; + +/** + * @constructor + */ +function SpeakerDACDebugger(audio_context, source_node) +{ + /** @const */ + this.audio_context = audio_context; + + /** @const */ + this.node_source = source_node; + + this.node_processor = null; + + this.node_gain = this.audio_context.createGain(); + this.node_gain.gain.setValueAtTime(0, this.audio_context.currentTime); + + this.node_gain.connect(this.audio_context.destination); + + this.is_active = false; + this.queued_history = []; + this.output_history = []; + this.queued = [[], []]; + this.output = [[], []]; +} + +/** @suppress {deprecated} */ +SpeakerDACDebugger.prototype.start = function(duration_ms) +{ + this.is_active = true; + this.queued = [[], []]; + this.output = [[], []]; + this.queued_history.push(this.queued); + this.output_history.push(this.output); + + this.node_processor = this.audio_context.createScriptProcessor(1024, 2, 2); + this.node_processor.onaudioprocess = (event) => + { + this.output[0].push(event.inputBuffer.getChannelData(0).slice()); + this.output[1].push(event.inputBuffer.getChannelData(1).slice()); + }; + + this.node_source.connect(this.node_processor); + this.node_processor.connect(this.node_gain); + + setTimeout(() => + { + this.stop(); + }, duration_ms); +}; + +SpeakerDACDebugger.prototype.stop = function() +{ + this.is_active = false; + this.node_source.disconnect(this.node_processor); + this.node_processor.disconnect(); + this.node_processor = null; +}; + +SpeakerDACDebugger.prototype.push_queued_data = function(data) +{ + if(this.is_active) + { + this.queued[0].push(data[0].slice()); + this.queued[1].push(data[1].slice()); + } +}; + +// Useful for Audacity imports +SpeakerDACDebugger.prototype.download_txt = function(history_id, channel) +{ + var txt = this.output_history[history_id][channel] + .map((v) => v.join(" ")) + .join(" "); + + dump_file(txt, "dacdata.txt"); +}; + +// Useful for general plotting +SpeakerDACDebugger.prototype.download_csv = function(history_id) +{ + var buffers = this.output_history[history_id]; + var csv_rows = []; + for(var buffer_id = 0; buffer_id < buffers[0].length; buffer_id++) + { + for(var i = 0; i < buffers[0][buffer_id].length; i++) + { + csv_rows.push(`${buffers[0][buffer_id][i]},${buffers[1][buffer_id][i]}`); + } + } + dump_file(csv_rows.join("\n"), "dacdata.csv"); +}; diff --git a/src/browser/starter.js b/src/browser/starter.js new file mode 100644 index 0000000..70d9496 --- /dev/null +++ b/src/browser/starter.js @@ -0,0 +1,1353 @@ +"use strict"; + +/** + * Constructor for emulator instances. + * + * Usage: `var emulator = new V86Starter(options);` + * + * Options can have the following properties (all optional, default in parenthesis): + * + * - `memory_size number` (16 * 1024 * 1024) - The memory size in bytes, should + * be a power of 2. + * - `vga_memory_size number` (8 * 1024 * 1024) - VGA memory size in bytes. + * + * - `autostart boolean` (false) - If emulation should be started when emulator + * is ready. + * + * - `disable_keyboard boolean` (false) - If the keyboard should be disabled. + * - `disable_mouse boolean` (false) - If the mouse should be disabled. + * + * - `network_relay_url string` (No network card) - The url of a server running + * websockproxy. See [networking.md](networking.md). Setting this will + * enable an emulated network card. + * + * - `bios Object` (No bios) - Either a url pointing to a bios or an + * ArrayBuffer, see below. + * - `vga_bios Object` (No VGA bios) - VGA bios, see below. + * - `hda Object` (No hard drive) - First hard disk, see below. + * - `fda Object` (No floppy disk) - First floppy disk, see below. + * - `cdrom Object` (No CD) - See below. + * + * - `bzimage Object` - A Linux kernel image to boot (only bzimage format), see below. + * - `initrd Object` - A Linux ramdisk image, see below. + * - `bzimage_initrd_from_filesystem boolean` - Automatically fetch bzimage and + * initrd from the specified `filesystem`. + * + * - `initial_state Object` (Normal boot) - An initial state to load, see + * [`restore_state`](#restore_statearraybuffer-state) and below. + * + * - `filesystem Object` (No 9p filesystem) - A 9p filesystem, see + * [filesystem.md](filesystem.md). + * + * - `serial_container HTMLTextAreaElement` (No serial terminal) - A textarea + * that will receive and send data to the emulated serial terminal. + * Alternatively the serial terminal can also be accessed programatically, + * see [serial.html](../examples/serial.html). + * + * - `screen_container HTMLElement` (No screen) - An HTMLElement. This should + * have a certain structure, see [basic.html](../examples/basic.html). + * + * *** + * + * There are two ways to load images (`bios`, `vga_bios`, `cdrom`, `hda`, ...): + * + * - Pass an object that has a url. Optionally, `async: true` and `size: + * size_in_bytes` can be added to the object, so that sectors of the image + * are loaded on demand instead of being loaded before boot (slower, but + * strongly recommended for big files). In that case, the `Range: bytes=...` + * header must be supported on the server. + * + * ```javascript + * // download file before boot + * bios: { + * url: "bios/seabios.bin" + * } + * // download file sectors as requested, size is required + * hda: { + * url: "disk/linux.iso", + * async: true, + * size: 16 * 1024 * 1024 + * } + * ``` + * + * - Pass an `ArrayBuffer` or `File` object as `buffer` property. + * + * ```javascript + * // use + * bios: { + * buffer: document.all.hd_image.files[0] + * } + * // start with empty hard drive + * hda: { + * buffer: new ArrayBuffer(16 * 1024 * 1024) + * } + * ``` + * + * *** + * + * @param {Object} options Options to initialize the emulator with. + * @constructor + */ +function V86Starter(options) +{ + //var worker = new Worker("src/browser/worker.js"); + //var adapter_bus = this.bus = WorkerBus.init(worker); + + this.cpu_is_running = false; + + const bus = Bus.create(); + const adapter_bus = this.bus = bus[0]; + this.emulator_bus = bus[1]; + + var cpu; + var wasm_memory; + + const wasm_table = new WebAssembly.Table({ element: "anyfunc", "initial": WASM_TABLE_SIZE + WASM_TABLE_OFFSET }); + + const wasm_shared_funcs = { + "cpu_exception_hook": (n) => { + return this["cpu_exception_hook"] && this["cpu_exception_hook"](n); + }, + "hlt_op": function() { return cpu.hlt_op(); }, + "abort": function() { dbg_assert(false); }, + "microtick": v86.microtick, + "get_rand_int": function() { return v86util.get_rand_int(); }, + + "pic_acknowledge": function() { cpu.pic_acknowledge(); }, + + "io_port_read8": function(addr) { return cpu.io.port_read8(addr); }, + "io_port_read16": function(addr) { return cpu.io.port_read16(addr); }, + "io_port_read32": function(addr) { return cpu.io.port_read32(addr); }, + "io_port_write8": function(addr, value) { cpu.io.port_write8(addr, value); }, + "io_port_write16": function(addr, value) { cpu.io.port_write16(addr, value); }, + "io_port_write32": function(addr, value) { cpu.io.port_write32(addr, value); }, + + "mmap_read8": function(addr) { return cpu.mmap_read8(addr); }, + "mmap_read16": function(addr) { return cpu.mmap_read16(addr); }, + "mmap_read32": function(addr) { return cpu.mmap_read32(addr); }, + "mmap_write8": function(addr, value) { cpu.mmap_write8(addr, value); }, + "mmap_write16": function(addr, value) { cpu.mmap_write16(addr, value); }, + "mmap_write32": function(addr, value) { cpu.mmap_write32(addr, value); }, + "mmap_write64": function(addr, value0, value1) { cpu.mmap_write64(addr, value0, value1); }, + "mmap_write128": function(addr, value0, value1, value2, value3) { + cpu.mmap_write128(addr, value0, value1, value2, value3); + }, + + "log_from_wasm": function(offset, len) { + const str = v86util.read_sized_string_from_mem(wasm_memory, offset, len); + dbg_log(str, LOG_CPU); + }, + "console_log_from_wasm": function(offset, len) { + const str = v86util.read_sized_string_from_mem(wasm_memory, offset, len); + console.error(str); + }, + "dbg_trace_from_wasm": function() { + dbg_trace(LOG_CPU); + }, + + "codegen_finalize": (wasm_table_index, start, state_flags, ptr, len) => { + cpu.codegen_finalize(wasm_table_index, start, state_flags, ptr, len); + }, + "jit_clear_func": (wasm_table_index) => cpu.jit_clear_func(wasm_table_index), + "jit_clear_all_funcs": () => cpu.jit_clear_all_funcs(), + + "__indirect_function_table": wasm_table, + }; + + let wasm_fn = options["wasm_fn"]; + + if(!wasm_fn) + { + wasm_fn = env => + { + return new Promise(resolve => { + let v86_bin = DEBUG ? "v86-debug.wasm" : "v86.wasm"; + let v86_bin_fallback = "v86-fallback.wasm"; + + if(options["wasm_path"]) + { + v86_bin = options["wasm_path"]; + const slash = v86_bin.lastIndexOf("/"); + const dir = slash === -1 ? "" : v86_bin.substr(0, slash); + v86_bin_fallback = dir + "/" + v86_bin_fallback; + } + else if(typeof window === "undefined" && typeof __dirname === "string") + { + v86_bin = __dirname + "/" + v86_bin; + v86_bin_fallback = __dirname + "/" + v86_bin_fallback; + } + else + { + v86_bin = "build/" + v86_bin; + v86_bin_fallback = "build/" + v86_bin_fallback; + } + + v86util.load_file(v86_bin, { + done: async bytes => + { + try + { + const { instance } = await WebAssembly.instantiate(bytes, env); + resolve(instance.exports); + } + catch(err) + { + v86util.load_file(v86_bin_fallback, { + done: async bytes => { + const { instance } = await WebAssembly.instantiate(bytes, env); + resolve(instance.exports); + }, + }); + } + }, + progress: e => + { + this.emulator_bus.send("download-progress", { + file_index: 0, + file_count: 1, + file_name: v86_bin, + + lengthComputable: e.lengthComputable, + total: e.total, + loaded: e.loaded, + }); + } + }); + }); + }; + } + + wasm_fn({ "env": wasm_shared_funcs }) + .then((exports) => { + wasm_memory = exports.memory; + exports["rust_init"](); + + const emulator = this.v86 = new v86(this.emulator_bus, { exports, wasm_table }); + cpu = emulator.cpu; + + this.continue_init(emulator, options); + }); +} + +V86Starter.prototype.continue_init = async function(emulator, options) +{ + this.bus.register("emulator-stopped", function() + { + this.cpu_is_running = false; + }, this); + + this.bus.register("emulator-started", function() + { + this.cpu_is_running = true; + }, this); + + var settings = {}; + + this.disk_images = { + "fda": undefined, + "fdb": undefined, + "hda": undefined, + "hdb": undefined, + "cdrom": undefined, + }; + + settings.acpi = options["acpi"]; + settings.load_devices = true; + settings.log_level = options["log_level"]; + settings.memory_size = options["memory_size"] || 64 * 1024 * 1024; + settings.vga_memory_size = options["vga_memory_size"] || 8 * 1024 * 1024; + settings.boot_order = options["boot_order"] || 0x213; + settings.fastboot = options["fastboot"] || false; + settings.fda = undefined; + settings.fdb = undefined; + settings.uart1 = options["uart1"]; + settings.uart2 = options["uart2"]; + settings.uart3 = options["uart3"]; + settings.cmdline = options["cmdline"]; + settings.preserve_mac_from_state_image = options["preserve_mac_from_state_image"]; + settings.mac_address_translation = options["mac_address_translation"]; + settings.cpuid_level = options["cpuid_level"]; + + if(options["network_adapter"]) + { + this.network_adapter = options["network_adapter"](this.bus); + } + else if(options["network_relay_url"]) + { + this.network_adapter = new NetworkAdapter(options["network_relay_url"], this.bus); + } + + // Enable unconditionally, so that state images don't miss hardware + // TODO: Should be properly fixed in restore_state + settings.enable_ne2k = true; + + if(!options["disable_keyboard"]) + { + this.keyboard_adapter = new KeyboardAdapter(this.bus); + } + if(!options["disable_mouse"]) + { + this.mouse_adapter = new MouseAdapter(this.bus, options["screen_container"]); + } + + if(options["screen_container"]) + { + this.screen_adapter = new ScreenAdapter(options["screen_container"], this.bus); + } + else if(options["screen_dummy"]) + { + this.screen_adapter = new DummyScreenAdapter(this.bus); + } + + if(options["serial_container"]) + { + this.serial_adapter = new SerialAdapter(options["serial_container"], this.bus); + //this.recording_adapter = new SerialRecordingAdapter(this.bus); + } + + if(options["serial_container_xtermjs"]) + { + this.serial_adapter = new SerialAdapterXtermJS(options["serial_container_xtermjs"], this.bus); + } + + if(!options["disable_speaker"]) + { + this.speaker_adapter = new SpeakerAdapter(this.bus); + } + + // ugly, but required for closure compiler compilation + function put_on_settings(name, buffer) + { + switch(name) + { + case "hda": + settings.hda = this.disk_images["hda"] = buffer; + break; + case "hdb": + settings.hdb = this.disk_images["hdb"] = buffer; + break; + case "cdrom": + settings.cdrom = this.disk_images["cdrom"] = buffer; + break; + case "fda": + settings.fda = this.disk_images["fda"] = buffer; + break; + case "fdb": + settings.fdb = this.disk_images["fdb"] = buffer; + break; + + case "multiboot": + settings.multiboot = this.disk_images["multiboot"] = buffer.buffer; + break; + case "bzimage": + settings.bzimage = this.disk_images["bzimage"] = buffer.buffer; + break; + case "initrd": + settings.initrd = this.disk_images["initrd"] = buffer.buffer; + break; + + case "bios": + settings.bios = buffer.buffer; + break; + case "vga_bios": + settings.vga_bios = buffer.buffer; + break; + case "initial_state": + settings.initial_state = buffer.buffer; + break; + case "fs9p_json": + settings.fs9p_json = buffer; + break; + default: + dbg_assert(false, name); + } + } + + var files_to_load = []; + + function add_file(name, file) + { + if(!file) + { + return; + } + + if(file.get && file.set && file.load) + { + files_to_load.push({ + name: name, + loadable: file, + }); + return; + } + + if(name === "bios" || name === "vga_bios" || + name === "initial_state" || name === "multiboot" || + name === "bzimage" || name === "initrd") + { + // Ignore async for these because they must be available before boot. + // This should make result.buffer available after the object is loaded + file.async = false; + } + + if(file.buffer instanceof ArrayBuffer) + { + var buffer = new v86util.SyncBuffer(file.buffer); + files_to_load.push({ + name: name, + loadable: buffer, + }); + } + else if(typeof File !== "undefined" && file.buffer instanceof File) + { + // SyncFileBuffer: + // - loads the whole disk image into memory, impossible for large files (more than 1GB) + // - can later serve get/set operations fast and synchronously + // - takes some time for first load, neglectable for small files (up to 100Mb) + // + // AsyncFileBuffer: + // - loads slices of the file asynchronously as requested + // - slower get/set + + // Heuristics: If file is larger than or equal to 256M, use AsyncFileBuffer + if(file.async === undefined) + { + file.async = file.buffer.size >= 256 * 1024 * 1024; + } + + if(file.async) + { + var buffer = new v86util.AsyncFileBuffer(file.buffer); + } + else + { + var buffer = new v86util.SyncFileBuffer(file.buffer); + } + + files_to_load.push({ + name: name, + loadable: buffer, + }); + } + else if(file.url) + { + if(file.async) + { + let buffer; + + if(file.use_parts) + { + buffer = new v86util.AsyncXHRPartfileBuffer(file.url, file.size, file.fixed_chunk_size); + } + else + { + buffer = new v86util.AsyncXHRBuffer(file.url, file.size, file.fixed_chunk_size); + } + + files_to_load.push({ + name: name, + loadable: buffer, + }); + } + else + { + files_to_load.push({ + name: name, + url: file.url, + size: file.size, + }); + } + } + else + { + dbg_log("Ignored file: url=" + file.url + " buffer=" + file.buffer); + } + } + + if(options["state"]) + { + console.warn("Warning: Unknown option 'state'. Did you mean 'initial_state'?"); + } + + var image_names = [ + "bios", "vga_bios", + "cdrom", "hda", "hdb", "fda", "fdb", + "initial_state", "multiboot", + "bzimage", "initrd", + ]; + + for(var i = 0; i < image_names.length; i++) + { + add_file(image_names[i], options[image_names[i]]); + } + + if(options["filesystem"]) + { + var fs_url = options["filesystem"].basefs; + var base_url = options["filesystem"].baseurl; + + let file_storage = new MemoryFileStorage(); + + if(base_url) + { + file_storage = new ServerFileStorageWrapper(file_storage, base_url); + } + settings.fs9p = this.fs9p = new FS(file_storage); + + if(fs_url) + { + dbg_assert(base_url, "Filesystem: baseurl must be specified"); + + var size; + + if(typeof fs_url === "object") + { + size = fs_url.size; + fs_url = fs_url.url; + } + dbg_assert(typeof fs_url === "string"); + + files_to_load.push({ + name: "fs9p_json", + url: fs_url, + size: size, + as_json: true, + }); + } + } + + var starter = this; + var total = files_to_load.length; + + var cont = function(index) + { + if(index === total) + { + setTimeout(done.bind(this), 0); + return; + } + + var f = files_to_load[index]; + + if(f.loadable) + { + f.loadable.onload = function(e) + { + put_on_settings.call(this, f.name, f.loadable); + cont(index + 1); + }.bind(this); + f.loadable.load(); + } + else + { + v86util.load_file(f.url, { + done: function(result) + { + put_on_settings.call(this, f.name, f.as_json ? result : new v86util.SyncBuffer(result)); + cont(index + 1); + }.bind(this), + progress: function progress(e) + { + if(e.target.status === 200) + { + starter.emulator_bus.send("download-progress", { + file_index: index, + file_count: total, + file_name: f.url, + + lengthComputable: e.lengthComputable, + total: e.total || f.size, + loaded: e.loaded, + }); + } + else + { + starter.emulator_bus.send("download-error", { + file_index: index, + file_count: total, + file_name: f.url, + request: e.target, + }); + } + }, + as_json: f.as_json, + }); + } + }.bind(this); + cont(0); + + async function done() + { + //if(settings.initial_state) + //{ + // // avoid large allocation now, memory will be restored later anyway + // settings.memory_size = 0; + //} + + if(settings.fs9p && settings.fs9p_json) + { + if(!settings.initial_state) + { + settings.fs9p.load_from_json(settings.fs9p_json); + } + else + { + dbg_log("Filesystem basefs ignored: Overridden by state image"); + } + + if(options["bzimage_initrd_from_filesystem"]) + { + const { bzimage_path, initrd_path } = this.get_bzimage_initrd_from_filesystem(settings.fs9p); + + dbg_log("Found bzimage: " + bzimage_path + " and initrd: " + initrd_path); + + const [initrd, bzimage] = await Promise.all([ + settings.fs9p.read_file(initrd_path), + settings.fs9p.read_file(bzimage_path), + ]); + put_on_settings.call(this, "initrd", new v86util.SyncBuffer(initrd.buffer)); + put_on_settings.call(this, "bzimage", new v86util.SyncBuffer(bzimage.buffer)); + finish.call(this); + } + else + { + finish.call(this); + } + } + else + { + dbg_assert( + !options["bzimage_initrd_from_filesystem"], + "bzimage_initrd_from_filesystem: Requires a filesystem"); + finish.call(this); + } + + function finish() + { + this.serial_adapter && this.serial_adapter.show && this.serial_adapter.show(); + + this.bus.send("cpu-init", settings); + + if(settings.initial_state) + { + emulator.restore_state(settings.initial_state); + + // The GC can't free settings, since it is referenced from + // several closures. This isn't needed anymore, so we delete it + // here + settings.initial_state = undefined; + } + + if(options["autostart"]) + { + this.bus.send("cpu-run"); + } + + this.emulator_bus.send("emulator-loaded"); + } + } +}; + +V86Starter.prototype.get_bzimage_initrd_from_filesystem = function(filesystem) +{ + const root = (filesystem.read_dir("/") || []).map(x => "/" + x); + const boot = (filesystem.read_dir("/boot/") || []).map(x => "/boot/" + x); + + let initrd_path; + let bzimage_path; + + for(let f of [].concat(root, boot)) + { + const old = /old/i.test(f) || /fallback/i.test(f); + const is_bzimage = /vmlinuz/i.test(f) || /bzimage/i.test(f); + const is_initrd = /initrd/i.test(f) || /initramfs/i.test(f); + + if(is_bzimage && (!bzimage_path || !old)) + { + bzimage_path = f; + } + + if(is_initrd && (!initrd_path || !old)) + { + initrd_path = f; + } + } + + if(!initrd_path || !bzimage_path) + { + console.log("Failed to find bzimage or initrd in filesystem. Files:"); + console.log(root.join(" ")); + console.log(boot.join(" ")); + } + + return { initrd_path, bzimage_path }; +}; + +/** + * Start emulation. Do nothing if emulator is running already. Can be + * asynchronous. + * @export + */ +V86Starter.prototype.run = async function() +{ + this.bus.send("cpu-run"); +}; + +/** + * Stop emulation. Do nothing if emulator is not running. Can be asynchronous. + * @export + */ +V86Starter.prototype.stop = async function() +{ + if(!this.cpu_is_running) + { + return; + } + + await new Promise(resolve => { + const listener = () => { + this.remove_listener("emulator-stopped", listener); + resolve(); + }; + this.add_listener("emulator-stopped", listener); + this.bus.send("cpu-stop"); + }); +}; + +/** + * @ignore + * @export + */ +V86Starter.prototype.destroy = async function() +{ + await this.stop(); + + this.v86.destroy(); + this.keyboard_adapter && this.keyboard_adapter.destroy(); + this.network_adapter && this.network_adapter.destroy(); + this.mouse_adapter && this.mouse_adapter.destroy(); + this.screen_adapter && this.screen_adapter.destroy(); + this.serial_adapter && this.serial_adapter.destroy(); + this.speaker_adapter && this.speaker_adapter.destroy(); +}; + +/** + * Restart (force a reboot). + * @export + */ +V86Starter.prototype.restart = function() +{ + this.bus.send("cpu-restart"); +}; + +/** + * Add an event listener (the emulator is an event emitter). A list of events + * can be found at [events.md](events.md). + * + * The callback function gets a single argument which depends on the event. + * + * @param {string} event Name of the event. + * @param {function(*)} listener The callback function. + * @export + */ +V86Starter.prototype.add_listener = function(event, listener) +{ + this.bus.register(event, listener, this); +}; + +/** + * Remove an event listener. + * + * @param {string} event + * @param {function(*)} listener + * @export + */ +V86Starter.prototype.remove_listener = function(event, listener) +{ + this.bus.unregister(event, listener); +}; + +/** + * Restore the emulator state from the given state, which must be an + * ArrayBuffer returned by + * [`save_state`](#save_statefunctionobject-arraybuffer-callback). + * + * Note that the state can only be restored correctly if this constructor has + * been created with the same options as the original instance (e.g., same disk + * images, memory size, etc.). + * + * Different versions of the emulator might use a different format for the + * state buffer. + * + * @param {ArrayBuffer} state + * @export + */ +V86Starter.prototype.restore_state = async function(state) +{ + dbg_assert(arguments.length === 1); + this.v86.restore_state(state); +}; + +/** + * Asynchronously save the current state of the emulator. + * + * @return {Promise} + * @export + */ +V86Starter.prototype.save_state = async function() +{ + dbg_assert(arguments.length === 0); + return this.v86.save_state(); +}; + +/** + * Return an object with several statistics. Return value looks similar to + * (but can be subject to change in future versions or different + * configurations, so use defensively): + * + * ```javascript + * { + * "cpu": { + * "instruction_counter": 2821610069 + * }, + * "hda": { + * "sectors_read": 95240, + * "sectors_written": 952, + * "bytes_read": 48762880, + * "bytes_written": 487424, + * "loading": false + * }, + * "cdrom": { + * "sectors_read": 0, + * "sectors_written": 0, + * "bytes_read": 0, + * "bytes_written": 0, + * "loading": false + * }, + * "mouse": { + * "enabled": true + * }, + * "vga": { + * "is_graphical": true, + * "res_x": 800, + * "res_y": 600, + * "bpp": 32 + * } + * } + * ``` + * + * @deprecated + * @return {Object} + * @export + */ +V86Starter.prototype.get_statistics = function() +{ + console.warn("V86Starter.prototype.get_statistics is deprecated. Use events instead."); + + var stats = { + cpu: { + instruction_counter: this.get_instruction_counter(), + }, + }; + + if(!this.v86) + { + return stats; + } + + var devices = this.v86.cpu.devices; + + if(devices.hda) + { + stats.hda = devices.hda.stats; + } + + if(devices.cdrom) + { + stats.cdrom = devices.cdrom.stats; + } + + if(devices.ps2) + { + stats["mouse"] = { + "enabled": devices.ps2.use_mouse, + }; + } + + if(devices.vga) + { + stats["vga"] = { + "is_graphical": devices.vga.stats.is_graphical, + }; + } + + return stats; +}; + +/** + * @return {number} + * @ignore + * @export + */ +V86Starter.prototype.get_instruction_counter = function() +{ + if(this.v86) + { + return this.v86.cpu.instruction_counter[0] >>> 0; + } + else + { + // TODO: Should be handled using events + return 0; + } +}; + +/** + * @return {boolean} + * @export + */ +V86Starter.prototype.is_running = function() +{ + return this.cpu_is_running; +}; + +/** + * Send a sequence of scan codes to the emulated PS2 controller. A list of + * codes can be found at http://stanislavs.org/helppc/make_codes.html. + * Do nothing if there is no keyboard controller. + * + * @param {Array.} codes + * @export + */ +V86Starter.prototype.keyboard_send_scancodes = function(codes) +{ + for(var i = 0; i < codes.length; i++) + { + this.bus.send("keyboard-code", codes[i]); + } +}; + +/** + * Send translated keys + * @ignore + * @export + */ +V86Starter.prototype.keyboard_send_keys = function(codes) +{ + for(var i = 0; i < codes.length; i++) + { + this.keyboard_adapter.simulate_press(codes[i]); + } +}; + +/** + * Send text + * @ignore + * @export + */ +V86Starter.prototype.keyboard_send_text = function(string) +{ + for(var i = 0; i < string.length; i++) + { + this.keyboard_adapter.simulate_char(string[i]); + } +}; + +/** + * Download a screenshot. + * + * @ignore + * @export + */ +V86Starter.prototype.screen_make_screenshot = function() +{ + if(this.screen_adapter) + { + this.screen_adapter.make_screenshot(); + } +}; + +/** + * Set the scaling level of the emulated screen. + * + * @param {number} sx + * @param {number} sy + * + * @ignore + * @export + */ +V86Starter.prototype.screen_set_scale = function(sx, sy) +{ + if(this.screen_adapter) + { + this.screen_adapter.set_scale(sx, sy); + } +}; + +/** + * Go fullscreen. + * + * @ignore + * @export + */ +V86Starter.prototype.screen_go_fullscreen = function() +{ + if(!this.screen_adapter) + { + return; + } + + var elem = document.getElementById("screen_container"); + + if(!elem) + { + return; + } + + // bracket notation because otherwise they get renamed by closure compiler + var fn = elem["requestFullScreen"] || + elem["webkitRequestFullscreen"] || + elem["mozRequestFullScreen"] || + elem["msRequestFullScreen"]; + + if(fn) + { + fn.call(elem); + + // This is necessary, because otherwise chromium keyboard doesn't work anymore. + // Might (but doesn't seem to) break something else + var focus_element = document.getElementsByClassName("phone_keyboard")[0]; + focus_element && focus_element.focus(); + } + + try { + navigator.keyboard.lock(); + } catch(e) {} + + this.lock_mouse(); +}; + +/** + * Lock the mouse cursor: It becomes invisble and is not moved out of the + * browser window. + * + * @ignore + * @export + */ +V86Starter.prototype.lock_mouse = function() +{ + var elem = document.body; + + var fn = elem["requestPointerLock"] || + elem["mozRequestPointerLock"] || + elem["webkitRequestPointerLock"]; + + if(fn) + { + fn.call(elem); + } +}; + +/** + * Enable or disable sending mouse events to the emulated PS2 controller. + * + * @param {boolean} enabled + */ +V86Starter.prototype.mouse_set_status = function(enabled) +{ + if(this.mouse_adapter) + { + this.mouse_adapter.emu_enabled = enabled; + } +}; + +/** + * Enable or disable sending keyboard events to the emulated PS2 controller. + * + * @param {boolean} enabled + * @export + */ +V86Starter.prototype.keyboard_set_status = function(enabled) +{ + if(this.keyboard_adapter) + { + this.keyboard_adapter.emu_enabled = enabled; + } +}; + + +/** + * Send a string to the first emulated serial terminal. + * + * @param {string} data + * @export + */ +V86Starter.prototype.serial0_send = function(data) +{ + for(var i = 0; i < data.length; i++) + { + this.bus.send("serial0-input", data.charCodeAt(i)); + } +}; + +/** + * Send bytes to a serial port (to be received by the emulated PC). + * + * @param {Uint8Array} data + * @export + */ +V86Starter.prototype.serial_send_bytes = function(serial, data) +{ + for(var i = 0; i < data.length; i++) + { + this.bus.send("serial" + serial + "-input", data[i]); + } +}; + +/** + * Mount another filesystem to the current filesystem. + * @param {string} path Path for the mount point + * @param {string|undefined} baseurl + * @param {string|undefined} basefs As a JSON string + * @param {function(Object)=} callback + * @export + */ +V86Starter.prototype.mount_fs = async function(path, baseurl, basefs, callback) +{ + let file_storage = new MemoryFileStorage(); + + if(baseurl) + { + file_storage = new ServerFileStorageWrapper(file_storage, baseurl); + } + const newfs = new FS(file_storage, this.fs9p.qidcounter); + const mount = () => + { + const idx = this.fs9p.Mount(path, newfs); + if(!callback) + { + return; + } + if(idx === -ENOENT) + { + callback(new FileNotFoundError()); + } + else if(idx === -EEXIST) + { + callback(new FileExistsError()); + } + else if(idx < 0) + { + dbg_assert(false, "Unexpected error code: " + (-idx)); + callback(new Error("Failed to mount. Error number: " + (-idx))); + } + else + { + callback(null); + } + }; + if(baseurl) + { + dbg_assert(typeof basefs === "object", "Filesystem: basefs must be a JSON object"); + newfs.load_from_json(basefs, () => mount()); + } + else + { + mount(); + } +}; + +/** + * Write to a file in the 9p filesystem. Nothing happens if no filesystem has + * been initialized. + * + * @param {string} file + * @param {Uint8Array} data + * @export + */ +V86Starter.prototype.create_file = async function(file, data) +{ + dbg_assert(arguments.length === 2); + var fs = this.fs9p; + + if(!fs) + { + return; + } + + var parts = file.split("/"); + var filename = parts[parts.length - 1]; + + var path_infos = fs.SearchPath(file); + var parent_id = path_infos.parentid; + var not_found = filename === "" || parent_id === -1; + + if(!not_found) + { + await fs.CreateBinaryFile(filename, parent_id, data); + } + else + { + return Promise.reject(new FileNotFoundError()); + } +}; + +/** + * Read a file in the 9p filesystem. Nothing happens if no filesystem has been + * initialized. + * + * @param {string} file + * @export + */ +V86Starter.prototype.read_file = async function(file) +{ + dbg_assert(arguments.length === 1); + var fs = this.fs9p; + + if(!fs) + { + return; + } + + const result = await fs.read_file(file); + + if(result) + { + return result; + } + else + { + return Promise.reject(new FileNotFoundError()); + } +}; + +V86Starter.prototype.automatically = function(steps) +{ + const run = (steps) => + { + const step = steps[0]; + + if(!step) + { + return; + } + + const remaining_steps = steps.slice(1); + + if(step.sleep) + { + setTimeout(() => run(remaining_steps), step.sleep * 1000); + return; + } + + if(step.vga_text) + { + const screen = this.screen_adapter.get_text_screen(); + + for(let line of screen) + { + if(line.includes(step.vga_text)) + { + run(remaining_steps); + return; + } + } + + setTimeout(() => run(steps), 1000); + return; + } + + if(step.keyboard_send) + { + if(step.keyboard_send instanceof Array) + { + this.keyboard_send_scancodes(step.keyboard_send); + } + else + { + dbg_assert(typeof step.keyboard_send === "string"); + this.keyboard_send_text(step.keyboard_send); + } + + run(remaining_steps); + return; + } + + if(step.call) + { + step.call(); + run(remaining_steps); + return; + } + + dbg_assert(false, step); + }; + + run(steps); + +}; + +/** + * Reads data from memory at specified offset. + * + * @param {number} offset + * @param {number} length + * @returns + */ +V86Starter.prototype.read_memory = function(offset, length) +{ + return this.v86.cpu.read_blob(offset, length); +}; + +/** + * Writes data to memory at specified offset. + * + * @param {Array.|Uint8Array} blob + * @param {number} offset + */ +V86Starter.prototype.write_memory = function(blob, offset) +{ + this.v86.cpu.write_blob(blob, offset); +}; + +/** + * @ignore + * @constructor + * + * @param {string=} message + */ +function FileExistsError(message) +{ + this.message = message || "File already exists"; +} +FileExistsError.prototype = Error.prototype; + +/** + * @ignore + * @constructor + * + * @param {string=} message + */ +function FileNotFoundError(message) +{ + this.message = message || "File not found"; +} +FileNotFoundError.prototype = Error.prototype; + +// Closure Compiler's way of exporting +if(typeof window !== "undefined") +{ + window["V86Starter"] = V86Starter; + window["V86"] = V86Starter; +} +else if(typeof module !== "undefined" && typeof module.exports !== "undefined") +{ + module.exports["V86Starter"] = V86Starter; + module.exports["V86"] = V86Starter; +} +else if(typeof importScripts === "function") +{ + // web worker + self["V86Starter"] = V86Starter; + self["V86"] = V86Starter; +} diff --git a/src/browser/worker_bus.js b/src/browser/worker_bus.js new file mode 100644 index 0000000..8d8636e --- /dev/null +++ b/src/browser/worker_bus.js @@ -0,0 +1,64 @@ +"use strict"; + +var WorkerBus = {}; + +/** @constructor */ +WorkerBus.Connector = function(pair) +{ + this.listeners = {}; + this.pair = pair; + + pair.addEventListener("message", function(e) + { + var data = e.data; + var listeners = this.listeners[data[0]]; + + for(var i = 0; i < listeners.length; i++) + { + var listener = listeners[i]; + listener.fn.call(listener.this_value, data[1]); + } + }.bind(this), false); + +}; + +WorkerBus.Connector.prototype.register = function(name, fn, this_value) +{ + var listeners = this.listeners[name]; + + if(listeners === undefined) + { + listeners = this.listeners[name] = []; + } + + listeners.push({ + fn: fn, + this_value: this_value, + }); +}; + +/** + * Send ("emit") a message + * + * @param {string} name + * @param {*=} value + * @param {*=} transfer_list + */ +WorkerBus.Connector.prototype.send = function(name, value, transfer_list) +{ + dbg_assert(arguments.length >= 1); + + if(!this.pair) + { + return; + } + + this.pair.postMessage([name, value], transfer_list); +}; + + +WorkerBus.init = function(worker) +{ + return new WorkerBus.Connector(worker); +}; + diff --git a/src/buffer.js b/src/buffer.js new file mode 100644 index 0000000..adff5e9 --- /dev/null +++ b/src/buffer.js @@ -0,0 +1,748 @@ +"use strict"; + +(function() +{ + v86util.SyncBuffer = SyncBuffer; + v86util.AsyncXHRBuffer = AsyncXHRBuffer; + v86util.AsyncXHRPartfileBuffer = AsyncXHRPartfileBuffer; + v86util.AsyncFileBuffer = AsyncFileBuffer; + v86util.SyncFileBuffer = SyncFileBuffer; + + // The smallest size the emulated hardware can emit + const BLOCK_SIZE = 256; + + const ASYNC_SAFE = false; + + /** + * Synchronous access to ArrayBuffer + * @constructor + */ + function SyncBuffer(buffer) + { + dbg_assert(buffer instanceof ArrayBuffer); + + this.buffer = buffer; + this.byteLength = buffer.byteLength; + this.onload = undefined; + this.onprogress = undefined; + } + + SyncBuffer.prototype.load = function() + { + this.onload && this.onload({ buffer: this.buffer }); + }; + + /** + * @this {SyncBuffer|SyncFileBuffer} + * @param {number} start + * @param {number} len + * @param {function(!Uint8Array)} fn + */ + SyncBuffer.prototype.get = function(start, len, fn) + { + dbg_assert(start + len <= this.byteLength); + fn(new Uint8Array(this.buffer, start, len)); + }; + + /** + * @this {SyncBuffer|SyncFileBuffer} + * @param {number} start + * @param {!Uint8Array} slice + * @param {function()} fn + */ + SyncBuffer.prototype.set = function(start, slice, fn) + { + dbg_assert(start + slice.byteLength <= this.byteLength); + + new Uint8Array(this.buffer, start, slice.byteLength).set(slice); + fn(); + }; + + /** + * @this {SyncBuffer|SyncFileBuffer} + * @param {function(!ArrayBuffer)} fn + */ + SyncBuffer.prototype.get_buffer = function(fn) + { + fn(this.buffer); + }; + + /** + * @this {SyncBuffer|SyncFileBuffer} + */ + SyncBuffer.prototype.get_state = function() + { + const state = []; + state[0] = this.byteLength; + state[1] = new Uint8Array(this.buffer); + return state; + }; + + /** + * @this {SyncBuffer|SyncFileBuffer} + */ + SyncBuffer.prototype.set_state = function(state) + { + this.byteLength = state[0]; + this.buffer = state[1].slice().buffer; + }; + + /** + * Asynchronous access to ArrayBuffer, loading blocks lazily as needed, + * using the `Range: bytes=...` header + * + * @constructor + * @param {string} filename Name of the file to download + * @param {number|undefined} size + * @param {number|undefined} fixed_chunk_size + */ + function AsyncXHRBuffer(filename, size, fixed_chunk_size) + { + this.filename = filename; + + this.byteLength = size; + + this.block_cache = new Map(); + this.block_cache_is_write = new Set(); + + this.fixed_chunk_size = fixed_chunk_size; + this.cache_reads = !!fixed_chunk_size; // TODO: could also be useful in other cases (needs testing) + + this.onload = undefined; + this.onprogress = undefined; + } + + AsyncXHRBuffer.prototype.load = function() + { + if(this.byteLength !== undefined) + { + this.onload && this.onload(Object.create(null)); + return; + } + + // Determine the size using a request + + determine_size(this.filename, (error, size) => + { + if(error) + { + throw new Error("Cannot use: " + this.filename + ". " + error); + } + else + { + dbg_assert(size >= 0); + this.byteLength = size; + this.onload && this.onload(Object.create(null)); + } + }); + }; + + /** + * @param {number} offset + * @param {number} len + * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer} + */ + AsyncXHRBuffer.prototype.get_from_cache = function(offset, len) + { + var number_of_blocks = len / BLOCK_SIZE; + var block_index = offset / BLOCK_SIZE; + + for(var i = 0; i < number_of_blocks; i++) + { + var block = this.block_cache.get(block_index + i); + + if(!block) + { + return; + } + } + + if(number_of_blocks === 1) + { + return this.block_cache.get(block_index); + } + else + { + var result = new Uint8Array(len); + for(var i = 0; i < number_of_blocks; i++) + { + result.set(this.block_cache.get(block_index + i), i * BLOCK_SIZE); + } + return result; + } + }; + + /** + * @param {number} offset + * @param {number} len + * @param {function(!Uint8Array)} fn + */ + AsyncXHRBuffer.prototype.get = function(offset, len, fn) + { + dbg_assert(offset + len <= this.byteLength); + dbg_assert(offset % BLOCK_SIZE === 0); + dbg_assert(len % BLOCK_SIZE === 0); + dbg_assert(len); + + var block = this.get_from_cache(offset, len); + if(block) + { + if(ASYNC_SAFE) + { + setTimeout(fn.bind(this, block), 0); + } + else + { + fn(block); + } + return; + } + + var requested_start = offset; + var requested_length = len; + if(this.fixed_chunk_size) + { + requested_start = offset - (offset % this.fixed_chunk_size); + requested_length = Math.ceil((offset - requested_start + len) / this.fixed_chunk_size) * this.fixed_chunk_size; + } + + v86util.load_file(this.filename, { + done: function done(buffer) + { + var block = new Uint8Array(buffer); + this.handle_read(requested_start, requested_length, block); + if(requested_start === offset && requested_length === len) + { + fn(block); + } + else + { + fn(block.subarray(offset - requested_start, offset - requested_start + len)); + } + }.bind(this), + range: { start: requested_start, length: requested_length }, + }); + }; + + /** + * Relies on this.byteLength and this.block_cache + * + * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer} + * + * @param {number} start + * @param {!Uint8Array} data + * @param {function()} fn + */ + AsyncXHRBuffer.prototype.set = function(start, data, fn) + { + var len = data.length; + dbg_assert(start + data.byteLength <= this.byteLength); + dbg_assert(start % BLOCK_SIZE === 0); + dbg_assert(len % BLOCK_SIZE === 0); + dbg_assert(len); + + var start_block = start / BLOCK_SIZE; + var block_count = len / BLOCK_SIZE; + + for(var i = 0; i < block_count; i++) + { + var block = this.block_cache.get(start_block + i); + + if(block === undefined) + { + const data_slice = data.slice(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE); + this.block_cache.set(start_block + i, data_slice); + } + else + { + const data_slice = data.subarray(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE); + dbg_assert(block.byteLength === data_slice.length); + block.set(data_slice); + } + + this.block_cache_is_write.add(start_block + i); + } + + fn(); + }; + + /** + * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer} + * @param {number} offset + * @param {number} len + * @param {!Uint8Array} block + */ + AsyncXHRBuffer.prototype.handle_read = function(offset, len, block) + { + // Used by AsyncXHRBuffer, AsyncXHRPartfileBuffer and AsyncFileBuffer + // Overwrites blocks from the original source that have been written since + + var start_block = offset / BLOCK_SIZE; + var block_count = len / BLOCK_SIZE; + + for(var i = 0; i < block_count; i++) + { + const cached_block = this.block_cache.get(start_block + i); + + if(cached_block) + { + block.set(cached_block, i * BLOCK_SIZE); + } + else if(this.cache_reads) + { + this.block_cache.set(start_block + i, block.slice(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE)); + } + } + }; + + AsyncXHRBuffer.prototype.get_buffer = function(fn) + { + // We must download all parts, unlikely a good idea for big files + fn(); + }; + + ///** + // * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer} + // */ + //AsyncXHRBuffer.prototype.get_block_cache = function() + //{ + // var count = Object.keys(this.block_cache).length; + + // var buffer = new Uint8Array(count * BLOCK_SIZE); + // var indices = []; + + // var i = 0; + // for(var index of Object.keys(this.block_cache)) + // { + // var block = this.block_cache.get(index); + // dbg_assert(block.length === BLOCK_SIZE); + // index = +index; + // indices.push(index); + // buffer.set( + // block, + // i * BLOCK_SIZE + // ); + // i++; + // } + + // return { + // buffer, + // indices, + // block_size: BLOCK_SIZE, + // }; + //}; + + /** + * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer} + */ + AsyncXHRBuffer.prototype.get_state = function() + { + const state = []; + const block_cache = []; + + for(let [index, block] of this.block_cache) + { + dbg_assert(isFinite(index)); + if(this.block_cache_is_write.has(index)) + { + block_cache.push([index, block]); + } + } + + state[0] = block_cache; + return state; + }; + + /** + * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer} + */ + AsyncXHRBuffer.prototype.set_state = function(state) + { + const block_cache = state[0]; + this.block_cache.clear(); + this.block_cache_is_write.clear(); + + for(let [index, block] of block_cache) + { + dbg_assert(isFinite(index)); + this.block_cache.set(index, block); + this.block_cache_is_write.add(index); + } + }; + + /** + * Asynchronous access to ArrayBuffer, loading blocks lazily as needed, + * downloading files named filename-%d-%d.ext (where the %d are start and end offset). + * Or, if partfile_alt_format is set, filename-%08d.ext (where %d is the part number, compatible with gnu split). + * + * @constructor + * @param {string} filename Name of the file to download + * @param {number|undefined} size + * @param {number|undefined} fixed_chunk_size + * @param {boolean|undefined} partfile_alt_format + */ + function AsyncXHRPartfileBuffer(filename, size, fixed_chunk_size, partfile_alt_format) + { + const parts = filename.match(/(.*)(\..*)/); + + if(parts) + { + this.basename = parts[1]; + this.extension = parts[2]; + } + else + { + this.basename = filename; + this.extension = ""; + } + + if(!this.basename.endsWith("/")) + { + this.basename += "-"; + } + + this.block_cache = new Map(); + this.block_cache_is_write = new Set(); + + this.byteLength = size; + this.fixed_chunk_size = fixed_chunk_size; + this.partfile_alt_format = !!partfile_alt_format; + + this.cache_reads = !!fixed_chunk_size; // TODO: could also be useful in other cases (needs testing) + + this.onload = undefined; + this.onprogress = undefined; + } + + AsyncXHRPartfileBuffer.prototype.load = function() + { + if(this.byteLength !== undefined) + { + this.onload && this.onload(Object.create(null)); + return; + } + dbg_assert(false); + this.onload && this.onload(Object.create(null)); + }; + + /** + * @param {number} offset + * @param {number} len + * @param {function(!Uint8Array)} fn + */ + AsyncXHRPartfileBuffer.prototype.get = function(offset, len, fn) + { + dbg_assert(offset + len <= this.byteLength); + dbg_assert(offset % BLOCK_SIZE === 0); + dbg_assert(len % BLOCK_SIZE === 0); + dbg_assert(len); + + const block = this.get_from_cache(offset, len); + + if(block) + { + if(ASYNC_SAFE) + { + setTimeout(fn.bind(this, block), 0); + } + else + { + fn(block); + } + return; + } + + if(this.fixed_chunk_size) + { + const start_index = Math.floor(offset / this.fixed_chunk_size); + const m_offset = offset - start_index * this.fixed_chunk_size; + dbg_assert(m_offset >= 0); + const total_count = Math.ceil((m_offset + len) / this.fixed_chunk_size); + const blocks = new Uint8Array(total_count * this.fixed_chunk_size); + let finished = 0; + + for(let i = 0; i < total_count; i++) + { + const offset = (start_index + i) * this.fixed_chunk_size; + + const part_filename = + this.partfile_alt_format ? + // matches output of gnu split: + // split -b 512 -a8 -d --additional-suffix .img w95.img w95- + this.basename + (start_index + i + "").padStart(8, "0") + this.extension + : + this.basename + offset + "-" + (offset + this.fixed_chunk_size) + this.extension; + + // XXX: unnecessary allocation + const block = this.get_from_cache(offset, this.fixed_chunk_size); + + if(block) + { + const cur = i * this.fixed_chunk_size; + blocks.set(block, cur); + finished++; + if(finished === total_count) + { + const tmp_blocks = blocks.subarray(m_offset, m_offset + len); + fn(tmp_blocks); + } + } + else + { + v86util.load_file(part_filename, { + done: function done(buffer) + { + const cur = i * this.fixed_chunk_size; + const block = new Uint8Array(buffer); + this.handle_read((start_index + i) * this.fixed_chunk_size, this.fixed_chunk_size|0, block); + blocks.set(block, cur); + finished++; + if(finished === total_count) + { + const tmp_blocks = blocks.subarray(m_offset, m_offset + len); + fn(tmp_blocks); + } + }.bind(this), + }); + } + } + } + else + { + const part_filename = this.basename + offset + "-" + (offset + len) + this.extension; + + v86util.load_file(part_filename, { + done: function done(buffer) + { + dbg_assert(buffer.byteLength === len); + var block = new Uint8Array(buffer); + this.handle_read(offset, len, block); + fn(block); + }.bind(this), + }); + } + }; + + AsyncXHRPartfileBuffer.prototype.get_from_cache = AsyncXHRBuffer.prototype.get_from_cache; + AsyncXHRPartfileBuffer.prototype.set = AsyncXHRBuffer.prototype.set; + AsyncXHRPartfileBuffer.prototype.handle_read = AsyncXHRBuffer.prototype.handle_read; + //AsyncXHRPartfileBuffer.prototype.get_block_cache = AsyncXHRBuffer.prototype.get_block_cache; + AsyncXHRPartfileBuffer.prototype.get_state = AsyncXHRBuffer.prototype.get_state; + AsyncXHRPartfileBuffer.prototype.set_state = AsyncXHRBuffer.prototype.set_state; + + /** + * Synchronous access to File, loading blocks from the input type=file + * The whole file is loaded into memory during initialisation + * + * @constructor + */ + function SyncFileBuffer(file) + { + this.file = file; + this.byteLength = file.size; + + if(file.size > (1 << 30)) + { + console.warn("SyncFileBuffer: Allocating buffer of " + (file.size >> 20) + " MB ..."); + } + + this.buffer = new ArrayBuffer(file.size); + + this.onload = undefined; + this.onprogress = undefined; + } + + SyncFileBuffer.prototype.load = function() + { + this.load_next(0); + }; + + /** + * @param {number} start + */ + SyncFileBuffer.prototype.load_next = function(start) + { + /** @const */ + var PART_SIZE = 4 << 20; + + var filereader = new FileReader(); + + filereader.onload = function(e) + { + var buffer = new Uint8Array(e.target.result); + new Uint8Array(this.buffer, start).set(buffer); + this.load_next(start + PART_SIZE); + }.bind(this); + + if(this.onprogress) + { + this.onprogress({ + loaded: start, + total: this.byteLength, + lengthComputable: true, + }); + } + + if(start < this.byteLength) + { + var end = Math.min(start + PART_SIZE, this.byteLength); + var slice = this.file.slice(start, end); + filereader.readAsArrayBuffer(slice); + } + else + { + this.file = undefined; + this.onload && this.onload({ buffer: this.buffer }); + } + }; + + SyncFileBuffer.prototype.get = SyncBuffer.prototype.get; + SyncFileBuffer.prototype.set = SyncBuffer.prototype.set; + SyncFileBuffer.prototype.get_buffer = SyncBuffer.prototype.get_buffer; + SyncFileBuffer.prototype.get_state = SyncBuffer.prototype.get_state; + SyncFileBuffer.prototype.set_state = SyncBuffer.prototype.set_state; + + /** + * Asynchronous access to File, loading blocks from the input type=file + * + * @constructor + */ + function AsyncFileBuffer(file) + { + this.file = file; + this.byteLength = file.size; + + this.block_cache = new Map(); + this.block_cache_is_write = new Set(); + + this.onload = undefined; + this.onprogress = undefined; + } + + AsyncFileBuffer.prototype.load = function() + { + this.onload && this.onload(Object.create(null)); + }; + + /** + * @param {number} offset + * @param {number} len + * @param {function(!Uint8Array)} fn + */ + AsyncFileBuffer.prototype.get = function(offset, len, fn) + { + dbg_assert(offset % BLOCK_SIZE === 0); + dbg_assert(len % BLOCK_SIZE === 0); + dbg_assert(len); + + var block = this.get_from_cache(offset, len); + if(block) + { + fn(block); + return; + } + + var fr = new FileReader(); + + fr.onload = function(e) + { + var buffer = e.target.result; + var block = new Uint8Array(buffer); + + this.handle_read(offset, len, block); + fn(block); + }.bind(this); + + fr.readAsArrayBuffer(this.file.slice(offset, offset + len)); + }; + AsyncFileBuffer.prototype.get_from_cache = AsyncXHRBuffer.prototype.get_from_cache; + AsyncFileBuffer.prototype.set = AsyncXHRBuffer.prototype.set; + AsyncFileBuffer.prototype.handle_read = AsyncXHRBuffer.prototype.handle_read; + AsyncFileBuffer.prototype.get_state = AsyncXHRBuffer.prototype.get_state; + AsyncFileBuffer.prototype.set_state = AsyncXHRBuffer.prototype.set_state; + + AsyncFileBuffer.prototype.get_buffer = function(fn) + { + // We must load all parts, unlikely a good idea for big files + fn(); + }; + + AsyncFileBuffer.prototype.get_as_file = function(name) + { + var parts = []; + var existing_blocks = Array.from(this.block_cache.keys()).sort(function(x, y) { return x - y; }); + + var current_offset = 0; + + for(var i = 0; i < existing_blocks.length; i++) + { + var block_index = existing_blocks[i]; + var block = this.block_cache.get(block_index); + var start = block_index * BLOCK_SIZE; + dbg_assert(start >= current_offset); + + if(start !== current_offset) + { + parts.push(this.file.slice(current_offset, start)); + current_offset = start; + } + + parts.push(block); + current_offset += block.length; + } + + if(current_offset !== this.file.size) + { + parts.push(this.file.slice(current_offset)); + } + + var file = new File(parts, name); + dbg_assert(file.size === this.file.size); + + return file; + }; + + if(typeof XMLHttpRequest === "undefined") + { + var determine_size = function(path, cb) + { + require("fs")["stat"](path, (err, stats) => + { + if(err) + { + cb(err); + } + else + { + cb(null, stats.size); + } + }); + }; + } + else + { + var determine_size = function(url, cb) + { + v86util.load_file(url, { + done: (buffer, http) => + { + var header = http.getResponseHeader("Content-Range") || ""; + var match = header.match(/\/(\d+)\s*$/); + + if(match) + { + cb(null, +match[1]); + } + else + { + const error = "`Range: bytes=...` header not supported (Got `" + header + "`)"; + cb(error); + } + }, + headers: { + Range: "bytes=0-0", + } + }); + }; + } +})(); diff --git a/src/bus.js b/src/bus.js new file mode 100644 index 0000000..e1ced8f --- /dev/null +++ b/src/bus.js @@ -0,0 +1,104 @@ +"use strict"; + +var Bus = {}; + +/** @constructor */ +function BusConnector() +{ + this.listeners = {}; + this.pair = undefined; +} + +/** + * @param {string} name + * @param {function(?)} fn + * @param {Object} this_value + */ +BusConnector.prototype.register = function(name, fn, this_value) +{ + var listeners = this.listeners[name]; + + if(listeners === undefined) + { + listeners = this.listeners[name] = []; + } + + listeners.push({ + fn: fn, + this_value: this_value, + }); +}; + +/** + * Unregister one message with the given name and callback + * + * @param {string} name + * @param {function(?)} fn + */ +BusConnector.prototype.unregister = function(name, fn) +{ + var listeners = this.listeners[name]; + + if(listeners === undefined) + { + return; + } + + this.listeners[name] = listeners.filter(function(l) + { + return l.fn !== fn; + }); +}; + +/** + * Send ("emit") a message + * + * @param {string} name + * @param {*=} value + * @param {*=} unused_transfer + */ +BusConnector.prototype.send = function(name, value, unused_transfer) +{ + if(!this.pair) + { + return; + } + + var listeners = this.pair.listeners[name]; + + if(listeners === undefined) + { + return; + } + + for(var i = 0; i < listeners.length; i++) + { + var listener = listeners[i]; + listener.fn.call(listener.this_value, value); + } +}; + +/** + * Send a message, guaranteeing that it is received asynchronously + * + * @param {string} name + * @param {Object=} value + */ +BusConnector.prototype.send_async = function(name, value) +{ + dbg_assert(arguments.length === 1 || arguments.length === 2); + + setTimeout(this.send.bind(this, name, value), 0); +}; + +Bus.create = function() +{ + var c0 = new BusConnector(); + var c1 = new BusConnector(); + + c0.pair = c1; + c1.pair = c0; + + return [c0, c1]; +}; + diff --git a/src/config.js b/src/config.js new file mode 100644 index 0000000..1eca2b8 --- /dev/null +++ b/src/config.js @@ -0,0 +1,64 @@ +"use strict"; +/* + * Compile time configuration, some only relevant for debug mode + */ + +/** + * @define {boolean} + * Overridden for production by closure compiler + */ +var DEBUG = true; + +/** @const */ +var LOG_TO_FILE = false; + +/** + * @const + * Enables logging all IO port reads and writes. Very verbose + */ +var LOG_ALL_IO = false; + +/** + * @const + */ +var DUMP_GENERATED_WASM = false; + +/** + * @const + */ +var DUMP_UNCOMPILED_ASSEMBLY = false; + +/** + * @const + * More accurate filenames in 9p debug messages at the cost of performance. + */ +var TRACK_FILENAMES = false; + +var LOG_LEVEL = LOG_ALL & ~LOG_PS2 & ~LOG_PIT & ~LOG_VIRTIO & ~LOG_9P & ~LOG_PIC & + ~LOG_DMA & ~LOG_SERIAL & ~LOG_NET & ~LOG_FLOPPY & ~LOG_DISK & ~LOG_VGA & ~LOG_SB16; + +/** + * @const + * Draws entire buffer and visualizes the layers that would be drawn + */ +var DEBUG_SCREEN_LAYERS = DEBUG && false; + + +/** @const */ +var ENABLE_HPET = DEBUG && false; + +/** + * @const + * How often, in milliseconds, to yield to the browser for rendering and + * running events + */ +var TIME_PER_FRAME = 1; + +/** + * @const + * How many ticks the TSC does per millisecond + */ +var TSC_RATE = 1 * 1000 * 1000; + +/** @const */ +var APIC_TIMER_FREQ = TSC_RATE; diff --git a/src/const.js b/src/const.js new file mode 100644 index 0000000..d0e17a5 --- /dev/null +++ b/src/const.js @@ -0,0 +1,163 @@ +"use strict"; + +var +/** @const */ LOG_ALL = -1, +/** @const */ LOG_NONE = 0, + +/** @const */ LOG_OTHER = 0x000001, +/** @const */ LOG_CPU = 0x000002, +/** @const */ LOG_FPU = 0x000004, +/** @const */ LOG_MEM = 0x000008, +/** @const */ LOG_DMA = 0x000010, +/** @const */ LOG_IO = 0x000020, +/** @const */ LOG_PS2 = 0x000040, +/** @const */ LOG_PIC = 0x000080, +/** @const */ LOG_VGA = 0x000100, +/** @const */ LOG_PIT = 0x000200, +/** @const */ LOG_MOUSE = 0x000400, +/** @const */ LOG_PCI = 0x000800, +/** @const */ LOG_BIOS = 0x001000, +/** @const */ LOG_FLOPPY = 0x002000, +/** @const */ LOG_SERIAL = 0x004000, +/** @const */ LOG_DISK = 0x008000, +/** @const */ LOG_RTC = 0x010000, +/** @const */ LOG_HPET = 0x020000, +/** @const */ LOG_ACPI = 0x040000, +/** @const */ LOG_APIC = 0x080000, +/** @const */ LOG_NET = 0x100000, +/** @const */ LOG_VIRTIO = 0x200000, +/** @const */ LOG_9P = 0x400000, +/** @const */ LOG_SB16 = 0x800000; + + +/** + * @const + * @type {Array>} + */ +var LOG_NAMES = [ + [1, ""], + [LOG_CPU, "CPU"], + [LOG_DISK, "DISK"], + [LOG_FPU, "FPU"], + [LOG_MEM, "MEM"], + [LOG_DMA, "DMA"], + [LOG_IO, "IO"], + [LOG_PS2, "PS2"], + [LOG_PIC, "PIC"], + [LOG_VGA, "VGA"], + [LOG_PIT, "PIT"], + [LOG_MOUSE, "MOUS"], + [LOG_PCI, "PCI"], + [LOG_BIOS, "BIOS"], + [LOG_FLOPPY, "FLOP"], + [LOG_SERIAL, "SERI"], + [LOG_RTC, "RTC"], + [LOG_HPET, "HPET"], + [LOG_ACPI, "ACPI"], + [LOG_APIC, "APIC"], + [LOG_NET, "NET"], + [LOG_VIRTIO, "VIO"], + [LOG_9P, "9P"], + [LOG_SB16, "SB16"] +]; + +var + +// flags register bitflags +/** @const */ FLAG_CARRY = 1, +/** @const */ FLAG_PARITY = 4, +/** @const */ FLAG_ADJUST = 16, +/** @const */ FLAG_ZERO = 64, +/** @const */ FLAG_SIGN = 128, +/** @const */ FLAG_TRAP = 256, +/** @const */ FLAG_INTERRUPT = 512, +/** @const */ FLAG_DIRECTION = 1024, +/** @const */ FLAG_OVERFLOW = 2048, +/** @const */ FLAG_IOPL = 1 << 12 | 1 << 13, +/** @const */ FLAG_NT = 1 << 14, +/** @const */ FLAG_RF = 1 << 16, +/** @const */ FLAG_VM = 1 << 17, +/** @const */ FLAG_AC = 1 << 18, +/** @const */ FLAG_VIF = 1 << 19, +/** @const */ FLAG_VIP = 1 << 20, +/** @const */ FLAG_ID = 1 << 21, + +/** + * default values of reserved flags bits + * @const + */ +FLAGS_DEFAULT = 1 << 1, + + +/** @const */ REG_EAX = 0, +/** @const */ REG_ECX = 1, +/** @const */ REG_EDX = 2, +/** @const */ REG_EBX = 3, +/** @const */ REG_ESP = 4, +/** @const */ REG_EBP = 5, +/** @const */ REG_ESI = 6, +/** @const */ REG_EDI = 7, + +/** @const */ REG_ES = 0, +/** @const */ REG_CS = 1, +/** @const */ REG_SS = 2, +/** @const */ REG_DS = 3, +/** @const */ REG_FS = 4, +/** @const */ REG_GS = 5, + +/** @const */ REG_LDTR = 7; // local descriptor table register + +var + /** + * The minimum number of bytes that can be memory-mapped + * by one device. + * + * @const + */ + MMAP_BLOCK_BITS = 17, + /** @const */ + MMAP_BLOCK_SIZE = 1 << MMAP_BLOCK_BITS; + +/** @const */ +var CR0_PG = 1 << 31; +/** @const */ +var CR4_PAE = 1 << 5; + + +// https://github.com/qemu/seabios/blob/14221cd86eadba82255fdc55ed174d401c7a0a04/src/fw/paravirt.c#L205-L219 + +/** @const */ var FW_CFG_SIGNATURE = 0x00; +/** @const */ var FW_CFG_ID = 0x01; +/** @const */ var FW_CFG_RAM_SIZE = 0x03; +/** @const */ var FW_CFG_NB_CPUS = 0x05; +/** @const */ var FW_CFG_MAX_CPUS = 0x0F; +/** @const */ var FW_CFG_NUMA = 0x0D; +/** @const */ var FW_CFG_FILE_DIR = 0x19; + +/** @const */ var FW_CFG_CUSTOM_START = 0x8000; +// This value is specific to v86, choosen to hopefully not collide with other indexes +/** @const */ var FW_CFG_FILE_START = 0xC000; + +/** @const */ var FW_CFG_SIGNATURE_QEMU = 0x554D4551; + + +// See same constant in jit.rs +/** @const */ +var WASM_TABLE_SIZE = 900; + +/** @const */ +var WASM_TABLE_OFFSET = 1024; + + +/** @const */ +var MIXER_CHANNEL_LEFT = 0; +/** @const */ +var MIXER_CHANNEL_RIGHT = 1; +/** @const */ +var MIXER_CHANNEL_BOTH = 2; +/** @const */ +var MIXER_SRC_MASTER = 0; +/** @const */ +var MIXER_SRC_PCSPEAKER = 1; +/** @const */ +var MIXER_SRC_DAC = 2; diff --git a/src/cpu.js b/src/cpu.js new file mode 100644 index 0000000..00f74f0 --- /dev/null +++ b/src/cpu.js @@ -0,0 +1,1529 @@ +"use strict"; + +/** @const */ +var CPU_LOG_VERBOSE = false; + + +// Resources: +// https://pdos.csail.mit.edu/6.828/2006/readings/i386/toc.htm +// https://www-ssl.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html +// http://ref.x86asm.net/geek32.html + + +/** @constructor */ +function CPU(bus, wm, next_tick_immediately) +{ + this.next_tick_immediately = next_tick_immediately; + this.wm = wm; + this.wasm_patch(); + this.create_jit_imports(); + + const memory = this.wm.exports.memory; + + this.wasm_memory = memory; + + this.memory_size = v86util.view(Uint32Array, memory, 812, 1); + + this.mem8 = new Uint8Array(0); + this.mem32s = new Int32Array(this.mem8.buffer); + + this.segment_is_null = v86util.view(Uint8Array, memory, 724, 8); + this.segment_offsets = v86util.view(Int32Array, memory, 736, 8); + this.segment_limits = v86util.view(Uint32Array, memory, 768, 8); + + /** + * Wheter or not in protected mode + */ + this.protected_mode = v86util.view(Int32Array, memory, 800, 1); + + this.idtr_size = v86util.view(Int32Array, memory, 564, 1); + this.idtr_offset = v86util.view(Int32Array, memory, 568, 1); + + /** + * global descriptor table register + */ + this.gdtr_size = v86util.view(Int32Array, memory, 572, 1); + this.gdtr_offset = v86util.view(Int32Array, memory, 576, 1); + + this.tss_size_32 = v86util.view(Int32Array, memory, 1128, 1); + + /* + * whether or not a page fault occured + */ + this.page_fault = v86util.view(Uint32Array, memory, 540, 8); + + this.cr = v86util.view(Int32Array, memory, 580, 8); + + // current privilege level + this.cpl = v86util.view(Uint8Array, memory, 612, 1); + + // current operand/address size + this.is_32 = v86util.view(Int32Array, memory, 804, 1); + + this.stack_size_32 = v86util.view(Int32Array, memory, 808, 1); + + /** + * Was the last instruction a hlt? + */ + this.in_hlt = v86util.view(Uint8Array, memory, 616, 1); + + this.last_virt_eip = v86util.view(Int32Array, memory, 620, 1); + this.eip_phys = v86util.view(Int32Array, memory, 624, 1); + + + this.sysenter_cs = v86util.view(Int32Array, memory, 636, 1); + + this.sysenter_esp = v86util.view(Int32Array, memory, 640, 1); + + this.sysenter_eip = v86util.view(Int32Array, memory, 644, 1); + + this.prefixes = v86util.view(Int32Array, memory, 648, 1); + + this.flags = v86util.view(Int32Array, memory, 120, 1); + + /** + * bitmap of flags which are not updated in the flags variable + * changed by arithmetic instructions, so only relevant to arithmetic flags + */ + this.flags_changed = v86util.view(Int32Array, memory, 100, 1); + + /** + * enough infos about the last arithmetic operation to compute eflags + */ + this.last_op_size = v86util.view(Int32Array, memory, 96, 1); + this.last_op1 = v86util.view(Int32Array, memory, 104, 1); + this.last_result = v86util.view(Int32Array, memory, 112, 1); + + this.current_tsc = v86util.view(Uint32Array, memory, 960, 2); // 64 bit + + /** @type {!Object} */ + this.devices = {}; + + this.instruction_pointer = v86util.view(Int32Array, memory, 556, 1); + this.previous_ip = v86util.view(Int32Array, memory, 560, 1); + + // configured by guest + this.apic_enabled = v86util.view(Uint8Array, memory, 548, 1); + // configured when the emulator starts (changes bios initialisation) + this.acpi_enabled = v86util.view(Uint8Array, memory, 552, 1); + + // managed in io.js + /** @const */ this.memory_map_read8 = []; + /** @const */ this.memory_map_write8 = []; + /** @const */ this.memory_map_read32 = []; + /** @const */ this.memory_map_write32 = []; + + /** + * @const + * @type {{main: ArrayBuffer, vga: ArrayBuffer}} + */ + this.bios = { + main: null, + vga: null, + }; + + this.instruction_counter = v86util.view(Uint32Array, memory, 664, 1); + + // registers + this.reg32 = v86util.view(Int32Array, memory, 64, 8); + + this.fpu_st = v86util.view(Int32Array, memory, 1152, 4 * 8); + + this.fpu_stack_empty = v86util.view(Uint8Array, memory, 816, 1); + this.fpu_stack_empty[0] = 0xFF; + this.fpu_stack_ptr = v86util.view(Uint8Array, memory, 1032, 1); + this.fpu_stack_ptr[0] = 0; + + this.fpu_control_word = v86util.view(Uint16Array, memory, 1036, 1); + this.fpu_control_word[0] = 0x37F; + this.fpu_status_word = v86util.view(Uint16Array, memory, 1040, 1); + this.fpu_status_word[0] = 0; + this.fpu_ip = v86util.view(Int32Array, memory, 1048, 1); + this.fpu_ip[0] = 0; + this.fpu_ip_selector = v86util.view(Int32Array, memory, 1052, 1); + this.fpu_ip_selector[0] = 0; + this.fpu_opcode = v86util.view(Int32Array, memory, 1044, 1); + this.fpu_opcode[0] = 0; + this.fpu_dp = v86util.view(Int32Array, memory, 1056, 1); + this.fpu_dp[0] = 0; + this.fpu_dp_selector = v86util.view(Int32Array, memory, 1060, 1); + this.fpu_dp_selector[0] = 0; + + this.reg_xmm32s = v86util.view(Int32Array, memory, 832, 8 * 4); + + this.mxcsr = v86util.view(Int32Array, memory, 824, 1); + + // segment registers, tr and ldtr + this.sreg = v86util.view(Uint16Array, memory, 668, 8); + + // debug registers + this.dreg = v86util.view(Int32Array, memory, 684, 8); + + this.reg_pdpte = v86util.view(Int32Array, memory, 968, 8); + + this.svga_dirty_bitmap_min_offset = v86util.view(Uint32Array, memory, 716, 1); + this.svga_dirty_bitmap_max_offset = v86util.view(Uint32Array, memory, 720, 1); + + this.fw_value = []; + this.fw_pointer = 0; + this.option_roms = []; + + this.io = undefined; + + this.bus = bus; + + this.set_tsc(0, 0); + + this.debug_init(); + + if(DEBUG) + { + this.do_many_cycles_count = 0; + this.do_many_cycles_total = 0; + + this.seen_code = {}; + this.seen_code_uncompiled = {}; + } + + //Object.seal(this); +} + +CPU.prototype.clear_opstats = function() +{ + new Uint8Array(this.wasm_memory.buffer, 0x8000, 0x20000).fill(0); + this.wm.exports["profiler_init"](); +}; + +CPU.prototype.create_jit_imports = function() +{ + // Set this.jit_imports as generated WASM modules will expect + + const jit_imports = Object.create(null); + + jit_imports["m"] = this.wm.exports["memory"]; + + for(let name of Object.keys(this.wm.exports)) + { + if(name.startsWith("_") || name.startsWith("zstd") || name.endsWith("_js")) + { + continue; + } + + jit_imports[name] = this.wm.exports[name]; + } + + this.jit_imports = jit_imports; +}; + +CPU.prototype.wasm_patch = function() +{ + const get_optional_import = (name) => { + return this.wm.exports[name]; + }; + + const get_import = (name) => + { + const f = get_optional_import(name); + console.assert(f, "Missing import: " + name); + return f; + }; + + this.reset_cpu = get_import("reset_cpu"); + + this.getiopl = get_import("getiopl"); + this.get_eflags = get_import("get_eflags"); + this.get_eflags_no_arith = get_import("get_eflags_no_arith"); + + this.pic_call_irq = get_import("pic_call_irq"); + + this.do_many_cycles_native = get_import("do_many_cycles_native"); + this.cycle_internal = get_import("cycle_internal"); + + this.read8 = get_import("read8"); + this.read16 = get_import("read16"); + this.read32s = get_import("read32s"); + this.write8 = get_import("write8"); + this.write16 = get_import("write16"); + this.write32 = get_import("write32"); + this.in_mapped_range = get_import("in_mapped_range"); + + // used by nasmtests + this.fpu_load_tag_word = get_import("fpu_load_tag_word"); + this.fpu_load_status_word = get_import("fpu_load_status_word"); + this.fpu_get_sti_f64 = get_import("fpu_get_sti_f64"); + + this.translate_address_system_read = get_import("translate_address_system_read_js"); + + this.get_seg_cs = get_import("get_seg_cs"); + this.get_real_eip = get_import("get_real_eip"); + + this.clear_tlb = get_import("clear_tlb"); + this.full_clear_tlb = get_import("full_clear_tlb"); + this.update_state_flags = get_import("update_state_flags"); + + this.set_tsc = get_import("set_tsc"); + this.store_current_tsc = get_import("store_current_tsc"); + + this.set_cpuid_level = get_import("set_cpuid_level"); + + if(DEBUG) + { + this.jit_force_generate_unsafe = get_optional_import("jit_force_generate_unsafe"); + } + + this.jit_clear_cache = get_import("jit_clear_cache_js"); + this.jit_dirty_cache = get_import("jit_dirty_cache"); + this.codegen_finalize_finished = get_import("codegen_finalize_finished"); + + this.allocate_memory = get_import("allocate_memory"); + this.zero_memory = get_import("zero_memory"); + + this.svga_allocate_memory = get_import("svga_allocate_memory"); + this.svga_allocate_dest_buffer = get_import("svga_allocate_dest_buffer"); + this.svga_fill_pixel_buffer = get_import("svga_fill_pixel_buffer"); + this.svga_mark_dirty = get_import("svga_mark_dirty"); + + this.zstd_create_ctx = get_import("zstd_create_ctx"); + this.zstd_get_src_ptr = get_import("zstd_get_src_ptr"); + this.zstd_free_ctx = get_import("zstd_free_ctx"); + this.zstd_read = get_import("zstd_read"); + this.zstd_read_free = get_import("zstd_read_free"); +}; + +CPU.prototype.jit_force_generate = function(addr) +{ + if(!this.jit_force_generate_unsafe) + { + dbg_assert(false, "Not supported in this wasm build: jit_force_generate_unsafe"); + return; + } + + this.jit_force_generate_unsafe(addr); +}; + +CPU.prototype.jit_clear_func = function(index) +{ + dbg_assert(index >= 0 && index < WASM_TABLE_SIZE); + this.wm.wasm_table.set(index + WASM_TABLE_OFFSET, null); +}; + +CPU.prototype.jit_clear_all_funcs = function() +{ + const table = this.wm.wasm_table; + + for(let i = 0; i < WASM_TABLE_SIZE; i++) + { + table.set(WASM_TABLE_OFFSET + i, null); + } +}; + +CPU.prototype.get_state = function() +{ + var state = []; + + state[0] = this.memory_size[0]; + state[1] = this.segment_is_null; + state[2] = this.segment_offsets; + state[3] = this.segment_limits; + state[4] = this.protected_mode[0]; + state[5] = this.idtr_offset[0]; + state[6] = this.idtr_size[0]; + state[7] = this.gdtr_offset[0]; + state[8] = this.gdtr_size[0]; + state[9] = this.page_fault[0]; + state[10] = this.cr; + state[11] = this.cpl[0]; + + state[13] = this.is_32[0]; + + state[16] = this.stack_size_32[0]; + state[17] = this.in_hlt[0]; + state[18] = this.last_virt_eip[0]; + state[19] = this.eip_phys[0]; + + state[22] = this.sysenter_cs[0]; + state[23] = this.sysenter_eip[0]; + state[24] = this.sysenter_esp[0]; + state[25] = this.prefixes[0]; + state[26] = this.flags[0]; + state[27] = this.flags_changed[0]; + state[28] = this.last_op1[0]; + + state[30] = this.last_op_size[0]; + + state[37] = this.instruction_pointer[0]; + state[38] = this.previous_ip[0]; + state[39] = this.reg32; + state[40] = this.sreg; + state[41] = this.dreg; + state[42] = this.reg_pdpte; + + this.store_current_tsc(); + state[43] = this.current_tsc; + + state[45] = this.devices.virtio_9p; + state[46] = this.devices.apic; + state[47] = this.devices.rtc; + state[48] = this.devices.pci; + state[49] = this.devices.dma; + state[50] = this.devices.acpi; + state[51] = this.devices.hpet; + state[52] = this.devices.vga; + state[53] = this.devices.ps2; + state[54] = this.devices.uart0; + state[55] = this.devices.fdc; + state[56] = this.devices.cdrom; + state[57] = this.devices.hda; + state[58] = this.devices.pit; + state[59] = this.devices.net; + state[60] = this.devices.pic; + state[61] = this.devices.sb16; + + state[62] = this.fw_value; + + state[63] = this.devices.ioapic; + + state[64] = this.tss_size_32[0]; + + state[66] = this.reg_xmm32s; + + state[67] = this.fpu_st; + state[68] = this.fpu_stack_empty[0]; + state[69] = this.fpu_stack_ptr[0]; + state[70] = this.fpu_control_word[0]; + state[71] = this.fpu_ip[0]; + state[72] = this.fpu_ip_selector[0]; + state[73] = this.fpu_dp[0]; + state[74] = this.fpu_dp_selector[0]; + state[75] = this.fpu_opcode[0]; + + const { packed_memory, bitmap } = this.pack_memory(); + state[77] = packed_memory; + state[78] = new Uint8Array(bitmap.get_buffer()); + + state[79] = this.devices.uart1; + state[80] = this.devices.uart2; + state[81] = this.devices.uart3; + + return state; +}; + +CPU.prototype.set_state = function(state) +{ + this.memory_size[0] = state[0]; + + if(this.mem8.length !== this.memory_size[0]) + { + console.warn("Note: Memory size mismatch. we=" + this.mem8.length + " state=" + this.memory_size[0]); + } + + this.segment_is_null.set(state[1]); + this.segment_offsets.set(state[2]); + this.segment_limits.set(state[3]); + this.protected_mode[0] = state[4]; + this.idtr_offset[0] = state[5]; + this.idtr_size[0] = state[6]; + this.gdtr_offset[0] = state[7]; + this.gdtr_size[0] = state[8]; + this.page_fault[0] = state[9]; + this.cr.set(state[10]); + this.cpl[0] = state[11]; + + this.is_32[0] = state[13]; + + this.stack_size_32[0] = state[16]; + + this.in_hlt[0] = state[17]; + this.last_virt_eip[0] = state[18]; + this.eip_phys[0] = state[19]; + + this.sysenter_cs[0] = state[22]; + this.sysenter_eip[0] = state[23]; + this.sysenter_esp[0] = state[24]; + this.prefixes[0] = state[25]; + + this.flags[0] = state[26]; + this.flags_changed[0] = state[27]; + this.last_op1[0] = state[28]; + + this.last_op_size[0] = state[30]; + + this.instruction_pointer[0] = state[37]; + this.previous_ip[0] = state[38]; + this.reg32.set(state[39]); + this.sreg.set(state[40]); + this.dreg.set(state[41]); + state[42] && this.reg_pdpte.set(state[42]); + + this.set_tsc(state[43][0], state[43][1]); + + this.devices.virtio_9p && this.devices.virtio_9p.set_state(state[45]); + this.devices.apic && this.devices.apic.set_state(state[46]); + this.devices.rtc && this.devices.rtc.set_state(state[47]); + this.devices.pci && this.devices.pci.set_state(state[48]); + this.devices.dma && this.devices.dma.set_state(state[49]); + this.devices.acpi && this.devices.acpi.set_state(state[50]); + this.devices.hpet && this.devices.hpet.set_state(state[51]); + this.devices.vga && this.devices.vga.set_state(state[52]); + this.devices.ps2 && this.devices.ps2.set_state(state[53]); + this.devices.uart0 && this.devices.uart0.set_state(state[54]); + this.devices.fdc && this.devices.fdc.set_state(state[55]); + this.devices.cdrom && this.devices.cdrom.set_state(state[56]); + this.devices.hda && this.devices.hda.set_state(state[57]); + this.devices.pit && this.devices.pit.set_state(state[58]); + this.devices.net && this.devices.net.set_state(state[59]); + this.devices.pic && this.devices.pic.set_state(state[60]); + this.devices.sb16 && this.devices.sb16.set_state(state[61]); + + this.devices.uart1 && this.devices.uart1.set_state(state[79]); + this.devices.uart2 && this.devices.uart2.set_state(state[80]); + this.devices.uart3 && this.devices.uart3.set_state(state[81]); + + this.fw_value = state[62]; + + this.devices.ioapic && this.devices.ioapic.set_state(state[63]); + + this.tss_size_32[0] = state[64]; + + this.reg_xmm32s.set(state[66]); + + this.fpu_st.set(state[67]); + this.fpu_stack_empty[0] = state[68]; + this.fpu_stack_ptr[0] = state[69]; + this.fpu_control_word[0] = state[70]; + this.fpu_ip[0] = state[71]; + this.fpu_ip_selector[0] = state[72]; + this.fpu_dp[0] = state[73]; + this.fpu_dp_selector[0] = state[74]; + this.fpu_opcode[0] = state[75]; + + const bitmap = new v86util.Bitmap(state[78].buffer); + const packed_memory = state[77]; + this.unpack_memory(bitmap, packed_memory); + + this.update_state_flags(); + + this.full_clear_tlb(); + + this.jit_clear_cache(); +}; + +CPU.prototype.pack_memory = function() +{ + dbg_assert((this.mem8.length & 0xFFF) === 0); + + const page_count = this.mem8.length >> 12; + const nonzero_pages = []; + + for(let page = 0; page < page_count; page++) + { + const offset = page << 12; + const view = this.mem32s.subarray(offset >> 2, offset + 0x1000 >> 2); + let is_zero = true; + + for(let i = 0; i < view.length; i++) + { + if(view[i] !== 0) + { + is_zero = false; + break; + } + } + + if(!is_zero) + { + nonzero_pages.push(page); + } + } + + const bitmap = new v86util.Bitmap(page_count); + const packed_memory = new Uint8Array(nonzero_pages.length << 12); + + for(let [i, page] of nonzero_pages.entries()) + { + bitmap.set(page, 1); + + const offset = page << 12; + const page_contents = this.mem8.subarray(offset, offset + 0x1000); + packed_memory.set(page_contents, i << 12); + } + + return { bitmap, packed_memory }; +}; + +CPU.prototype.unpack_memory = function(bitmap, packed_memory) +{ + this.zero_memory(this.memory_size[0]); + + const page_count = this.memory_size[0] >> 12; + let packed_page = 0; + + for(let page = 0; page < page_count; page++) + { + if(bitmap.get(page)) + { + let offset = packed_page << 12; + let view = packed_memory.subarray(offset, offset + 0x1000); + this.mem8.set(view, page << 12); + packed_page++; + } + } +}; + +/** + * @return {number} time in ms until this method should becalled again + */ +CPU.prototype.main_run = function() +{ + if(this.in_hlt[0]) + { + const t = this.hlt_loop(); + + if(this.in_hlt[0]) + { + return t; + } + } + + const start = v86.microtick(); + let now = start; + + for(; now - start < TIME_PER_FRAME;) + { + this.do_many_cycles(); + + now = v86.microtick(); + + const t = this.run_hardware_timers(now); + this.handle_irqs(); + + if(this.in_hlt[0]) + { + return t; + } + } + + return 0; +}; + +CPU.prototype.reboot_internal = function() +{ + this.reset_cpu(); + + this.fw_value = []; + + if(this.devices.virtio) + { + this.devices.virtio.reset(); + } + + this.load_bios(); +}; + +CPU.prototype.reset_memory = function() +{ + this.mem8.fill(0); +}; + +/** @export */ +CPU.prototype.create_memory = function(size) +{ + if(size < 1024 * 1024) + { + size = 1024 * 1024; + } + else if((size | 0) < 0) + { + size = Math.pow(2, 31) - MMAP_BLOCK_SIZE; + } + + size = ((size - 1) | (MMAP_BLOCK_SIZE - 1)) + 1 | 0; + dbg_assert((size | 0) > 0); + dbg_assert((size & MMAP_BLOCK_SIZE - 1) === 0); + + console.assert(this.memory_size[0] === 0, "Expected uninitialised memory"); + + this.memory_size[0] = size; + + const memory_offset = this.allocate_memory(size); + + this.mem8 = v86util.view(Uint8Array, this.wasm_memory, memory_offset, size); + this.mem32s = v86util.view(Uint32Array, this.wasm_memory, memory_offset, size >> 2); +}; + +CPU.prototype.init = function(settings, device_bus) +{ + if(typeof settings.log_level === "number") + { + // XXX: Shared between all emulator instances + LOG_LEVEL = settings.log_level; + } + + this.create_memory(typeof settings.memory_size === "number" ? + settings.memory_size : 1024 * 1024 * 64); + + settings.cpuid_level && this.set_cpuid_level(settings.cpuid_level); + + this.acpi_enabled[0] = +settings.acpi; + + this.reset_cpu(); + + var io = new IO(this); + this.io = io; + + this.bios.main = settings.bios; + this.bios.vga = settings.vga_bios; + + this.load_bios(); + + if(settings.bzimage) + { + const { option_rom } = load_kernel(this.mem8, settings.bzimage, settings.initrd, settings.cmdline || ""); + + if(option_rom) + { + this.option_roms.push(option_rom); + } + } + + io.register_read(0xB3, this, function() + { + // seabios smm_relocate_and_restore + dbg_log("port 0xB3 read"); + return 0; + }); + + var a20_byte = 0; + + io.register_read(0x92, this, function() + { + return a20_byte; + }); + + io.register_write(0x92, this, function(out_byte) + { + a20_byte = out_byte; + }); + + io.register_read(0x511, this, function() + { + // bios config port (used by seabios and kvm-unit-test) + if(this.fw_pointer < this.fw_value.length) + { + return this.fw_value[this.fw_pointer++]; + } + else + { + dbg_assert(false, "config port: Read past value"); + return 0; + } + }); + io.register_write(0x510, this, undefined, function(value) + { + // https://wiki.osdev.org/QEMU_fw_cfg + // https://github.com/qemu/qemu/blob/master/docs/specs/fw_cfg.txt + + dbg_log("bios config port, index=" + h(value)); + + function i32(x) + { + return new Uint8Array(new Int32Array([x]).buffer); + } + + function to_be16(x) + { + return x >> 8 | x << 8 & 0xFF00; + } + + function to_be32(x) + { + return x << 24 | x << 8 & 0xFF0000 | x >> 8 & 0xFF00 | x >>> 24; + } + + this.fw_pointer = 0; + + if(value === FW_CFG_SIGNATURE) + { + // Pretend to be qemu (for seabios) + this.fw_value = i32(FW_CFG_SIGNATURE_QEMU); + } + else if(value === FW_CFG_ID) + { + this.fw_value = i32(0); + } + else if(value === FW_CFG_RAM_SIZE) + { + this.fw_value = i32(this.memory_size[0]); + } + else if(value === FW_CFG_NB_CPUS) + { + this.fw_value = i32(1); + } + else if(value === FW_CFG_MAX_CPUS) + { + this.fw_value = i32(1); + } + else if(value === FW_CFG_NUMA) + { + this.fw_value = new Uint8Array(16); + } + else if(value === FW_CFG_FILE_DIR) + { + const buffer_size = 4 + 64 * this.option_roms.length; + const buffer32 = new Int32Array(buffer_size); + const buffer8 = new Uint8Array(buffer32.buffer); + + buffer32[0] = to_be32(this.option_roms.length); + + for(let i = 0; i < this.option_roms.length; i++) + { + const { name, data } = this.option_roms[i]; + const file_struct_ptr = 4 + 64 * i; + + dbg_assert(FW_CFG_FILE_START + i < 0x10000); + buffer32[file_struct_ptr + 0 >> 2] = to_be32(data.length); + buffer32[file_struct_ptr + 4 >> 2] = to_be16(FW_CFG_FILE_START + i); + + dbg_assert(name.length < 64 - 8); + + for(let j = 0; j < name.length; j++) + { + buffer8[file_struct_ptr + 8 + j] = name.charCodeAt(j); + } + } + + this.fw_value = buffer8; + } + else if(value >= FW_CFG_CUSTOM_START && value < FW_CFG_FILE_START) + { + this.fw_value = i32(0); + } + else if(value >= FW_CFG_FILE_START && value - FW_CFG_FILE_START < this.option_roms.length) + { + const i = value - FW_CFG_FILE_START; + this.fw_value = this.option_roms[i].data; + } + else + { + dbg_log("Warning: Unimplemented fw index: " + h(value)); + this.fw_value = i32(0); + } + }); + + if(DEBUG) + { + // Avoid logging noisey ports + io.register_write(0x80, this, function(out_byte) {}); + io.register_read(0x80, this, function() { return 0xFF; }); + io.register_write(0xE9, this, function(out_byte) {}); + } + + this.devices = {}; + + // TODO: Make this more configurable + if(settings.load_devices) + { + this.devices.pic = new PIC(this); + this.devices.pci = new PCI(this); + + if(this.acpi_enabled[0]) + { + this.devices.ioapic = new IOAPIC(this); + this.devices.apic = new APIC(this); + this.devices.acpi = new ACPI(this); + } + + this.devices.rtc = new RTC(this); + this.fill_cmos(this.devices.rtc, settings); + + this.devices.dma = new DMA(this); + + if(ENABLE_HPET) + { + this.devices.hpet = new HPET(this); + } + + this.devices.vga = new VGAScreen(this, device_bus, + settings.vga_memory_size || 8 * 1024 * 1024); + + this.devices.ps2 = new PS2(this, device_bus); + + this.devices.uart0 = new UART(this, 0x3F8, device_bus); + + if(settings.uart1) + { + this.devices.uart1 = new UART(this, 0x2F8, device_bus); + } + if(settings.uart2) + { + this.devices.uart2 = new UART(this, 0x3E8, device_bus); + } + if(settings.uart3) + { + this.devices.uart3 = new UART(this, 0x2E8, device_bus); + } + + this.devices.fdc = new FloppyController(this, settings.fda, settings.fdb); + + var ide_device_count = 0; + + if(settings.hda) + { + this.devices.hda = new IDEDevice(this, settings.hda, settings.hdb, false, ide_device_count++, device_bus); + } + + if(settings.cdrom) + { + this.devices.cdrom = new IDEDevice(this, settings.cdrom, undefined, true, ide_device_count++, device_bus); + } + + this.devices.pit = new PIT(this, device_bus); + + if(settings.enable_ne2k) + { + this.devices.net = new Ne2k(this, device_bus, settings.preserve_mac_from_state_image, settings.mac_address_translation); + } + + if(settings.fs9p) + { + this.devices.virtio_9p = new Virtio9p(settings.fs9p, this, device_bus); + } + + if(true) + { + this.devices.sb16 = new SB16(this, device_bus); + } + } + + if(settings.multiboot) + { + this.load_multiboot(settings.multiboot); + } + + if(DEBUG) + { + this.debug.init(); + } +}; + +CPU.prototype.load_multiboot = function(buffer) +{ + // https://www.gnu.org/software/grub/manual/multiboot/multiboot.html + + dbg_log("Trying multiboot from buffer of size " + buffer.byteLength, LOG_CPU); + + const MAGIC = 0x1BADB002; + const ELF_MAGIC = 0x464C457F; + const MULTIBOOT_HEADER_ADDRESS = 0x10000; + const MULTIBOOT_SEARCH_BYTES = 8192; + + if(buffer.byteLength < MULTIBOOT_SEARCH_BYTES) + { + var buf32 = new Int32Array(MULTIBOOT_SEARCH_BYTES / 4); + new Uint8Array(buf32.buffer).set(new Uint8Array(buffer)); + } + else + { + var buf32 = new Int32Array(buffer, 0, MULTIBOOT_SEARCH_BYTES / 4); + } + + for(var offset = 0; offset < MULTIBOOT_SEARCH_BYTES; offset += 4) + { + if(buf32[offset >> 2] === MAGIC) + { + var flags = buf32[offset + 4 >> 2]; + var checksum = buf32[offset + 8 >> 2]; + var total = MAGIC + flags + checksum | 0; + + if(total) + { + dbg_log("Multiboot checksum check failed", LOG_CPU); + continue; + } + } + else + { + continue; + } + + dbg_log("Multiboot magic found, flags: " + h(flags >>> 0, 8), LOG_CPU); + dbg_assert((flags & ~MULTIBOOT_HEADER_ADDRESS) === 0, "TODO"); + + this.reg32[REG_EAX] = 0x2BADB002; + + let multiboot_info_addr = 0x7C00; + this.reg32[REG_EBX] = multiboot_info_addr; + this.write32(multiboot_info_addr, 0); + + this.cr[0] = 1; + this.protected_mode[0] = +true; + this.flags[0] = FLAGS_DEFAULT; + this.is_32[0] = +true; + this.stack_size_32[0] = +true; + + for(var i = 0; i < 6; i++) + { + this.segment_is_null[i] = 0; + this.segment_offsets[i] = 0; + this.segment_limits[i] = 0xFFFFFFFF; + + // Value doesn't matter, OS isn't allowed to reload without setting + // up a proper GDT + this.sreg[i] = 0xB002; + } + + if(flags & MULTIBOOT_HEADER_ADDRESS) + { + dbg_log("Multiboot specifies its own address table", LOG_CPU); + + var header_addr = buf32[offset + 12 >> 2]; + var load_addr = buf32[offset + 16 >> 2]; + var load_end_addr = buf32[offset + 20 >> 2]; + var bss_end_addr = buf32[offset + 24 >> 2]; + var entry_addr = buf32[offset + 28 >> 2]; + + dbg_log("header=" + h(header_addr, 8) + + " load=" + h(load_addr, 8) + + " load_end=" + h(load_end_addr, 8) + + " bss_end=" + h(bss_end_addr, 8) + + " entry=" + h(entry_addr, 8)); + + dbg_assert(load_addr <= header_addr); + + var file_start = offset - (header_addr - load_addr); + + if(load_end_addr === 0) + { + var length = undefined; + } + else + { + dbg_assert(load_end_addr >= load_addr); + var length = load_end_addr - load_addr; + } + + let blob = new Uint8Array(buffer, file_start, length); + this.write_blob(blob, load_addr); + + this.instruction_pointer[0] = this.get_seg_cs() + entry_addr | 0; + } + else if(buf32[0] === ELF_MAGIC) + { + dbg_log("Multiboot image is in elf format", LOG_CPU); + + let elf = read_elf(buffer); + + this.instruction_pointer[0] = this.get_seg_cs() + elf.header.entry | 0; + + for(let program of elf.program_headers) + { + if(program.type === 0) + { + // null + } + else if(program.type === 1) + { + // load + + // Since multiboot specifies that paging is disabled, + // virtual and physical address must be equal + dbg_assert(program.paddr === program.vaddr); + dbg_assert(program.filesz <= program.memsz); + + if(program.paddr + program.memsz < this.memory_size[0]) + { + if(program.filesz) // offset might be outside of buffer if filesz is 0 + { + let blob = new Uint8Array(buffer, program.offset, program.filesz); + this.write_blob(blob, program.paddr); + } + } + else + { + dbg_log("Warning: Skipped loading section, paddr=" + h(program.paddr) + " memsz=" + program.memsz, LOG_CPU); + } + } + else if( + program.type === 2 || + program.type === 3 || + program.type === 4 || + program.type === 6 || + program.type === 0x6474e550 || + program.type === 0x6474e551 || + program.type === 0x6474e553) + { + // ignore for now + } + else + { + dbg_assert(false, "unimplemented elf section type: " + h(program.type)); + } + } + } + else + { + dbg_assert(false, "Not a bootable multiboot format"); + } + + // only for kvm-unit-test + this.io.register_write_consecutive(0xF4, this, + function(value) + { + console.log("Test exited with code " + h(value, 2)); + throw "HALT"; + }, + function() {}, + function() {}, + function() {}); + + // only for kvm-unit-test + for(let i = 0; i <= 0xF; i++) + { + function handle_write(value) + { + dbg_log("kvm-unit-test: Set irq " + h(i) + " to " + h(value, 2)); + if(value) + { + this.device_raise_irq(i); + } + else + { + this.device_lower_irq(i); + } + } + + this.io.register_write(0x2000 + i, this, handle_write, handle_write, handle_write); + } + + this.update_state_flags(); + + dbg_log("Starting multiboot kernel at:", LOG_CPU); + this.debug.dump_state(); + this.debug.dump_regs(); + + break; + } +}; + +CPU.prototype.fill_cmos = function(rtc, settings) +{ + var boot_order = settings.boot_order || 0x213; + + // Used by seabios to determine the boot order + // Nibble + // 1: FloppyPrio + // 2: HDPrio + // 3: CDPrio + // 4: BEVPrio + // bootflag 1, high nibble, lowest priority + // Low nibble: Disable floppy signature check (1) + rtc.cmos_write(CMOS_BIOS_BOOTFLAG1 , 1 | boot_order >> 4 & 0xF0); + + // bootflag 2, both nibbles, high and middle priority + rtc.cmos_write(CMOS_BIOS_BOOTFLAG2, boot_order & 0xFF); + + // 640k or less if less memory is used + rtc.cmos_write(CMOS_MEM_BASE_LOW, 640 & 0xFF); + rtc.cmos_write(CMOS_MEM_BASE_HIGH, 640 >> 8); + + var memory_above_1m = 0; // in k + if(this.memory_size[0] >= 1024 * 1024) + { + memory_above_1m = (this.memory_size[0] - 1024 * 1024) >> 10; + memory_above_1m = Math.min(memory_above_1m, 0xFFFF); + } + + rtc.cmos_write(CMOS_MEM_OLD_EXT_LOW, memory_above_1m & 0xFF); + rtc.cmos_write(CMOS_MEM_OLD_EXT_HIGH, memory_above_1m >> 8 & 0xFF); + rtc.cmos_write(CMOS_MEM_EXTMEM_LOW, memory_above_1m & 0xFF); + rtc.cmos_write(CMOS_MEM_EXTMEM_HIGH, memory_above_1m >> 8 & 0xFF); + + var memory_above_16m = 0; // in 64k blocks + if(this.memory_size[0] >= 16 * 1024 * 1024) + { + memory_above_16m = (this.memory_size[0] - 16 * 1024 * 1024) >> 16; + memory_above_16m = Math.min(memory_above_16m, 0xFFFF); + } + rtc.cmos_write(CMOS_MEM_EXTMEM2_LOW, memory_above_16m & 0xFF); + rtc.cmos_write(CMOS_MEM_EXTMEM2_HIGH, memory_above_16m >> 8 & 0xFF); + + // memory above 4G (not supported by this emulator) + rtc.cmos_write(CMOS_MEM_HIGHMEM_LOW, 0); + rtc.cmos_write(CMOS_MEM_HIGHMEM_MID, 0); + rtc.cmos_write(CMOS_MEM_HIGHMEM_HIGH, 0); + + rtc.cmos_write(CMOS_EQUIPMENT_INFO, 0x2F); + + rtc.cmos_write(CMOS_BIOS_SMP_COUNT, 0); + + // Used by bochs BIOS to skip the boot menu delay. + if (settings.fastboot) rtc.cmos_write(0x3f, 0x01); +}; + +CPU.prototype.load_bios = function() +{ + var bios = this.bios.main; + var vga_bios = this.bios.vga; + + if(!bios) + { + dbg_log("Warning: No BIOS"); + return; + } + + // load bios + var data = new Uint8Array(bios), + start = 0x100000 - bios.byteLength; + + this.write_blob(data, start); + + if(vga_bios) + { + // load vga bios + var vga_bios8 = new Uint8Array(vga_bios); + + // older versions of seabios + this.write_blob(vga_bios8, 0xC0000); + + // newer versions of seabios (needs to match pci rom address, see vga.js) + this.io.mmap_register(0xFEB00000, 0x100000, + function(addr) + { + addr = (addr - 0xFEB00000) | 0; + if(addr < vga_bios8.length) + { + return vga_bios8[addr]; + } + else + { + return 0; + } + }, + function(addr, value) + { + dbg_assert(false, "Unexpected write to VGA rom"); + }); + } + else + { + dbg_log("Warning: No VGA BIOS"); + } + + // seabios expects the bios to be mapped to 0xFFF00000 also + this.io.mmap_register(0xFFF00000, 0x100000, + function(addr) + { + addr &= 0xFFFFF; + return this.mem8[addr]; + }.bind(this), + function(addr, value) + { + addr &= 0xFFFFF; + this.mem8[addr] = value; + }.bind(this)); +}; + +CPU.prototype.do_many_cycles = function() +{ + if(DEBUG) + { + var start_time = v86.microtick(); + } + + this.do_many_cycles_native(); + + if(DEBUG) + { + this.do_many_cycles_total += v86.microtick() - start_time; + this.do_many_cycles_count++; + } +}; + +/** @export */ +CPU.prototype.cycle = function() +{ + // XXX: May do several cycles + this.cycle_internal(); +}; + +CPU.prototype.codegen_finalize = function(wasm_table_index, start, state_flags, ptr, len) +{ + ptr >>>= 0; + len >>>= 0; + + dbg_assert(wasm_table_index >= 0 && wasm_table_index < WASM_TABLE_SIZE); + + const code = new Uint8Array(this.wasm_memory.buffer, ptr, len); + + if(DEBUG) + { + if(DUMP_GENERATED_WASM && !this.seen_code[start]) + { + this.debug.dump_wasm(code); + + const DUMP_ASSEMBLY = false; + + if(DUMP_ASSEMBLY) + { + let end = 0; + + if((start ^ end) & ~0xFFF) + { + dbg_log("truncated disassembly start=" + h(start >>> 0) + " end=" + h(end >>> 0)); + end = (start | 0xFFF) + 1; // until the end of the page + } + + dbg_assert(end >= start); + + const buffer = new Uint8Array(end - start); + + for(let i = start; i < end; i++) + { + buffer[i - start] = this.read8(i); + } + + this.debug.dump_code(this.is_32[0] ? 1 : 0, buffer, start); + } + } + + this.seen_code[start] = (this.seen_code[start] || 0) + 1; + + if(this.test_hook_did_generate_wasm) + { + this.test_hook_did_generate_wasm(code); + } + } + + const SYNC_COMPILATION = false; + + if(SYNC_COMPILATION) + { + const module = new WebAssembly.Module(code); + const result = new WebAssembly.Instance(module, { "e": this.jit_imports }); + const f = result.exports["f"]; + + this.wm.wasm_table.set(wasm_table_index + WASM_TABLE_OFFSET, f); + this.codegen_finalize_finished(wasm_table_index, start, state_flags); + + if(this.test_hook_did_finalize_wasm) + { + this.test_hook_did_finalize_wasm(code); + } + + return; + } + + const result = WebAssembly.instantiate(code, { "e": this.jit_imports }).then(result => { + const f = result.instance.exports["f"]; + + this.wm.wasm_table.set(wasm_table_index + WASM_TABLE_OFFSET, f); + this.codegen_finalize_finished(wasm_table_index, start, state_flags); + + if(this.test_hook_did_finalize_wasm) + { + this.test_hook_did_finalize_wasm(code); + } + }); + + if(DEBUG) + { + result.catch(e => { + console.log(e); + debugger; + throw e; + }); + } +}; + +CPU.prototype.log_uncompiled_code = function(start, end) +{ + if(!DEBUG || !DUMP_UNCOMPILED_ASSEMBLY) + { + return; + } + + if((this.seen_code_uncompiled[start] || 0) < 100) + { + this.seen_code_uncompiled[start] = (this.seen_code_uncompiled[start] || 0) + 1; + + end += 8; // final jump is not included + + if((start ^ end) & ~0xFFF) + { + dbg_log("truncated disassembly start=" + h(start >>> 0) + " end=" + h(end >>> 0)); + end = (start | 0xFFF) + 1; // until the end of the page + } + + if(end < start) end = start; + + dbg_assert(end >= start); + + const buffer = new Uint8Array(end - start); + + for(let i = start; i < end; i++) + { + buffer[i - start] = this.read8(i); + } + + dbg_log("Uncompiled code:"); + this.debug.dump_code(this.is_32[0] ? 1 : 0, buffer, start); + } +}; + +CPU.prototype.dump_function_code = function(block_ptr, count) +{ + if(!DEBUG || !DUMP_GENERATED_WASM) + { + return; + } + + const SIZEOF_BASIC_BLOCK_IN_DWORDS = 7; + + const mem32 = new Int32Array(this.wasm_memory.buffer); + + dbg_assert((block_ptr & 3) === 0); + + const is_32 = this.is_32[0]; + + for(let i = 0; i < count; i++) + { + const struct_start = (block_ptr >> 2) + i * SIZEOF_BASIC_BLOCK_IN_DWORDS; + const start = mem32[struct_start + 0]; + const end = mem32[struct_start + 1]; + const is_entry_block = mem32[struct_start + 6] & 0xFF00; + + const buffer = new Uint8Array(end - start); + + for(let i = start; i < end; i++) + { + buffer[i - start] = this.read8(this.translate_address_system_read(i)); + } + + dbg_log("---" + (is_entry_block ? " entry" : "")); + this.debug.dump_code(is_32 ? 1 : 0, buffer, start); + } +}; + +CPU.prototype.hlt_loop = function() +{ + if(this.get_eflags_no_arith() & FLAG_INTERRUPT) + { + const t = this.run_hardware_timers(v86.microtick()); + this.handle_irqs(); + return t; + } + else + { + return 100; + } +}; + +CPU.prototype.run_hardware_timers = function(now) +{ + if(ENABLE_HPET) + { + var pit_time = this.devices.pit.timer(now, this.devices.hpet.legacy_mode); + var rtc_time = this.devices.rtc.timer(now, this.devices.hpet.legacy_mode); + var hpet_time = this.devices.hpet.timer(now); + } + else + { + var pit_time = this.devices.pit.timer(now, false); + var rtc_time = this.devices.rtc.timer(now, false); + var hpet_time = 100; + } + + let acpi_time = 100; + let apic_time = 100; + if(this.acpi_enabled[0]) + { + acpi_time = this.devices.acpi.timer(now); + apic_time = this.devices.apic.timer(now); + } + + return Math.min(pit_time, rtc_time, hpet_time, acpi_time, apic_time); +}; + +CPU.prototype.hlt_op = function() +{ + if((this.get_eflags_no_arith() & FLAG_INTERRUPT) === 0) + { + // execution can never resume (until NMIs are supported) + this.bus.send("cpu-event-halt"); + } + + // get out of here and into hlt_loop + this.in_hlt[0] = +true; + + // Try an hlt loop right now: This will run timer interrupts, and if one is + // due it will immediately call call_interrupt_vector and continue + // execution without an unnecessary cycle through do_run + this.hlt_loop(); +}; + +CPU.prototype.handle_irqs = function() +{ + //dbg_assert(this.prefixes[0] === 0); + + if(this.get_eflags_no_arith() & FLAG_INTERRUPT) + { + this.pic_acknowledge(); + this.next_tick_immediately(); + } +}; + +CPU.prototype.pic_acknowledge = function() +{ + dbg_assert(this.get_eflags_no_arith() & FLAG_INTERRUPT); + + if(this.devices.pic) + { + this.devices.pic.acknowledge_irq(); + } + + if(this.devices.apic) + { + this.devices.apic.acknowledge_irq(); + } +}; + +CPU.prototype.device_raise_irq = function(i) +{ + dbg_assert(arguments.length === 1); + if(this.devices.pic) + { + this.devices.pic.set_irq(i); + } + + if(this.devices.ioapic) + { + this.devices.ioapic.set_irq(i); + } +}; + +CPU.prototype.device_lower_irq = function(i) +{ + if(this.devices.pic) + { + this.devices.pic.clear_irq(i); + } + + if(this.devices.ioapic) + { + this.devices.ioapic.clear_irq(i); + } +}; + +// Closure Compiler's way of exporting +if(typeof window !== "undefined") +{ + window["CPU"] = CPU; +} +else if(typeof module !== "undefined" && typeof module.exports !== "undefined") +{ + module.exports["CPU"] = CPU; +} +else if(typeof importScripts === "function") +{ + self["CPU"] = CPU; +} diff --git a/src/debug.js b/src/debug.js new file mode 100644 index 0000000..1fd6e45 --- /dev/null +++ b/src/debug.js @@ -0,0 +1,664 @@ +"use strict"; + +CPU.prototype.debug_init = function() +{ + var cpu = this; + var debug = {}; + this.debug = debug; + + debug.init = function() + { + if(!DEBUG) return; + + if(cpu.io) + { + // write seabios debug output to console + var seabios_debug = ""; + + cpu.io.register_write(0x402, this, handle); // seabios + cpu.io.register_write(0x500, this, handle); // vgabios + } + + function handle(out_byte) + { + if(out_byte === 10) + { + dbg_log(seabios_debug, LOG_BIOS); + seabios_debug = ""; + } + else + { + seabios_debug += String.fromCharCode(out_byte); + } + } + }; + + debug.get_regs_short = get_regs_short; + debug.dump_regs = dump_regs_short; + debug.get_state = get_state; + debug.dump_state = dump_state; + debug.dump_stack = dump_stack; + + debug.dump_page_structures = dump_page_structures; + debug.dump_gdt_ldt = dump_gdt_ldt; + debug.dump_idt = dump_idt; + + debug.get_memory_dump = get_memory_dump; + debug.memory_hex_dump = memory_hex_dump; + debug.used_memory_dump = used_memory_dump; + + function dump_stack(start, end) + { + if(!DEBUG) return; + + var esp = cpu.reg32[REG_ESP]; + dbg_log("========= STACK =========="); + + if(end >= start || end === undefined) + { + start = 5; + end = -5; + } + + for(var i = start; i > end; i--) + { + var line = " "; + + if(!i) line = "=> "; + + line += h(i, 2) + " | "; + + dbg_log(line + h(esp + 4 * i, 8) + " | " + h(cpu.read32s(esp + 4 * i) >>> 0)); + } + } + + function get_state(where) + { + if(!DEBUG) return; + + var mode = cpu.protected_mode[0] ? "prot" : "real"; + var vm = (cpu.flags[0] & FLAG_VM) ? 1 : 0; + var flags = cpu.get_eflags(); + var iopl = cpu.getiopl(); + var cpl = cpu.cpl[0]; + var cs_eip = h(cpu.sreg[REG_CS], 4) + ":" + h(cpu.get_real_eip() >>> 0, 8); + var ss_esp = h(cpu.sreg[REG_SS], 4) + ":" + h(cpu.reg32[REG_ES] >>> 0, 8); + var op_size = cpu.is_32[0] ? "32" : "16"; + var if_ = (cpu.flags[0] & FLAG_INTERRUPT) ? 1 : 0; + + var flag_names = { + [FLAG_CARRY]: "c", + [FLAG_PARITY]: "p", + [FLAG_ADJUST]: "a", + [FLAG_ZERO]: "z", + [FLAG_SIGN]: "s", + [FLAG_TRAP]: "t", + [FLAG_INTERRUPT]: "i", + [FLAG_DIRECTION]: "d", + [FLAG_OVERFLOW]: "o", + }; + var flag_string = ""; + + for(var i = 0; i < 16; i++) + { + if(flag_names[1 << i]) + { + if(flags & 1 << i) + { + flag_string += flag_names[1 << i]; + } + else + { + flag_string += " "; + } + } + } + + return ("mode=" + mode + "/" + op_size + " paging=" + (+((cpu.cr[0] & CR0_PG) !== 0)) + + " pae=" + (+((cpu.cr[4] & CR4_PAE) !== 0)) + + " iopl=" + iopl + " cpl=" + cpl + " if=" + if_ + " cs:eip=" + cs_eip + + " cs_off=" + h(cpu.get_seg_cs() >>> 0, 8) + + " flgs=" + h(cpu.get_eflags() >>> 0, 6) + " (" + flag_string + ")" + + " ss:esp=" + ss_esp + + " ssize=" + (+cpu.stack_size_32[0]) + + (where ? " in " + where : "")); + } + + function dump_state(where) + { + if(!DEBUG) return; + + dbg_log(get_state(where), LOG_CPU); + } + + function get_regs_short() + { + if(!DEBUG) return; + + var + r32 = { "eax": REG_EAX, "ecx": REG_ECX, "edx": REG_EDX, "ebx": REG_EBX, + "esp": REG_ESP, "ebp": REG_EBP, "esi": REG_ESI, "edi": REG_EDI }, + r32_names = ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"], + s = { "cs": REG_CS, "ds": REG_DS, "es": REG_ES, "fs": REG_FS, "gs": REG_GS, "ss": REG_SS }, + line1 = "", + line2 = ""; + + + + for(var i = 0; i < 4; i++) + { + line1 += r32_names[i] + "=" + h(cpu.reg32[r32[r32_names[i]]] >>> 0, 8) + " "; + line2 += r32_names[i+4] + "=" + h(cpu.reg32[r32[r32_names[i+4]]] >>> 0, 8) + " "; + } + + //line1 += " eip=" + h(cpu.get_real_eip() >>> 0, 8); + //line2 += " flg=" + h(cpu.get_eflags(), 8); + + line1 += " ds=" + h(cpu.sreg[REG_DS], 4) + " es=" + h(cpu.sreg[REG_ES], 4) + " fs=" + h(cpu.sreg[REG_FS], 4); + line2 += " gs=" + h(cpu.sreg[REG_GS], 4) + " cs=" + h(cpu.sreg[REG_CS], 4) + " ss=" + h(cpu.sreg[REG_SS], 4); + + return [line1, line2]; + } + + function dump_regs_short() + { + if(!DEBUG) return; + + var lines = get_regs_short(); + + dbg_log(lines[0], LOG_CPU); + dbg_log(lines[1], LOG_CPU); + } + + function dump_gdt_ldt() + { + if(!DEBUG) return; + + dbg_log("gdt: (len = " + h(cpu.gdtr_size[0]) + ")"); + dump_table(cpu.translate_address_system_read(cpu.gdtr_offset[0]), cpu.gdtr_size[0]); + + dbg_log("\nldt: (len = " + h(cpu.segment_limits[REG_LDTR]) + ")"); + dump_table(cpu.translate_address_system_read(cpu.segment_offsets[REG_LDTR]), cpu.segment_limits[REG_LDTR]); + + function dump_table(addr, size) + { + for(var i = 0; i < size; i += 8, addr += 8) + { + var base = cpu.read16(addr + 2) | + cpu.read8(addr + 4) << 16 | + cpu.read8(addr + 7) << 24, + + limit = cpu.read16(addr) | (cpu.read8(addr + 6) & 0xF) << 16, + access = cpu.read8(addr + 5), + flags = cpu.read8(addr + 6) >> 4, + flags_str = "", + dpl = access >> 5 & 3; + + if(!(access & 128)) + { + // present bit not set + //continue; + flags_str += "NP "; + } + else + { + flags_str += " P "; + } + + if(access & 16) + { + if(flags & 4) + { + flags_str += "32b "; + } + else + { + flags_str += "16b "; + } + + if(access & 8) + { + // executable + flags_str += "X "; + + if(access & 4) + { + flags_str += "C "; + } + } + else + { + // data + flags_str += "R "; + } + + flags_str += "RW "; + } + else + { + // system + flags_str += "sys: " + h(access & 15); + } + + if(flags & 8) + { + limit = limit << 12 | 0xFFF; + } + + dbg_log(h(i & ~7, 4) + " " + h(base >>> 0, 8) + " (" + h(limit >>> 0, 8) + " bytes) " + + flags_str + "; dpl = " + dpl + ", a = " + access.toString(2) + + ", f = " + flags.toString(2)); + } + } + } + + function dump_idt() + { + if(!DEBUG) return; + + for(var i = 0; i < cpu.idtr_size[0]; i += 8) + { + var addr = cpu.translate_address_system_read(cpu.idtr_offset[0] + i), + base = cpu.read16(addr) | cpu.read16(addr + 6) << 16, + selector = cpu.read16(addr + 2), + type = cpu.read8(addr + 5), + line, + dpl = type >> 5 & 3; + + if((type & 31) === 5) + { + line = "task gate "; + } + else if((type & 31) === 14) + { + line = "intr gate "; + } + else if((type & 31) === 15) + { + line = "trap gate "; + } + else + { + line = "invalid "; + } + + + if(type & 128) + { + line += " P"; + } + else + { + // present bit not set + //continue; + line += "NP"; + } + + + dbg_log(h(i >> 3, 4) + " " + h(base >>> 0, 8) + ", " + + h(selector, 4) + "; " + line + "; dpl = " + dpl + ", t = " + type.toString(2)); + } + } + + function load_page_entry(dword_entry, pae, is_directory) + { + if(!DEBUG) return; + + if(!(dword_entry & 1)) + { + // present bit not set + return false; + } + + var size = (dword_entry & 128) === 128, + address; + + if(size && !is_directory) + { + address = dword_entry & (pae ? 0xFFE00000 : 0xFFC00000); + } + else + { + address = dword_entry & 0xFFFFF000; + } + + return { + size: size, + global: (dword_entry & 256) === 256, + accessed: (dword_entry & 0x20) === 0x20, + dirty: (dword_entry & 0x40) === 0x40, + cache_disable : (dword_entry & 16) === 16, + user : (dword_entry & 4) === 4, + read_write : (dword_entry & 2) === 2, + address : address >>> 0 + }; + } + + function dump_page_structures() { + var pae = !!(cpu.cr[4] & CR4_PAE); + if (pae) + { + dbg_log("PAE enabled"); + + for (var i = 0; i < 4; i++) { + var addr = cpu.cr[3] + 8 * i; + var dword = cpu.read32s(addr); + if (dword & 1) + { + dump_page_directory(dword & 0xFFFFF000, true, i << 30); + } + } + } + else + { + dbg_log("PAE disabled"); + dump_page_directory(cpu.cr[3], false, 0); + } + } + + /* NOTE: PAE entries are 64-bits, we ignore the high half here. */ + function dump_page_directory(pd_addr, pae, start) + { + if(!DEBUG) return; + + var n = pae ? 512 : 1024; + var entry_size = pae ? 8 : 4; + var pd_shift = pae ? 21 : 22; + + for(var i = 0; i < n; i++) + { + var addr = pd_addr + i * entry_size, + dword = cpu.read32s(addr), + entry = load_page_entry(dword, pae, true); + + if(!entry) + { + continue; + } + + var flags = ""; + + flags += entry.size ? "S " : " "; + flags += entry.accessed ? "A " : " "; + flags += entry.cache_disable ? "Cd " : " "; + flags += entry.user ? "U " : " "; + flags += entry.read_write ? "Rw " : " "; + + if(entry.size) + { + dbg_log("=== " + h(start + (i << pd_shift) >>> 0, 8) + " -> " + + h(entry.address >>> 0, 8) + " | " + flags); + continue; + } + else + { + dbg_log("=== " + h(start + (i << pd_shift) >>> 0, 8) + " | " + flags); + } + + for(var j = 0; j < n; j++) + { + var sub_addr = entry.address + j * entry_size; + dword = cpu.read32s(sub_addr); + + var subentry = load_page_entry(dword, pae, false); + + if(subentry) + { + flags = ""; + + flags += subentry.cache_disable ? "Cd " : " "; + flags += subentry.user ? "U " : " "; + flags += subentry.read_write ? "Rw " : " "; + flags += subentry.global ? "G " : " "; + flags += subentry.accessed ? "A " : " "; + flags += subentry.dirty ? "Di " : " "; + + dbg_log("# " + h(start + (i << pd_shift | j << 12) >>> 0, 8) + " -> " + + h(subentry.address, 8) + " | " + flags + " (at " + h(sub_addr, 8) + ")"); + } + } + } + } + + + function get_memory_dump(start, count) + { + if(!DEBUG) return; + + if(start === undefined) + { + start = 0; + count = cpu.memory_size[0]; + } + else if(count === undefined) + { + count = start; + start = 0; + } + + return cpu.mem8.slice(start, start + count).buffer; + } + + + function memory_hex_dump(addr, length) + { + if(!DEBUG) return; + + length = length || 4 * 0x10; + var line, byt; + + for(var i = 0; i < length >> 4; i++) + { + line = h(addr + (i << 4), 5) + " "; + + for(var j = 0; j < 0x10; j++) + { + byt = cpu.read8(addr + (i << 4) + j); + line += h(byt, 2) + " "; + } + + line += " "; + + for(j = 0; j < 0x10; j++) + { + byt = cpu.read8(addr + (i << 4) + j); + line += (byt < 33 || byt > 126) ? "." : String.fromCharCode(byt); + } + + dbg_log(line); + } + } + + function used_memory_dump() + { + if(!DEBUG) return; + + var width = 0x80, + height = 0x10, + block_size = cpu.memory_size[0] / width / height | 0, + row; + + for(var i = 0; i < height; i++) + { + row = h(i * width * block_size, 8) + " | "; + + for(var j = 0; j < width; j++) + { + var used = cpu.mem32s[(i * width + j) * block_size] > 0; + + row += used ? "X" : " "; + } + + dbg_log(row); + } + } + + + debug.debug_interrupt = function(interrupt_nr) + { + //if(interrupt_nr === 0x20) + //{ + // //var vxd_device = cpu.safe_read16(cpu.instruction_pointer + 2); + // //var vxd_sub = cpu.safe_read16(cpu.instruction_pointer + 0); + // //var service = ""; + // //if(vxd_device === 1) + // //{ + // // service = vxd_table1[vxd_sub]; + // //} + // //dbg_log("vxd: " + h(vxd_device, 4) + " " + h(vxd_sub, 4) + " " + service); + //} + + //if(interrupt_nr >= 0x21 && interrupt_nr < 0x30) + //{ + // dbg_log("dos: " + h(interrupt_nr, 2) + " ah=" + h(this.reg8[reg_ah], 2) + " ax=" + h(this.reg16[reg_ax], 4)); + //} + + //if(interrupt_nr === 0x13 && (this.reg8[reg_ah] | 1) === 0x43) + //{ + // this.debug.memory_hex_dump(this.get_seg(reg_ds) + this.reg16[reg_si], 0x18); + //} + + //if(interrupt_nr == 0x10) + //{ + // dbg_log("int10 ax=" + h(this.reg16[reg_ax], 4) + " '" + String.fromCharCode(this.reg8[reg_al]) + "'"); + // this.debug.dump_regs_short(); + // if(this.reg8[reg_ah] == 0xe) vga.tt_write(this.reg8[reg_al]); + //} + + //if(interrupt_nr === 0x13) + //{ + // this.debug.dump_regs_short(); + //} + + //if(interrupt_nr === 6) + //{ + // this.instruction_pointer += 2; + // dbg_log("BUG()", LOG_CPU); + // dbg_log("line=" + this.read_imm16() + " " + + // "file=" + this.read_string(this.translate_address_read(this.read_imm32s())), LOG_CPU); + // this.instruction_pointer -= 8; + // this.debug.dump_regs_short(); + //} + + //if(interrupt_nr === 0x80) + //{ + // dbg_log("linux syscall"); + // this.debug.dump_regs_short(); + //} + + //if(interrupt_nr === 0x40) + //{ + // dbg_log("kolibri syscall"); + // this.debug.dump_regs_short(); + //} + }; + + let cs; + let capstone_decoder; + + debug.dump_code = function(is_32, buffer, start) + { + if(!capstone_decoder) + { + if(cs === undefined) + { + if(typeof require === "function") + { + cs = require("./capstone-x86.min.js"); + } + else + { + cs = window.cs; + } + + if(cs === undefined) + { + dbg_log("Warning: Missing capstone library, disassembly not available"); + return; + } + } + + capstone_decoder = [ + new cs.Capstone(cs.ARCH_X86, cs.MODE_16), + new cs.Capstone(cs.ARCH_X86, cs.MODE_32), + ]; + } + + try + { + const instructions = capstone_decoder[is_32].disasm(buffer, start); + + instructions.forEach(function (instr) { + dbg_log(h(instr.address >>> 0) + ": " + + v86util.pads(instr.bytes.map(x => h(x, 2).slice(-2)).join(" "), 20) + " " + + instr.mnemonic + " " + instr.op_str); + }); + dbg_log(""); + } + catch(e) + { + dbg_log("Could not disassemble: " + Array.from(buffer).map(x => h(x, 2)).join(" ")); + } + }; + + function dump_file(ab, name) + { + var blob = new Blob([ab]); + + var a = document.createElement("a"); + a["download"] = name; + a.href = window.URL.createObjectURL(blob); + a.dataset["downloadurl"] = ["application/octet-stream", a["download"], a.href].join(":"); + + a.click(); + window.URL.revokeObjectURL(a.src); + } + + let wabt; + + debug.dump_wasm = function(buffer) + { + if(wabt === undefined) + { + if(typeof require === "function") + { + wabt = require("./libwabt.js"); + } + else + { + wabt = new window.WabtModule; + } + + if(wabt === undefined) + { + dbg_log("Warning: Missing libwabt, wasm dump not available"); + return; + } + } + + // Need to make a small copy otherwise libwabt goes nuts trying to copy + // the whole underlying buffer + buffer = buffer.slice(); + + try + { + var module = wabt.readWasm(buffer, { readDebugNames: false }); + module.generateNames(); + module.applyNames(); + const result = module.toText({ foldExprs: true, inlineExport: true }); + dbg_log(result); + } + catch(e) + { + dump_file(buffer, "failed.wasm"); + console.log(e.toString()); + } + finally + { + if(module) + { + module.destroy(); + } + } + }; +}; diff --git a/src/dma.js b/src/dma.js new file mode 100644 index 0000000..4283bde --- /dev/null +++ b/src/dma.js @@ -0,0 +1,424 @@ +"use strict"; + +/** + * @constructor + * @param {CPU} cpu + */ +function DMA(cpu) +{ + /** @const @type {CPU} */ + this.cpu = cpu; + + this.channel_page = new Uint8Array(8); + this.channel_pagehi = new Uint8Array(8); + this.channel_addr = new Uint16Array(8); + this.channel_addr_init = new Uint16Array(8); + this.channel_count = new Uint16Array(8); + this.channel_count_init = new Uint16Array(8); + this.channel_mask = new Uint8Array(8); + this.channel_mode = new Uint8Array(8); + this.unmask_listeners = []; + + this.lsb_msb_flipflop = 0; + + var io = cpu.io; + + io.register_write(0x00, this, this.port_addr_write.bind(this, 0)); + io.register_write(0x02, this, this.port_addr_write.bind(this, 1)); + io.register_write(0x04, this, this.port_addr_write.bind(this, 2)); + io.register_write(0x06, this, this.port_addr_write.bind(this, 3)); + io.register_write(0x01, this, this.port_count_write.bind(this, 0)); + io.register_write(0x03, this, this.port_count_write.bind(this, 1)); + io.register_write(0x05, this, this.port_count_write.bind(this, 2)); + io.register_write(0x07, this, this.port_count_write.bind(this, 3)); + + io.register_read(0x00, this, this.port_addr_read.bind(this, 0)); + io.register_read(0x02, this, this.port_addr_read.bind(this, 1)); + io.register_read(0x04, this, this.port_addr_read.bind(this, 2)); + io.register_read(0x06, this, this.port_addr_read.bind(this, 3)); + io.register_read(0x01, this, this.port_count_read.bind(this, 0)); + io.register_read(0x03, this, this.port_count_read.bind(this, 1)); + io.register_read(0x05, this, this.port_count_read.bind(this, 2)); + io.register_read(0x07, this, this.port_count_read.bind(this, 3)); + + io.register_write(0xC0, this, this.port_addr_write.bind(this, 4)); + io.register_write(0xC4, this, this.port_addr_write.bind(this, 5)); + io.register_write(0xC8, this, this.port_addr_write.bind(this, 6)); + io.register_write(0xCC, this, this.port_addr_write.bind(this, 7)); + io.register_write(0xC2, this, this.port_count_write.bind(this, 4)); + io.register_write(0xC6, this, this.port_count_write.bind(this, 5)); + io.register_write(0xCA, this, this.port_count_write.bind(this, 6)); + io.register_write(0xCE, this, this.port_count_write.bind(this, 7)); + + io.register_read(0xC0, this, this.port_addr_read.bind(this, 4)); + io.register_read(0xC4, this, this.port_addr_read.bind(this, 5)); + io.register_read(0xC8, this, this.port_addr_read.bind(this, 6)); + io.register_read(0xCC, this, this.port_addr_read.bind(this, 7)); + io.register_read(0xC2, this, this.port_count_read.bind(this, 4)); + io.register_read(0xC6, this, this.port_count_read.bind(this, 5)); + io.register_read(0xCA, this, this.port_count_read.bind(this, 6)); + io.register_read(0xCE, this, this.port_count_read.bind(this, 7)); + + io.register_write(0x87, this, this.port_page_write.bind(this, 0)); + io.register_write(0x83, this, this.port_page_write.bind(this, 1)); + io.register_write(0x81, this, this.port_page_write.bind(this, 2)); + io.register_write(0x82, this, this.port_page_write.bind(this, 3)); + io.register_write(0x8F, this, this.port_page_write.bind(this, 4)); + io.register_write(0x8B, this, this.port_page_write.bind(this, 5)); + io.register_write(0x89, this, this.port_page_write.bind(this, 6)); + io.register_write(0x8A, this, this.port_page_write.bind(this, 7)); + + io.register_read(0x87, this, this.port_page_read.bind(this, 0)); + io.register_read(0x83, this, this.port_page_read.bind(this, 1)); + io.register_read(0x81, this, this.port_page_read.bind(this, 2)); + io.register_read(0x82, this, this.port_page_read.bind(this, 3)); + io.register_read(0x8F, this, this.port_page_read.bind(this, 4)); + io.register_read(0x8B, this, this.port_page_read.bind(this, 5)); + io.register_read(0x89, this, this.port_page_read.bind(this, 6)); + io.register_read(0x8A, this, this.port_page_read.bind(this, 7)); + + io.register_write(0x487, this, this.port_pagehi_write.bind(this, 0)); + io.register_write(0x483, this, this.port_pagehi_write.bind(this, 1)); + io.register_write(0x481, this, this.port_pagehi_write.bind(this, 2)); + io.register_write(0x482, this, this.port_pagehi_write.bind(this, 3)); + io.register_write(0x48B, this, this.port_pagehi_write.bind(this, 5)); + io.register_write(0x489, this, this.port_pagehi_write.bind(this, 6)); + io.register_write(0x48A, this, this.port_pagehi_write.bind(this, 7)); + + io.register_read(0x487, this, this.port_pagehi_read.bind(this, 0)); + io.register_read(0x483, this, this.port_pagehi_read.bind(this, 1)); + io.register_read(0x481, this, this.port_pagehi_read.bind(this, 2)); + io.register_read(0x482, this, this.port_pagehi_read.bind(this, 3)); + io.register_read(0x48B, this, this.port_pagehi_read.bind(this, 5)); + io.register_read(0x489, this, this.port_pagehi_read.bind(this, 6)); + io.register_read(0x48A, this, this.port_pagehi_read.bind(this, 7)); + + io.register_write(0x0A, this, this.port_singlemask_write.bind(this, 0)); + io.register_write(0xD4, this, this.port_singlemask_write.bind(this, 4)); + io.register_write(0x0F, this, this.port_multimask_write.bind(this, 0)); + io.register_write(0xDE, this, this.port_multimask_write.bind(this, 4)); + + io.register_read(0x0F, this, this.port_multimask_read.bind(this, 0)); + io.register_read(0xDE, this, this.port_multimask_read.bind(this, 4)); + + io.register_write(0x0B, this, this.port_mode_write.bind(this, 0)); + io.register_write(0xD6, this, this.port_mode_write.bind(this, 4)); + + io.register_write(0x0C, this, this.portC_write); + io.register_write(0xD8, this, this.portC_write); +} + +DMA.prototype.get_state = function() +{ + return [ + this.channel_page, + this.channel_pagehi, + this.channel_addr, + this.channel_addr_init, + this.channel_count, + this.channel_count_init, + this.channel_mask, + this.channel_mode, + this.lsb_msb_flipflop, + ]; +}; + +DMA.prototype.set_state = function(state) +{ + this.channel_page = state[0]; + this.channel_pagehi = state[1]; + this.channel_addr = state[2]; + this.channel_addr_init = state[3]; + this.channel_count = state[4]; + this.channel_count_init = state[5]; + this.channel_mask = state[6]; + this.channel_mode = state[7]; + this.lsb_msb_flipflop = state[8]; +}; + +DMA.prototype.port_count_write = function(channel, data_byte) +{ + dbg_log("count write [" + channel + "] = " + h(data_byte), LOG_DMA); + + this.channel_count[channel] = + this.flipflop_get(this.channel_count[channel], data_byte, false); + + this.channel_count_init[channel] = + this.flipflop_get(this.channel_count_init[channel], data_byte, true); +}; + +DMA.prototype.port_count_read = function(channel) +{ + dbg_log("count read [" + channel + "] -> " + h(this.channel_count[channel]), LOG_DMA); + return this.flipflop_read(this.channel_count[channel]); +}; + +DMA.prototype.port_addr_write = function(channel, data_byte) +{ + dbg_log("addr write [" + channel + "] = " + h(data_byte), LOG_DMA); + + this.channel_addr[channel] = + this.flipflop_get(this.channel_addr[channel], data_byte, false); + + this.channel_addr_init[channel] = + this.flipflop_get(this.channel_addr_init[channel], data_byte, true); +}; + +DMA.prototype.port_addr_read = function(channel) +{ + dbg_log("addr read [" + channel + "] -> " + h(this.channel_addr[channel]), LOG_DMA); + return this.flipflop_read(this.channel_addr[channel]); +}; + +DMA.prototype.port_pagehi_write = function(channel, data_byte) +{ + dbg_log("pagehi write [" + channel + "] = " + h(data_byte), LOG_DMA); + this.channel_pagehi[channel] = data_byte; +}; + +DMA.prototype.port_pagehi_read = function(channel) +{ + dbg_log("pagehi read [" + channel + "]", LOG_DMA); + return this.channel_pagehi[channel]; +}; + +DMA.prototype.port_page_write = function(channel, data_byte) +{ + dbg_log("page write [" + channel + "] = " + h(data_byte), LOG_DMA); + this.channel_page[channel] = data_byte; +}; + +DMA.prototype.port_page_read = function(channel) +{ + dbg_log("page read [" + channel + "]", LOG_DMA); + return this.channel_page[channel]; +}; + +DMA.prototype.port_singlemask_write = function(channel_offset, data_byte) +{ + var channel = (data_byte & 0x3) + channel_offset; + var value = data_byte & 0x4 ? 1 : 0; + dbg_log("singlechannel mask write [" + channel + "] = " + value, LOG_DMA); + this.update_mask(channel, value); +}; + +DMA.prototype.port_multimask_write = function(channel_offset, data_byte) +{ + dbg_log("multichannel mask write: " + h(data_byte), LOG_DMA); + for(var i = 0; i < 4; i++) + { + this.update_mask(channel_offset + i, data_byte & (1 << i)); + } +}; + +DMA.prototype.port_multimask_read = function(channel_offset) +{ + var value = 0; + value |= this.channel_mask[channel_offset + 0]; + value |= this.channel_mask[channel_offset + 1] << 1; + value |= this.channel_mask[channel_offset + 2] << 2; + value |= this.channel_mask[channel_offset + 3] << 3; + dbg_log("multichannel mask read: " + h(value), LOG_DMA); + return value; +}; + +DMA.prototype.port_mode_write = function(channel_offset, data_byte) +{ + var channel = (data_byte & 0x3) + channel_offset; + dbg_log("mode write [" + channel + "] = " + h(data_byte), LOG_DMA); + this.channel_mode[channel] = data_byte; +}; + +DMA.prototype.portC_write = function(data_byte) +{ + dbg_log("flipflop reset", LOG_DMA); + this.lsb_msb_flipflop = 0; +}; + +DMA.prototype.on_unmask = function(fn, this_value) +{ + this.unmask_listeners.push({ + fn: fn, + this_value: this_value, + }); +}; + +DMA.prototype.update_mask = function(channel, value) +{ + if(this.channel_mask[channel] !== value) + { + this.channel_mask[channel] = value; + + if(!value) + { + dbg_log("firing on_unmask(" + channel + ")", LOG_DMA); + for(var i = 0; i < this.unmask_listeners.length; i++) + { + this.unmask_listeners[i].fn.call( + this.unmask_listeners[i].this_value, + channel + ); + } + } + } +}; + +// read data, write to memory +DMA.prototype.do_read = function(buffer, start, len, channel, fn) +{ + var read_count = this.count_get_8bit(channel), + addr = this.address_get_8bit(channel); + + dbg_log("DMA write channel " + channel, LOG_DMA); + dbg_log("to " + h(addr) + " len " + h(read_count), LOG_DMA); + + if(len < read_count) + { + dbg_log("DMA should read more than provided: " + h(len) + " " + h(read_count), LOG_DMA); + } + + if(start + read_count > buffer.byteLength) + { + dbg_log("DMA read outside of buffer", LOG_DMA); + fn(true); + } + else + { + var cpu = this.cpu; + this.channel_addr[channel] += read_count; + + buffer.get(start, read_count, function(data) + { + cpu.write_blob(data, addr); + fn(false); + }); + } +}; + +// write data, read memory +// start and len in bytes +DMA.prototype.do_write = function(buffer, start, len, channel, fn) +{ + var read_count = (this.channel_count[channel] + 1) & 0xFFFF, + bytes_per_count = channel >= 5 ? 2 : 1, + read_bytes = read_count * bytes_per_count, + addr = this.address_get_8bit(channel), + unfinished = false, + want_more = false, + autoinit = this.channel_mode[channel] & 0x10; + + dbg_log("DMA write channel " + channel, LOG_DMA); + dbg_log("to " + h(addr) + " len " + h(read_bytes), LOG_DMA); + + if(len < read_bytes) + { + dbg_log("DMA should read more than provided", LOG_DMA); + read_count = Math.floor(len / bytes_per_count); + read_bytes = read_count * bytes_per_count; + unfinished = true; + } + else if(len > read_bytes) + { + dbg_log("DMA attempted to read more than provided", LOG_DMA); + want_more = true; + } + + if(start + read_bytes > buffer.byteLength) + { + dbg_log("DMA write outside of buffer", LOG_DMA); + fn(true); + } + else + { + this.channel_addr[channel] += read_count; + this.channel_count[channel] -= read_count; + // when complete, counter should underflow to 0xFFFF + + if(!unfinished && autoinit) + { + dbg_log("DMA autoinit", LOG_DMA); + this.channel_addr[channel] = this.channel_addr_init[channel]; + this.channel_count[channel] = this.channel_count_init[channel]; + } + + buffer.set(start, + this.cpu.mem8.subarray(addr, addr + read_bytes), + () => + { + if(want_more && autoinit) + { + dbg_log("DMA continuing from start", LOG_DMA); + this.do_write(buffer, start + read_bytes, len - read_bytes, channel, fn); + } + else + { + fn(false); + } + } + ); + } +}; + +DMA.prototype.address_get_8bit = function(channel) +{ + var addr = this.channel_addr[channel]; + + // http://wiki.osdev.org/ISA_DMA#16_bit_issues + if(channel >= 5) + { + addr = (addr << 1); + } + + addr &= 0xFFFF; + addr |= this.channel_page[channel] << 16; + addr |= this.channel_pagehi[channel] << 24; + + return addr; +}; + +DMA.prototype.count_get_8bit = function(channel) +{ + var count = this.channel_count[channel] + 1; + + if(channel >= 5) + { + count *= 2; + } + + return count; +}; + +DMA.prototype.flipflop_get = function(old_dword, new_byte, continuing) +{ + if(!continuing) + { + this.lsb_msb_flipflop ^= 1; + } + + if(this.lsb_msb_flipflop) + { + // low byte + return old_dword & ~0xFF | new_byte; + } + else + { + // high byte + return old_dword & ~0xFF00 | new_byte << 8; + } +}; + +DMA.prototype.flipflop_read = function(dword) +{ + this.lsb_msb_flipflop ^= 1; + + if(this.lsb_msb_flipflop) + { + // low byte + return dword & 0xFF; + } + else + { + // high byte + return (dword >> 8) & 0xFF; + } +}; diff --git a/src/elf.js b/src/elf.js new file mode 100644 index 0000000..7f92708 --- /dev/null +++ b/src/elf.js @@ -0,0 +1,221 @@ +"use strict"; + +// A minimal elf parser for loading 32 bit, x86, little endian, executable elf files + +const ELF_MAGIC = 0x464C457F; + +let types = DataView.prototype; +let U8 = { size: 1, get: types.getUint8, set: types.setUint8, }; +let U16 = { size: 2, get: types.getUint16, set: types.setUint16, }; +let U32 = { size: 4, get: types.getUint32, set: types.setUint32, }; +let pad = function(size) +{ + return { + size, + get: offset => -1, + }; +}; + +let Header = create_struct([ + { magic: U32, }, + + { class: U8, }, + { data: U8, }, + { version0: U8, }, + { osabi: U8, }, + + { abiversion: U8, }, + { pad0: pad(7) }, + + { type: U16, }, + { machine: U16, }, + + { version1: U32, }, + { entry: U32, }, + { phoff: U32, }, + { shoff: U32, }, + { flags: U32, }, + + { ehsize: U16, }, + { phentsize: U16, }, + { phnum: U16, }, + { shentsize: U16, }, + { shnum: U16, }, + { shstrndx: U16, }, +]); +console.assert(Header.reduce((a, entry) => a + entry.size, 0) === 52); + +let ProgramHeader = create_struct([ + { type: U32, }, + { offset: U32, }, + { vaddr: U32, }, + { paddr: U32, }, + { filesz: U32, }, + { memsz: U32, }, + { flags: U32, }, + { align: U32, }, +]); +console.assert(ProgramHeader.reduce((a, entry) => a + entry.size, 0) === 32); + +let SectionHeader = create_struct([ + { name: U32, }, + { type: U32, }, + { flags: U32, }, + { addr: U32, }, + { offset: U32, }, + { size: U32, }, + { link: U32, }, + { info: U32, }, + { addralign: U32, }, + { entsize: U32, }, +]); +console.assert(SectionHeader.reduce((a, entry) => a + entry.size, 0) === 40); + + +// From [{ name: type }, ...] to [{ name, type, size, get, set }, ...] +function create_struct(struct) +{ + return struct.map(function(entry) + { + let keys = Object.keys(entry); + console.assert(keys.length === 1); + let name = keys[0]; + let type = entry[name]; + + console.assert(type.size > 0); + + return { + name, + type, + size: type.size, + get: type.get, + set: type.set, + }; + }); +} + +/** @param {ArrayBuffer} buffer */ +function read_elf(buffer) +{ + let view = new DataView(buffer); + + let [header, offset] = read_struct(view, Header); + console.assert(offset === 52); + + if(DEBUG) + { + for(let key of Object.keys(header)) + { + dbg_log(key + ": 0x" + (header[key].toString(16) >>> 0)); + } + } + + console.assert(header.magic === ELF_MAGIC, "Bad magic"); + console.assert(header.class === 1, "Unimplemented: 64 bit elf"); + console.assert(header.data === 1, "Unimplemented: big endian"); + console.assert(header.version0 === 1, "Bad version0"); + + // 1, 2, 3, 4 specify whether the object is relocatable, executable, + // shared, or core, respectively. + console.assert(header.type === 2, "Unimplemented type"); + + console.assert(header.version1 === 1, "Bad version1"); + + // these are different in 64 bit + console.assert(header.ehsize === 52, "Bad header size"); + console.assert(header.phentsize === 32, "Bad program header size"); + console.assert(header.shentsize === 40, "Bad section header size"); + + let [program_headers, ph_offset] = read_structs( + view_slice(view, header.phoff, header.phentsize * header.phnum), + ProgramHeader, + header.phnum); + + let [sections_headers, sh_offset] = read_structs( + view_slice(view, header.shoff, header.shentsize * header.shnum), + SectionHeader, + header.shnum); + + if(DEBUG && LOG_LEVEL) + { + console.log("%d program headers:", program_headers.length); + for(let program of program_headers) + { + console.log( + "type=%s offset=%s vaddr=%s paddr=%s " + + "filesz=%s memsz=%s flags=%s align=%s", + program.type.toString(16), + program.offset.toString(16), + program.vaddr.toString(16), + program.paddr.toString(16), + program.filesz.toString(16), + program.memsz.toString(16), + program.flags.toString(16), + program.align.toString(16) + ); + } + + console.log("%d program headers:", sections_headers.length); + for(let section of sections_headers) + { + console.log( + "name=%s type=%s flags=%s addr=%s offset=%s " + + "size=%s link=%s info=%s addralign=%s entsize=%s", + section.name.toString(16), + section.type.toString(16), + section.flags.toString(16), + section.addr.toString(16), + section.offset.toString(16), + section.size.toString(16), + section.link.toString(16), + section.info.toString(16), + section.addralign.toString(16), + section.entsize.toString(16) + ); + } + } + + return { + header, + program_headers, + sections_headers, + }; +} + +function read_struct(view, Struct) +{ + let result = {}; + let offset = 0; + const LITTLE_ENDIAN = true; // big endian not supported yet + + for(let entry of Struct) + { + let value = entry.get.call(view, offset, LITTLE_ENDIAN); + console.assert(result[entry.name] === undefined); + result[entry.name] = value; + offset += entry.size; + } + + return [result, offset]; +} + +function read_structs(view, Struct, count) +{ + let result = []; + let offset = 0; + + for(var i = 0; i < count; i++) + { + let [s, size] = read_struct(view_slice(view, offset), Struct); + result.push(s); + offset += size; + } + + return [result, offset]; +} + +/** @param {number=} length */ +function view_slice(view, offset, length) +{ + return new DataView(view.buffer, view.byteOffset + offset, length); +} diff --git a/src/externs.js b/src/externs.js new file mode 100644 index 0000000..057dfd0 --- /dev/null +++ b/src/externs.js @@ -0,0 +1,31 @@ +"use strict"; + +var global = {}; +var process = { hrtime: function() {} }; + +/** + * @param {string} name + * @param {function()} processor + */ +var registerProcessor = function(name, processor) {}; + +/** @const */ +var sampleRate = 0; + +var WabtModule = { + readWasm: function(buf, opt) {}, + generateNames: function() {}, + applyNames: function() {}, + toText: function() {}, +}; +var cs = { + Capstone: function() {}, + ARCH_X86: 0, + MODE_16: 0, + MODE_32: 0, + disasm: { bytes: "", mnemonic: "", op_str: "", }, +}; + +const Buffer = { + allocUnsafe : function(length) {}, +}; diff --git a/src/floppy.js b/src/floppy.js new file mode 100644 index 0000000..ee1f2fb --- /dev/null +++ b/src/floppy.js @@ -0,0 +1,459 @@ +"use strict"; + +/** + * @constructor + * + * @param {CPU} cpu + */ +function FloppyController(cpu, fda_image, fdb_image) +{ + /** @const @type {IO|undefined} */ + this.io = cpu.io; + + /** @const @type {CPU} */ + this.cpu = cpu; + + /** @const @type {DMA} */ + this.dma = cpu.devices.dma; + + this.bytes_expecting = 0; + this.receiving_command = new Uint8Array(10); + this.receiving_index = 0; + this.next_command = null; + + this.response_data = new Uint8Array(10); + this.response_index = 0; + this.response_length = 0; + + /* const */ + this.fda_image = fda_image; + + /* const */ + this.fdb_image = fdb_image; + + + this.status_reg0 = 0; + this.status_reg1 = 0; + this.status_reg2 = 0; + this.drive = 0; + + this.last_cylinder = 0; + this.last_head = 0; + this.last_sector = 1; + + // this should actually be write-only ... but people read it anyway + this.dor = 0; + + if(!fda_image) + { + // Needed for CD emulation provided by seabios + cpu.devices.rtc.cmos_write(CMOS_FLOPPY_DRIVE_TYPE, 4 << 4); + + this.sectors_per_track = 0; + this.number_of_heads = 0; + this.number_of_cylinders = 0; + } + else + { + var floppy_types = { + [ 160 * 1024] : { type: 1, tracks: 40, sectors: 8 , heads: 1 }, + [ 180 * 1024] : { type: 1, tracks: 40, sectors: 9 , heads: 1 }, + [ 200 * 1024] : { type: 1, tracks: 40, sectors: 10, heads: 1 }, + [ 320 * 1024] : { type: 1, tracks: 40, sectors: 8 , heads: 2 }, + [ 360 * 1024] : { type: 1, tracks: 40, sectors: 9 , heads: 2 }, + [ 400 * 1024] : { type: 1, tracks: 40, sectors: 10, heads: 2 }, + [ 720 * 1024] : { type: 3, tracks: 80, sectors: 9 , heads: 2 }, + [1200 * 1024] : { type: 2, tracks: 80, sectors: 15, heads: 2 }, + [1440 * 1024] : { type: 4, tracks: 80, sectors: 18, heads: 2 }, + [1722 * 1024] : { type: 5, tracks: 82, sectors: 21, heads: 2 }, + [2880 * 1024] : { type: 5, tracks: 80, sectors: 36, heads: 2 }, + + // not a real floppy type, used to support sectorlisp and friends + 512: { type: 1, tracks: 1, sectors: 1, heads: 1 }, + }; + + let floppy_size = fda_image.byteLength; + + var number_of_cylinders, + sectors_per_track, + number_of_heads, + floppy_type = floppy_types[floppy_size]; + + if(!floppy_type) + { + floppy_size = fda_image.byteLength > 1440 * 1024 ? 2880 * 1024 : 1440 * 1024; + floppy_type = floppy_types[floppy_size]; + + dbg_log("Warning: Unkown floppy size: " + fda_image.byteLength + ", assuming " + floppy_size); + } + + cpu.devices.rtc.cmos_write(CMOS_FLOPPY_DRIVE_TYPE, floppy_type.type << 4); + + sectors_per_track = floppy_type.sectors; + number_of_heads = floppy_type.heads; + number_of_cylinders = floppy_type.tracks; + + this.sectors_per_track = sectors_per_track; + this.number_of_heads = number_of_heads; + this.number_of_cylinders = number_of_cylinders; + } + + this.io.register_read(0x3F0, this, this.port3F0_read); + this.io.register_read(0x3F2, this, this.port3F2_read); + this.io.register_read(0x3F4, this, this.port3F4_read); + this.io.register_read(0x3F5, this, this.port3F5_read); + this.io.register_read(0x3F7, this, this.port3F7_read); + + this.io.register_write(0x3F2, this, this.port3F2_write); + this.io.register_write(0x3F5, this, this.port3F5_write); +} + +FloppyController.prototype.get_state = function() +{ + var state = []; + + state[0] = this.bytes_expecting; + state[1] = this.receiving_command; + state[2] = this.receiving_index; + //state[3] = this.next_command; + state[4] = this.response_data; + state[5] = this.response_index; + state[6] = this.response_length; + + state[8] = this.status_reg0; + state[9] = this.status_reg1; + state[10] = this.status_reg2; + state[11] = this.drive; + state[12] = this.last_cylinder; + state[13] = this.last_head; + state[14] = this.last_sector; + state[15] = this.dor; + state[16] = this.sectors_per_track; + state[17] = this.number_of_heads; + state[18] = this.number_of_cylinders; + + return state; +}; + +FloppyController.prototype.set_state = function(state) +{ + this.bytes_expecting = state[0]; + this.receiving_command = state[1]; + this.receiving_index = state[2]; + this.next_command = state[3]; + this.response_data = state[4]; + this.response_index = state[5]; + this.response_length = state[6]; + + this.status_reg0 = state[8]; + this.status_reg1 = state[9]; + this.status_reg2 = state[10]; + this.drive = state[11]; + this.last_cylinder = state[12]; + this.last_head = state[13]; + this.last_sector = state[14]; + this.dor = state[15]; + this.sectors_per_track = state[16]; + this.number_of_heads = state[17]; + this.number_of_cylinders = state[18]; +}; + +FloppyController.prototype.port3F0_read = function() +{ + dbg_log("3F0 read", LOG_FLOPPY); + + return 0; +}; + + +FloppyController.prototype.port3F4_read = function() +{ + dbg_log("3F4 read", LOG_FLOPPY); + + var return_byte = 0x80; + + if(this.response_index < this.response_length) + { + return_byte |= 0x40 | 0x10; + } + + if((this.dor & 8) === 0) + { + return_byte |= 0x20; + } + + return return_byte; +}; + +FloppyController.prototype.port3F7_read = function() +{ + dbg_log("3F7 read", LOG_FLOPPY); + return 0x00; +}; + +FloppyController.prototype.port3F5_read = function() +{ + if(this.response_index < this.response_length) + { + dbg_log("3F5 read: " + this.response_data[this.response_index], LOG_FLOPPY); + this.cpu.device_lower_irq(6); + return this.response_data[this.response_index++]; + } + else + { + dbg_log("3F5 read, empty", LOG_FLOPPY); + return 0xFF; + } +}; + +FloppyController.prototype.port3F5_write = function(reg_byte) +{ + if(!this.fda_image) return; + + dbg_log("3F5 write " + h(reg_byte), LOG_FLOPPY); + + if(this.bytes_expecting > 0) + { + this.receiving_command[this.receiving_index++] = reg_byte; + + this.bytes_expecting--; + + if(this.bytes_expecting === 0) + { + if(DEBUG) + { + var log = "3F5 command received: "; + for(var i = 0; i < this.receiving_index; i++) + log += h(this.receiving_command[i]) + " "; + dbg_log(log, LOG_FLOPPY); + } + + this.next_command.call(this, this.receiving_command); + } + } + else + { + switch(reg_byte) + { + // TODO + //case 2: + //this.next_command = read_complete_track; + //this.bytes_expecting = 8; + //break; + case 0x03: + this.next_command = this.fix_drive_data; + this.bytes_expecting = 2; + break; + case 0x04: + this.next_command = this.check_drive_status; + this.bytes_expecting = 1; + break; + case 0x05: + case 0x45: + case 0xC5: + this.next_command = function(args) { this.do_sector(true, args); }; + this.bytes_expecting = 8; + break; + case 0xE6: + this.next_command = function(args) { this.do_sector(false, args); }; + this.bytes_expecting = 8; + break; + case 0x07: + this.next_command = this.calibrate; + this.bytes_expecting = 1; + break; + case 0x08: + this.check_interrupt_status(); + break; + case 0x4A: + this.next_command = this.read_sector_id; + this.bytes_expecting = 1; + break; + case 0x0F: + this.bytes_expecting = 2; + this.next_command = this.seek; + break; + case 0x0E: + // dump regs + dbg_log("dump registers", LOG_FLOPPY); + this.response_data[0] = 0x80; + this.response_index = 0; + this.response_length = 1; + + this.bytes_expecting = 0; + break; + + default: + dbg_assert(false, "Unimplemented floppy command call " + h(reg_byte)); + } + + this.receiving_index = 0; + } +}; + +FloppyController.prototype.port3F2_read = function() +{ + dbg_log("read 3F2: DOR", LOG_FLOPPY); + return this.dor; +}; + +FloppyController.prototype.port3F2_write = function(value) +{ + if((value & 4) === 4 && (this.dor & 4) === 0) + { + // reset + this.cpu.device_raise_irq(6); + } + + dbg_log("start motors: " + h(value >> 4), LOG_FLOPPY); + dbg_log("enable dma: " + !!(value & 8), LOG_FLOPPY); + dbg_log("reset fdc: " + !!(value & 4), LOG_FLOPPY); + dbg_log("drive select: " + (value & 3), LOG_FLOPPY); + dbg_log("DOR = " + h(value), LOG_FLOPPY); + + this.dor = value; +}; + +FloppyController.prototype.check_drive_status = function(args) +{ + dbg_log("check drive status", LOG_FLOPPY); + + this.response_index = 0; + this.response_length = 1; + this.response_data[0] = 1 << 5; +}; + +FloppyController.prototype.seek = function(args) +{ + dbg_log("seek", LOG_FLOPPY); + dbg_assert((args[0] & 3) === 0, "Unhandled seek drive"); + + this.last_cylinder = args[1]; + this.last_head = args[0] >> 2 & 1; + + this.raise_irq(); +}; + +FloppyController.prototype.calibrate = function(args) +{ + dbg_log("floppy calibrate", LOG_FLOPPY); + + this.raise_irq(); +}; + +FloppyController.prototype.check_interrupt_status = function() +{ + // do not trigger an interrupt here + dbg_log("floppy check interrupt status", LOG_FLOPPY); + + this.response_index = 0; + this.response_length = 2; + + this.response_data[0] = 1 << 5; + this.response_data[1] = this.last_cylinder; +}; + +FloppyController.prototype.do_sector = function(is_write, args) +{ + var head = args[2], + cylinder = args[1], + sector = args[3], + sector_size = 128 << args[4], + read_count = args[5] - args[3] + 1, + + read_offset = ((head + this.number_of_heads * cylinder) * this.sectors_per_track + sector - 1) * sector_size; + + dbg_log("Floppy " + (is_write ? "Write" : "Read"), LOG_FLOPPY); + dbg_log("from " + h(read_offset) + " length " + h(read_count * sector_size), LOG_FLOPPY); + dbg_log(cylinder + " / " + head + " / " + sector, LOG_FLOPPY); + + if(!args[4]) + { + dbg_log("FDC: sector count is zero, use data length instead", LOG_FLOPPY); + } + + if(!this.fda_image) + { + return; + } + + if(is_write) + { + this.dma.do_write(this.fda_image, read_offset, read_count * sector_size, 2, this.done.bind(this, args, cylinder, head, sector)); + } + else + { + this.dma.do_read(this.fda_image, read_offset, read_count * sector_size, 2, this.done.bind(this, args, cylinder, head, sector)); + } +}; + +FloppyController.prototype.done = function(args, cylinder, head, sector, error) +{ + if(error) + { + // TODO: Set appropriate bits + return; + } + + sector++; + + if(sector > this.sectors_per_track) + { + sector = 1; + head++; + + if(head >= this.number_of_heads) + { + head = 0; + cylinder++; + } + } + + this.last_cylinder = cylinder; + this.last_head = head; + this.last_sector = sector; + + this.response_index = 0; + this.response_length = 7; + + this.response_data[0] = head << 2 | 0x20; + this.response_data[1] = 0; + this.response_data[2] = 0; + this.response_data[3] = cylinder; + this.response_data[4] = head; + this.response_data[5] = sector; + this.response_data[6] = args[4]; + + this.raise_irq(); +}; + +FloppyController.prototype.fix_drive_data = function(args) +{ + dbg_log("floppy fix drive data " + args, LOG_FLOPPY); +}; + +FloppyController.prototype.read_sector_id = function(args) +{ + dbg_log("floppy read sector id " + args, LOG_FLOPPY); + + this.response_index = 0; + this.response_length = 7; + + this.response_data[0] = 0; + this.response_data[1] = 0; + this.response_data[2] = 0; + this.response_data[3] = 0; + this.response_data[4] = 0; + this.response_data[5] = 0; + this.response_data[6] = 0; + + this.raise_irq(); +}; + +FloppyController.prototype.raise_irq = function() +{ + if(this.dor & 8) + { + this.cpu.device_raise_irq(6); + } +}; diff --git a/src/hpet.js b/src/hpet.js new file mode 100644 index 0000000..1dc527d --- /dev/null +++ b/src/hpet.js @@ -0,0 +1,295 @@ +"use strict"; + + +var HPET_ADDR = 0xFED00000, + HPET_PERIOD = 0x05F5E100, // in nano seconds + HPET_FREQ_MS = 1e12 / HPET_PERIOD, // in kHZ + HPET_SUPPORT_64 = 0, + HPET_COUNTER_CONFIG = 1 << 4 | HPET_SUPPORT_64 << 5, + HPET_COUNTER_CONFIG_MASK = 1 << 4 | 1 << 5 | 1 << 15, + HPET_NUM_COUNTERS = 4; + +/** + * HPET - High Precision Event Timer + * http://wiki.osdev.org/HPET + * + * @constructor + * @param {CPU} cpu + */ +function HPET(cpu) +{ + var me = this, + + hpet_enabled = false, + hpet_start = Date.now(), + + hpet_offset_low = 0, + hpet_offset_high = 0, + + counter_read_acc_next = false, + interrupt_status = 0, + + counter_config = new Int32Array(HPET_NUM_COUNTERS << 1), + counter_comparator = new Int32Array(HPET_NUM_COUNTERS << 1), + counter_accumulator = new Int32Array(HPET_NUM_COUNTERS << 1); + + //var counter_last_irq = new Int32Array(HPET_NUM_COUNTERS << 1); + + + var last_check = 0; + + + this.legacy_mode = false; + + this.timer = function(now) + { + if(!hpet_enabled) + { + return 100; + } + + var + counter_value = get_counter() >>> 0, + config, + //last_irq, + comparator, + do_irq; + + for(var i = 0; i < HPET_NUM_COUNTERS; i++) + { + config = counter_config[i << 1]; + //last_irq = counter_last_irq[i << 1] >>> 0; + comparator = counter_comparator[i << 1] >>> 0; + + if(last_check <= counter_value ? + comparator > last_check && comparator <= counter_value : + comparator > last_check || comparator <= counter_value + ) { + do_irq = config & 4; + //counter_last_irq[i << 1] = comparator; + + if(config & 2) + { + // level triggered + do_irq = do_irq && !(interrupt_status & 1 << i); + interrupt_status |= 1 << i; + } + else + { + // edge-triggered + interrupt_status &= ~(1 << i); + } + + if(config & 1 << 3) + { + // periodic mode + counter_comparator[i << 1] += counter_accumulator[i << 1]; + } + + //dbg_log("do_irq=" + do_irq, LOG_HPET); + if(do_irq) + { + if(me.legacy_mode && i === 0) + { + cpu.device_raise_irq(0); + } + else if(me.legacy_mode && i === 1) + { + cpu.device_raise_irq(0); + } + else + { + // TODO + cpu.device_raise_irq(0); + } + } + } + } + + last_check = counter_value; + + return 100; // TODO + }; + + function get_counter() + { + if(hpet_enabled) + { + return (Date.now() - hpet_start) * HPET_FREQ_MS + hpet_offset_low | 0; + } + else + { + return hpet_offset_low; + } + } + + function get_counter_high() + { + if(HPET_SUPPORT_64) + { + if(hpet_enabled) + { + return (Date.now() - hpet_start) * (HPET_FREQ_MS / 0x100000000) + hpet_offset_high | 0; + } + else + { + return hpet_offset_high; + } + } + else + { + return 0; + } + } + + cpu.io.mmap_register(HPET_ADDR, 0x4000, mmio_read, mmio_write); + + + + function mmio_read(addr) + { + dbg_log("Read " + h(addr, 4) + " (ctr=" + h(get_counter() >>> 0) + ")", LOG_HPET); + + switch(addr) + { + case 0: + return 1 << 16 | HPET_NUM_COUNTERS - 1 << 8 | 0x8000 | 0x01 | HPET_SUPPORT_64 << 13; + case 4: + return HPET_PERIOD; + + case 0x10: + return me.legacy_mode << 1 | hpet_enabled; + + case 0xF0: + return get_counter(); + + case 0xF4: + return get_counter_high(); + } + + // read from counter register + var register = addr >> 2 & 7, + counter = addr - 0x100 >> 5; + + if(addr < 0x100 || counter >= HPET_NUM_COUNTERS || register > 5) + { + dbg_log("Read reserved address: " + h(addr), LOG_HPET); + return 0; + } + + dbg_log("Read counter: addr=" + h(addr) + " counter=" + h(counter, 2) + + " reg=" + h(register), LOG_HPET); + + switch(register) + { + case 0: + return counter_config[counter << 1] & ~HPET_COUNTER_CONFIG_MASK | HPET_COUNTER_CONFIG; + case 1: + return counter_config[counter << 1 | 1]; + + case 2: + return counter_comparator[counter << 1]; + case 3: + return counter_comparator[counter << 1 | 1]; + + case 4: + case 5: + // TODO interrupt route register + return 0; + } + } + + function mmio_write(addr, data) + { + dbg_log("Write " + h(addr, 4) + ": " + h(data, 2), LOG_HPET); + + switch(addr) + { + case 0x10: + dbg_log("conf: enabled=" + (data & 1) + " legacy=" + (data >> 1 & 1), LOG_HPET); + + if((hpet_enabled ^ data) & 1) + { + if(data & 1) + { + // counter is enabled now, start counting now + hpet_start = Date.now(); + } + else + { + // counter is disabled now, save current count + hpet_offset_low = get_counter(); + hpet_offset_high = get_counter_high(); + } + } + + hpet_enabled = (data & 1) === 1; + me.legacy_mode = (data & 2) === 2; + + return; + + case 0x20: + // writing a 1 clears bits + interrupt_status &= ~data; + return; + + case 0xF0: + hpet_offset_low = data; + return; + + case 0xF4: + hpet_offset_high = data; + return; + } + + // read from counter register + var register = addr >> 2 & 7, + counter = addr - 0x100 >> 5; + + if(addr < 0x100 || counter >= HPET_NUM_COUNTERS || register > 2) + { + dbg_log("Write reserved address: " + h(addr) + " data=" + h(data), LOG_HPET); + return; + } + + dbg_log("Write counter: addr=" + h(addr) + " counter=" + h(counter, 2) + + " reg=" + h(register) + " data=" + h(data, 2), LOG_HPET); + + switch(register) + { + case 0: + counter_config[counter << 1] = data; + break; + case 1: + //counter_config[counter << 1 | 1] = data; + break; + + case 2: + if(counter_read_acc_next) + { + counter_accumulator[counter << 1] = data; + counter_read_acc_next = false; + dbg_log("Accumulator acc=" + h(data >>> 0, 8) + " ctr=" + h(counter, 2), LOG_HPET); + } + else + { + counter_comparator[counter << 1] = data; + + if(counter_config[counter << 1] & 1 << 6) + { + counter_read_acc_next = true; + counter_config[counter << 1] &= ~(1 << 6); + } + } + break; + case 3: + counter_comparator[counter << 1 | 1] = data; + break; + + case 4: + case 5: + // TODO interrupt route register + + } + } +} diff --git a/src/ide.js b/src/ide.js new file mode 100644 index 0000000..fde307e --- /dev/null +++ b/src/ide.js @@ -0,0 +1,2092 @@ +"use strict"; + +/** @const */ +var CDROM_SECTOR_SIZE = 2048; +/** @const */ +var HD_SECTOR_SIZE = 512; + +/** + * @constructor + * @param {CPU} cpu + * @param {boolean} is_cd + * @param {number} nr + * @param {BusConnector} bus + * */ +function IDEDevice(cpu, master_buffer, slave_buffer, is_cd, nr, bus) +{ + this.master = new IDEInterface(this, cpu, master_buffer, is_cd, nr, 0, bus); + this.slave = new IDEInterface(this, cpu, slave_buffer, false, nr, 1, bus); + + this.current_interface = this.master; + + this.cpu = cpu; + + // gets set via PCI in seabios, likely doesn't matter + if(nr === 0) + { + this.ata_port = 0x1F0; + this.irq = 14; + + this.pci_id = 0x1E << 3; + } + else if(nr === 1) + { + this.ata_port = 0x170; + this.irq = 15; + + this.pci_id = 0x1F << 3; + } + else + { + dbg_assert(false, "IDE device with nr " + nr + " ignored", LOG_DISK); + } + + // alternate status, starting at 3f4/374 + /** @type {number} */ + this.ata_port_high = this.ata_port | 0x204; + + /** @type {number} */ + this.master_port = 0xB400; + + this.pci_space = [ + 0x86, 0x80, 0x10, 0x70, 0x05, 0x00, 0xA0, 0x02, + 0x00, 0x80, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, + this.ata_port & 0xFF | 1, this.ata_port >> 8, 0x00, 0x00, + this.ata_port_high & 0xFF | 1, this.ata_port_high >> 8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // second device + 0x00, 0x00, 0x00, 0x00, // second device + this.master_port & 0xFF | 1, this.master_port >> 8, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x43, 0x10, 0xD4, 0x82, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, this.irq, 0x01, 0x00, 0x00, + + // 0x40 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // 0x80 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]; + this.pci_bars = [ + { + size: 8, + }, + { + size: 4, + }, + undefined, + undefined, + { + size: 0x10, + }, + ]; + this.name = "ide" + nr; + + /** @type {number} */ + this.device_control = 2; + + // status + cpu.io.register_read(this.ata_port | 7, this, function() { + dbg_log("lower irq", LOG_DISK); + this.cpu.device_lower_irq(this.irq); + return this.read_status(); + }); + cpu.io.register_read(this.ata_port_high | 2, this, this.read_status); + + cpu.io.register_write(this.ata_port_high | 2, this, this.write_control); + cpu.io.register_read(this.ata_port | 0, this, function() + { + return this.current_interface.read_data(1); + }, function() + { + return this.current_interface.read_data(2); + }, function() + { + return this.current_interface.read_data(4); + }); + + cpu.io.register_read(this.ata_port | 1, this, function() + { + dbg_log("Read error: " + h(this.current_interface.error & 0xFF) + + " slave=" + (this.current_interface === this.slave), LOG_DISK); + return this.current_interface.error & 0xFF; + }); + cpu.io.register_read(this.ata_port | 2, this, function() + { + dbg_log("Read bytecount: " + h(this.current_interface.bytecount & 0xFF), LOG_DISK); + return this.current_interface.bytecount & 0xFF; + }); + cpu.io.register_read(this.ata_port | 3, this, function() + { + dbg_log("Read sector: " + h(this.current_interface.sector & 0xFF), LOG_DISK); + return this.current_interface.sector & 0xFF; + }); + + cpu.io.register_read(this.ata_port | 4, this, function() + { + dbg_log("Read 1F4: " + h(this.current_interface.cylinder_low & 0xFF), LOG_DISK); + return this.current_interface.cylinder_low & 0xFF; + }); + cpu.io.register_read(this.ata_port | 5, this, function() + { + dbg_log("Read 1F5: " + h(this.current_interface.cylinder_high & 0xFF), LOG_DISK); + return this.current_interface.cylinder_high & 0xFF; + }); + cpu.io.register_read(this.ata_port | 6, this, function() + { + dbg_log("Read 1F6", LOG_DISK); + return this.current_interface.drive_head & 0xFF; + }); + + cpu.io.register_write(this.ata_port | 0, this, function(data) + { + this.current_interface.write_data_port8(data); + }, function(data) + { + this.current_interface.write_data_port16(data); + }, function(data) + { + this.current_interface.write_data_port32(data); + }); + + cpu.io.register_write(this.ata_port | 1, this, function(data) + { + dbg_log("1F1/lba_count: " + h(data), LOG_DISK); + this.master.lba_count = (this.master.lba_count << 8 | data) & 0xFFFF; + this.slave.lba_count = (this.slave.lba_count << 8 | data) & 0xFFFF; + }); + cpu.io.register_write(this.ata_port | 2, this, function(data) + { + dbg_log("1F2/bytecount: " + h(data), LOG_DISK); + this.master.bytecount = (this.master.bytecount << 8 | data) & 0xFFFF; + this.slave.bytecount = (this.slave.bytecount << 8 | data) & 0xFFFF; + }); + cpu.io.register_write(this.ata_port | 3, this, function(data) + { + dbg_log("1F3/sector: " + h(data), LOG_DISK); + this.master.sector = (this.master.sector << 8 | data) & 0xFFFF; + this.slave.sector = (this.slave.sector << 8 | data) & 0xFFFF; + }); + + cpu.io.register_write(this.ata_port | 4, this, function(data) + { + dbg_log("1F4/sector low: " + h(data), LOG_DISK); + this.master.cylinder_low = (this.master.cylinder_low << 8 | data) & 0xFFFF; + this.slave.cylinder_low = (this.slave.cylinder_low << 8 | data) & 0xFFFF; + }); + cpu.io.register_write(this.ata_port | 5, this, function(data) + { + dbg_log("1F5/sector high: " + h(data), LOG_DISK); + this.master.cylinder_high = (this.master.cylinder_high << 8 | data) & 0xFFFF; + this.slave.cylinder_high = (this.slave.cylinder_high << 8 | data) & 0xFFFF; + }); + cpu.io.register_write(this.ata_port | 6, this, function(data) + { + var slave = data & 0x10; + var mode = data & 0xE0; + + dbg_log("1F6/drive: " + h(data, 2), LOG_DISK); + + if(slave) + { + dbg_log("Slave", LOG_DISK); + this.current_interface = this.slave; + } + else + { + this.current_interface = this.master; + } + + this.master.drive_head = data; + this.slave.drive_head = data; + this.master.is_lba = this.slave.is_lba = data >> 6 & 1; + this.master.head = this.slave.head = data & 0xF; + }); + + /** @type {number} */ + this.prdt_addr = 0; + + /** @type {number} */ + this.dma_status = 0; + + /** @type {number} */ + this.dma_command = 0; + + cpu.io.register_write(this.ata_port | 7, this, function(data) + { + dbg_log("lower irq", LOG_DISK); + this.cpu.device_lower_irq(this.irq); + this.current_interface.ata_command(data); + }); + + cpu.io.register_read(this.master_port | 4, this, undefined, undefined, this.dma_read_addr); + cpu.io.register_write(this.master_port | 4, this, undefined, undefined, this.dma_set_addr); + + cpu.io.register_read(this.master_port, this, + this.dma_read_command8, undefined, this.dma_read_command); + cpu.io.register_write(this.master_port, this, + this.dma_write_command8, undefined, this.dma_write_command); + + cpu.io.register_read(this.master_port | 2, this, this.dma_read_status); + cpu.io.register_write(this.master_port | 2, this, this.dma_write_status); + + cpu.io.register_read(this.master_port | 0x8, this, function() { + dbg_log("DMA read 0x8", LOG_DISK); return 0; + }); + cpu.io.register_read(this.master_port | 0xA, this, function() { + dbg_log("DMA read 0xA", LOG_DISK); return 0; + }); + + cpu.devices.pci.register_device(this); + + DEBUG && Object.seal(this); +} + +IDEDevice.prototype.read_status = function() +{ + if(this.current_interface.buffer) + { + var ret = this.current_interface.status; + dbg_log("ATA read status: " + h(ret, 2), LOG_DISK); + return ret; + } + else + { + return 0; + } +}; + +IDEDevice.prototype.write_control = function(data) +{ + dbg_log("set device control: " + h(data, 2) + " interrupts " + + ((data & 2) ? "disabled" : "enabled"), LOG_DISK); + + if(data & 4) + { + dbg_log("Reset via control port", LOG_DISK); + + this.cpu.device_lower_irq(this.irq); + + this.master.device_reset(); + this.slave.device_reset(); + } + + this.device_control = data; +}; + +IDEDevice.prototype.dma_read_addr = function() +{ + dbg_log("dma get address: " + h(this.prdt_addr, 8), LOG_DISK); + return this.prdt_addr; +}; + +IDEDevice.prototype.dma_set_addr = function(data) +{ + dbg_log("dma set address: " + h(data, 8), LOG_DISK); + this.prdt_addr = data; +}; + +IDEDevice.prototype.dma_read_status = function() +{ + dbg_log("DMA read status: " + h(this.dma_status), LOG_DISK); + return this.dma_status; +}; + +IDEDevice.prototype.dma_write_status = function(value) +{ + dbg_log("DMA set status: " + h(value), LOG_DISK); + this.dma_status &= ~(value & 6); +}; + +IDEDevice.prototype.dma_read_command = function() +{ + return this.dma_read_command8() | this.dma_read_status() << 16; +}; + +IDEDevice.prototype.dma_read_command8 = function() +{ + dbg_log("DMA read command: " + h(this.dma_command), LOG_DISK); + return this.dma_command; +}; + +IDEDevice.prototype.dma_write_command = function(value) +{ + dbg_log("DMA write command: " + h(value), LOG_DISK); + + this.dma_write_command8(value & 0xFF); + this.dma_write_status(value >> 16 & 0xFF); +}; + +IDEDevice.prototype.dma_write_command8 = function(value) +{ + dbg_log("DMA write command8: " + h(value), LOG_DISK); + + let old_command = this.dma_command; + this.dma_command = value & 0x9; + + if((old_command & 1) === (value & 1)) + { + return; + } + + if((value & 1) === 0) + { + this.dma_status &= ~1; + return; + } + + this.dma_status |= 1; + + switch(this.current_interface.current_command) + { + case 0x25: + case 0xC8: + this.current_interface.do_ata_read_sectors_dma(); + break; + + case 0xCA: + case 0x35: + this.current_interface.do_ata_write_sectors_dma(); + break; + + case 0xA0: + this.current_interface.do_atapi_dma(); + break; + + default: + dbg_log("Spurious dma command write, current command: " + + h(this.current_interface.current_command), LOG_DISK); + dbg_assert(false); + } +}; + +IDEDevice.prototype.push_irq = function() +{ + if((this.device_control & 2) === 0) + { + dbg_log("push irq", LOG_DISK); + this.dma_status |= 4; + this.cpu.device_raise_irq(this.irq); + } +}; + +IDEDevice.prototype.get_state = function() +{ + var state = []; + state[0] = this.master; + state[1] = this.slave; + state[2] = this.ata_port; + state[3] = this.irq; + state[4] = this.pci_id; + state[5] = this.ata_port_high; + state[6] = this.master_port; + state[7] = this.name; + state[8] = this.device_control; + state[9] = this.prdt_addr; + state[10] = this.dma_status; + state[11] = this.current_interface === this.master; + state[12] = this.dma_command; + return state; +}; + +IDEDevice.prototype.set_state = function(state) +{ + this.master.set_state(state[0]); + this.slave.set_state(state[1]); + this.ata_port = state[2]; + this.irq = state[3]; + this.pci_id = state[4]; + this.ata_port_high = state[5]; + this.master_port = state[6]; + this.name = state[7]; + this.device_control = state[8]; + this.prdt_addr = state[9]; + this.dma_status = state[10]; + this.current_interface = state[11] ? this.master : this.slave; + this.dma_command = state[12]; +}; + + +/** + * @constructor + */ +function IDEInterface(device, cpu, buffer, is_cd, device_nr, interface_nr, bus) +{ + this.device = device; + + /** @const @type {BusConnector} */ + this.bus = bus; + + /** + * @const + * @type {number} + */ + this.nr = device_nr; + + /** @const @type {CPU} */ + this.cpu = cpu; + + this.buffer = buffer; + + /** @type {number} */ + this.sector_size = is_cd ? CDROM_SECTOR_SIZE : HD_SECTOR_SIZE; + + /** @type {boolean} */ + this.is_atapi = is_cd; + + /** @type {number} */ + this.sector_count = 0; + + /** @type {number} */ + this.head_count = 0; + + /** @type {number} */ + this.sectors_per_track = 0; + + /** @type {number} */ + this.cylinder_count = 0; + + if(this.buffer) + { + this.sector_count = this.buffer.byteLength / this.sector_size; + + if(this.sector_count !== (this.sector_count | 0)) + { + dbg_log("Warning: Disk size not aligned with sector size", LOG_DISK); + this.sector_count = Math.ceil(this.sector_count); + } + + if(is_cd) + { + this.head_count = 1; + this.sectors_per_track = 0; + } + else + { + // "default" values: 16/63 + // common: 255, 63 + this.head_count = 16; + this.sectors_per_track = 63; + } + + + this.cylinder_count = this.sector_count / this.head_count / this.sectors_per_track; + + if(this.cylinder_count !== (this.cylinder_count | 0)) + { + dbg_log("Warning: Rounding up cylinder count. Choose different head number", LOG_DISK); + this.cylinder_count = Math.floor(this.cylinder_count); + //this.sector_count = this.cylinder_count * this.head_count * + // this.sectors_per_track * this.sector_size; + } + + //if(this.cylinder_count > 16383) + //{ + // this.cylinder_count = 16383; + //} + + // disk translation: lba + var rtc = cpu.devices.rtc; + + // master + rtc.cmos_write(CMOS_BIOS_DISKTRANSFLAG, + rtc.cmos_read(CMOS_BIOS_DISKTRANSFLAG) | 1 << this.nr * 4); + rtc.cmos_write(CMOS_DISK_DATA, rtc.cmos_read(CMOS_DISK_DATA) & 0x0F | 0xF0); + + var reg = CMOS_DISK_DRIVE1_CYL; + rtc.cmos_write(reg + 0, this.cylinder_count & 0xFF); + rtc.cmos_write(reg + 1, this.cylinder_count >> 8 & 0xFF); + rtc.cmos_write(reg + 2, this.head_count & 0xFF); + rtc.cmos_write(reg + 3, 0xFF); + rtc.cmos_write(reg + 4, 0xFF); + rtc.cmos_write(reg + 5, 0xC8); + rtc.cmos_write(reg + 6, this.cylinder_count & 0xFF); + rtc.cmos_write(reg + 7, this.cylinder_count >> 8 & 0xFF); + rtc.cmos_write(reg + 8, this.sectors_per_track & 0xFF); + + //rtc.cmos_write(CMOS_BIOS_DISKTRANSFLAG, + // rtc.cmos_read(CMOS_BIOS_DISKTRANSFLAG) | 1 << (nr * 4 + 2)); // slave + } + + /** @const */ + this.stats = { + sectors_read: 0, + sectors_written: 0, + bytes_read: 0, + bytes_written: 0, + loading: false, + }; + + + this.buffer = buffer; + + /** @type {number} */ + this.is_lba = 0; + + /** @type {number} */ + this.bytecount = 0; + + /** @type {number} */ + this.sector = 0; + + /** @type {number} */ + this.lba_count = 0; + + /** @type {number} */ + this.cylinder_low = 0; + + /** @type {number} */ + this.cylinder_high = 0; + + /** @type {number} */ + this.head = 0; + + /** @type {number} */ + this.drive_head = 0; + + /** @type {number} */ + this.status = 0x50; + + /** @type {number} */ + this.sectors_per_drq = 0x80; + + /** @type {number} */ + this.error = 0; + + /** @type {number} */ + this.data_pointer = 0; + + this.data = new Uint8Array(64 * 1024); + this.data16 = new Uint16Array(this.data.buffer); + this.data32 = new Int32Array(this.data.buffer); + + /** @type {number} */ + this.data_length = 0; + + /** @type {number} */ + this.data_end = 0; + + /** @type {number} */ + this.current_command = -1; + + /** @type {number} */ + this.current_atapi_command = -1; + + /** @type {number} */ + this.write_dest = 0; + + // cancellation support + this.last_io_id = 0; + this.in_progress_io_ids = new Set(); + this.cancelled_io_ids = new Set(); + + Object.seal(this); +} + +IDEInterface.prototype.device_reset = function() +{ + if(this.is_atapi) + { + this.status = 0; + this.bytecount = 1; + this.error = 1; + this.sector = 1; // lba_low + this.cylinder_low = 0x14; // lba_mid + this.cylinder_high = 0xEB; // lba_high + } + else + { + this.status = 0x50 | 1; + this.bytecount = 1; + this.error = 1; + this.sector = 1; // lba_low + + // 0, 0 needed by bochs bios + this.cylinder_low = 0; // lba_mid + this.cylinder_high = 0; // lba_high + } + + this.cancel_io_operations(); +}; + +IDEInterface.prototype.push_irq = function() +{ + this.device.push_irq(); +}; + +IDEInterface.prototype.ata_command = function(cmd) +{ + dbg_log("ATA Command: " + h(cmd) + " slave=" + (this.drive_head >> 4 & 1), LOG_DISK); + + if(!this.buffer) + { + dbg_log("abort: No buffer", LOG_DISK); + this.error = 4; + this.status = 0x41; + this.push_irq(); + return; + } + + this.current_command = cmd; + this.error = 0; + + switch(cmd) + { + case 0x08: + dbg_log("ATA device reset", LOG_DISK); + this.data_pointer = 0; + this.data_end = 0; + this.data_length = 0; + this.device_reset(); + this.push_irq(); + break; + + case 0x10: + // calibrate drive + this.status = 0x50; + this.cylinder_low = 0; + this.push_irq(); + break; + + case 0xF8: + // read native max address + this.status = 0x50; + var last_sector = this.sector_count - 1; + this.sector = last_sector & 0xFF; + this.cylinder_low = last_sector >> 8 & 0xFF; + this.cylinder_high = last_sector >> 16 & 0xFF; + this.drive_head = this.drive_head & 0xF0 | last_sector >> 24 & 0x0F; + this.push_irq(); + break; + + case 0x27: + // read native max address ext + this.status = 0x50; + var last_sector = this.sector_count - 1; + this.sector = last_sector & 0xFF; + this.cylinder_low = last_sector >> 8 & 0xFF; + this.cylinder_high = last_sector >> 16 & 0xFF; + this.sector |= last_sector >> 24 << 8 & 0xFF00; + this.push_irq(); + break; + + case 0x20: + case 0x24: + case 0x29: + case 0xC4: + // 0x20 read sectors + // 0x24 read sectors ext + // 0xC4 read multiple + // 0x29 read multiple ext + this.ata_read_sectors(cmd); + break; + + case 0x30: + case 0x34: + case 0x39: + case 0xC5: + // 0x30 write sectors + // 0x34 write sectors ext + // 0xC5 write multiple + // 0x39 write multiple ext + this.ata_write_sectors(cmd); + break; + + case 0x90: + // execute device diagnostic + this.push_irq(); + this.error = 0x101; + this.status = 0x50; + break; + + case 0x91: + // initialize device parameters + this.status = 0x50; + this.push_irq(); + break; + + case 0xA0: + // ATA packet + if(this.is_atapi) + { + this.status = 0x58; + this.data_allocate(12); + this.data_end = 12; + this.bytecount = 1; + this.push_irq(); + } + break; + + case 0xA1: + dbg_log("ATA identify packet device", LOG_DISK); + + if(this.is_atapi) + { + this.create_identify_packet(); + this.status = 0x58; + + this.cylinder_low = 0x14; + this.cylinder_high = 0xEB; + + this.push_irq(); + } + else + { + this.status = 0x41; + this.push_irq(); + } + break; + + case 0xC6: + // set multiple mode + // Logical sectors per DRQ Block in word 1 + dbg_log("Logical sectors per DRQ Block: " + h(this.bytecount & 0xFF), LOG_DISK); + this.sectors_per_drq = this.bytecount & 0xFF; + this.status = 0x50; + this.push_irq(); + break; + + case 0x25: // read dma ext + case 0xC8: // read dma + this.ata_read_sectors_dma(cmd); + break; + + case 0x35: // write dma ext + case 0xCA: // write dma + this.ata_write_sectors_dma(cmd); + break; + + case 0x40: + dbg_log("read verify sectors", LOG_DISK); + this.status = 0x50; + this.push_irq(); + break; + + case 0xDA: + dbg_log("Unimplemented: get media status", LOG_DISK); + this.status = 0x41; + this.error = 4; + this.push_irq(); + break; + + case 0xE0: + dbg_log("ATA standby immediate", LOG_DISK); + this.status = 0x50; + this.push_irq(); + break; + + case 0xE1: + dbg_log("ATA idle immediate", LOG_DISK); + this.status = 0x50; + this.push_irq(); + break; + + case 0xE7: + dbg_log("ATA flush cache", LOG_DISK); + this.status = 0x50; + this.push_irq(); + break; + + case 0xEC: + dbg_log("ATA identify device", LOG_DISK); + + if(this.is_atapi) + { + this.status = 0x41; + this.error = 4; + this.push_irq(); + return; + } + + this.create_identify_packet(); + this.status = 0x58; + + this.push_irq(); + break; + + case 0xEA: + dbg_log("flush cache ext", LOG_DISK); + this.status = 0x50; + this.push_irq(); + break; + + case 0xEF: + dbg_log("set features: " + h(this.bytecount & 0xFF), LOG_DISK); + this.status = 0x50; + this.push_irq(); + break; + + case 0xDE: + // obsolete + this.status = 0x50; + this.push_irq(); + break; + + case 0xF5: + dbg_log("security freeze lock", LOG_DISK); + this.status = 0x50; + this.push_irq(); + break; + + case 0xF9: + dbg_log("Unimplemented: set max address", LOG_DISK); + this.status = 0x41; + this.error = 4; + break; + + default: + dbg_assert(false, "New ATA cmd on 1F7: " + h(cmd), LOG_DISK); + + this.status = 0x41; + // abort bit set + this.error = 4; + } +}; + +IDEInterface.prototype.atapi_handle = function() +{ + dbg_log("ATAPI Command: " + h(this.data[0]) + + " slave=" + (this.drive_head >> 4 & 1), LOG_DISK); + + this.data_pointer = 0; + this.current_atapi_command = this.data[0]; + + switch(this.current_atapi_command) + { + case 0x00: + dbg_log("test unit ready", LOG_DISK); + // test unit ready + this.data_allocate(0); + this.data_end = this.data_length; + this.status = 0x50; + break; + + case 0x03: + // request sense + this.data_allocate(this.data[4]); + this.data_end = this.data_length; + this.status = 0x58; + + this.data[0] = 0x80 | 0x70; + this.data[2] = 5; // illegal request + this.data[7] = 8; + break; + + case 0x12: + // inquiry + var length = this.data[4]; + this.status = 0x58; + + dbg_log("inquiry: " + h(this.data[1], 2) + " length=" + length, LOG_DISK); + + // http://www.t10.org/ftp/x3t9.2/document.87/87-106r0.txt + //this.data_allocate(36); + this.data.set([ + 0x05, 0x80, 0x01, 0x31, + // additional length + 31, + 0, 0, 0, + + // 8 + 0x53, 0x4F, 0x4E, 0x59, + 0x20, 0x20, 0x20, 0x20, + + // 16 + 0x43, 0x44, 0x2D, 0x52, + 0x4F, 0x4D, 0x20, 0x43, + 0x44, 0x55, 0x2D, 0x31, + 0x30, 0x30, 0x30, 0x20, + + // 32 + 0x31, 0x2E, 0x31, 0x61, + ]); + this.data_end = this.data_length = Math.min(36, length); + break; + + case 0x1A: + // mode sense (6) + this.data_allocate(this.data[4]); + this.data_end = this.data_length; + this.status = 0x58; + break; + + case 0x1E: + // prevent/allow medium removal + this.data_allocate(0); + this.data_end = this.data_length; + this.status = 0x50; + break; + + case 0x25: + // read capacity + var count = this.sector_count - 1; + this.data_set(new Uint8Array([ + count >> 24 & 0xFF, + count >> 16 & 0xFF, + count >> 8 & 0xFF, + count & 0xFF, + 0, + 0, + this.sector_size >> 8 & 0xFF, + this.sector_size & 0xFF, + ])); + this.data_end = this.data_length; + this.status = 0x58; + break; + + case 0x28: + // read + if(this.lba_count & 1) + { + this.atapi_read_dma(this.data); + } + else + { + this.atapi_read(this.data); + } + break; + + case 0x42: + var length = this.data[8]; + this.data_allocate(Math.min(8, length)); + this.data_end = this.data_length; + dbg_log("read q subcode: length=" + length, LOG_DISK); + this.status = 0x58; + break; + + case 0x43: + // read toc + var length = this.data[8] | this.data[7] << 8; + var format = this.data[9] >> 6; + + this.data_allocate(length); + this.data_end = this.data_length; + dbg_log("read toc: " + h(format, 2) + + " length=" + length + + " " + (this.data[1] & 2) + + " " + h(this.data[6]), LOG_DISK); + + if(format === 0) + { + var sector_count = this.sector_count; + this.data.set(new Uint8Array([ + 0, 18, // length + 1, 1, // first and last session + + 0, + 0x14, + 1, // track number + 0, + 0, 0, 0, 0, + + 0, + 0x16, + 0xAA, // track number + 0, + sector_count >> 24, + sector_count >> 16 & 0xFF, + sector_count >> 8 & 0xFF, + sector_count & 0xFF, + ])); + } + else if(format === 1) + { + this.data.set(new Uint8Array([ + 0, 10, // length + 1, 1, // first and last session + 0, 0, + 0, 0, + 0, 0, + 0, 0, + ])); + } + else + { + dbg_assert(false, "Unimplemented format: " + format); + } + + this.status = 0x58; + break; + + case 0x46: + // get configuration + var length = this.data[8] | this.data[7] << 8; + length = Math.min(length, 32); + this.data_allocate(length); + this.data_end = this.data_length; + this.data[0] = length - 4 >> 24 & 0xFF; + this.data[1] = length - 4 >> 16 & 0xFF; + this.data[2] = length - 4 >> 8 & 0xFF; + this.data[3] = length - 4 & 0xFF; + this.data[6] = 0x08; + this.data[10] = 3; + this.status = 0x58; + break; + + case 0x51: + // read disk information + this.data_allocate(0); + this.data_end = this.data_length; + this.status = 0x50; + break; + + case 0x52: + dbg_log("Unimplemented ATAPI command: " + h(this.data[0]), LOG_DISK); + this.status = 0x51; + this.data_length = 0; + this.error = 5 << 4; + break; + + case 0x5A: + // mode sense + var length = this.data[8] | this.data[7] << 8; + var page_code = this.data[2]; + dbg_log("mode sense: " + h(page_code) + " length=" + length, LOG_DISK); + if(page_code === 0x2A) + { + this.data_allocate(Math.min(30, length)); + } + this.data_end = this.data_length; + this.status = 0x58; + break; + + case 0xBD: + // mechanism status + this.data_allocate(this.data[9] | this.data[8] << 8); + this.data_end = this.data_length; + this.data[5] = 1; + this.status = 0x58; + break; + + case 0x4A: + this.status = 0x51; + this.data_length = 0; + this.error = 5 << 4; + dbg_log("Unimplemented ATAPI command: " + h(this.data[0]), LOG_DISK); + break; + + case 0xBE: + // Hiren's boot CD + dbg_log("Unimplemented ATAPI command: " + h(this.data[0]), LOG_DISK); + this.data_allocate(0); + this.data_end = this.data_length; + this.status = 0x50; + break; + + default: + this.status = 0x51; + this.data_length = 0; + this.error = 5 << 4; + dbg_log("Unimplemented ATAPI command: " + h(this.data[0]), LOG_DISK); + dbg_assert(false); + } + + this.bytecount = this.bytecount & ~7 | 2; + + if((this.status & 0x80) === 0) + { + this.push_irq(); + } + + if((this.status & 0x80) === 0 && this.data_length === 0) + { + this.bytecount |= 1; + this.status &= ~8; + } +}; + +IDEInterface.prototype.do_write = function() +{ + this.status = 0x50; + + dbg_assert(this.data_length <= this.data.length); + var data = this.data.subarray(0, this.data_length); + + //dbg_log(hex_dump(data), LOG_DISK); + dbg_assert(this.data_length % 512 === 0); + this.ata_advance(this.current_command, this.data_length / 512); + this.push_irq(); + + this.buffer.set(this.write_dest, data, function() + { + }); + + this.report_write(this.data_length); +}; + +IDEInterface.prototype.atapi_read = function(cmd) +{ + // Note: Big Endian + var lba = cmd[2] << 24 | cmd[3] << 16 | cmd[4] << 8 | cmd[5]; + var count = cmd[7] << 8 | cmd[8]; + var flags = cmd[1]; + var byte_count = count * this.sector_size; + var start = lba * this.sector_size; + + dbg_log("CD read lba=" + h(lba) + + " lbacount=" + h(count) + + " bytecount=" + h(byte_count) + + " flags=" + h(flags), LOG_DISK); + + this.data_length = 0; + var req_length = this.cylinder_high << 8 & 0xFF00 | this.cylinder_low & 0xFF; + dbg_log(h(this.cylinder_high, 2) + " " + h(this.cylinder_low, 2), LOG_DISK); + this.cylinder_low = this.cylinder_high = 0; // oak technology driver (windows 3.0) + + if(req_length === 0xFFFF) + req_length--; + + if(req_length > byte_count) + { + req_length = byte_count; + } + + if(start >= this.buffer.byteLength) + { + dbg_assert(false, "CD read: Outside of disk end=" + h(start + byte_count) + + " size=" + h(this.buffer.byteLength), LOG_DISK); + + this.status = 0xFF; + this.push_irq(); + } + else if(byte_count === 0) + { + this.status = 0x50; + + this.data_pointer = 0; + //this.push_irq(); + } + else + { + byte_count = Math.min(byte_count, this.buffer.byteLength - start); + this.status = 0x50 | 0x80; + this.report_read_start(); + + this.read_buffer(start, byte_count, (data) => + { + //setTimeout(() => { + dbg_log("cd read: data arrived", LOG_DISK); + this.data_set(data); + this.status = 0x58; + this.bytecount = this.bytecount & ~7 | 2; + + this.push_irq(); + + req_length &= ~3; + + this.data_end = req_length; + if(this.data_end > this.data_length) + { + this.data_end = this.data_length; + } + this.cylinder_low = this.data_end & 0xFF; + this.cylinder_high = this.data_end >> 8 & 0xFF; + + this.report_read_end(byte_count); + //}, 10); + }); + } +}; + +IDEInterface.prototype.atapi_read_dma = function(cmd) +{ + // Note: Big Endian + var lba = cmd[2] << 24 | cmd[3] << 16 | cmd[4] << 8 | cmd[5]; + var count = cmd[7] << 8 | cmd[8]; + var flags = cmd[1]; + var byte_count = count * this.sector_size; + var start = lba * this.sector_size; + + dbg_log("CD read DMA lba=" + h(lba) + + " lbacount=" + h(count) + + " bytecount=" + h(byte_count) + + " flags=" + h(flags), LOG_DISK); + + if(start >= this.buffer.byteLength) + { + dbg_assert(false, "CD read: Outside of disk end=" + h(start + byte_count) + + " size=" + h(this.buffer.byteLength), LOG_DISK); + + this.status = 0xFF; + this.push_irq(); + } + else + { + this.status = 0x50 | 0x80; + this.report_read_start(); + + this.read_buffer(start, byte_count, (data) => + { + dbg_log("atapi_read_dma: Data arrived"); + this.report_read_end(byte_count); + this.status = 0x58; + this.bytecount = this.bytecount & ~7 | 2; + this.data_set(data); + + this.do_atapi_dma(); + }); + } +}; + +IDEInterface.prototype.do_atapi_dma = function() +{ + if((this.device.dma_status & 1) === 0) + { + dbg_log("do_atapi_dma: Status not set", LOG_DISK); + return; + } + + if((this.status & 0x8) === 0) + { + dbg_log("do_atapi_dma: DRQ not set", LOG_DISK); + return; + } + + dbg_log("atapi dma transfer len=" + this.data_length, LOG_DISK); + + var prdt_start = this.device.prdt_addr; + var offset = 0; + + var data = this.data; + + do { + var addr = this.cpu.read32s(prdt_start); + var count = this.cpu.read16(prdt_start + 4); + var end = this.cpu.read8(prdt_start + 7) & 0x80; + + if(!count) + { + count = 0x10000; + } + + dbg_log("dma read dest=" + h(addr) + " count=" + h(count) + " datalen=" + h(this.data_length), LOG_DISK); + this.cpu.write_blob(data.subarray(offset, Math.min(offset + count, this.data_length)), addr); + + offset += count; + prdt_start += 8; + + if(offset >= this.data_length && !end) + { + dbg_log("leave early end=" + (+end) + + " offset=" + h(offset) + + " data_length=" + h(this.data_length) + + " cmd=" + h(this.current_command), LOG_DISK); + break; + } + } + while(!end); + + dbg_log("end offset=" + offset, LOG_DISK); + + this.status = 0x50; + this.device.dma_status &= ~1; + this.bytecount = this.bytecount & ~7 | 3; + this.push_irq(); +}; + +IDEInterface.prototype.read_data = function(length) +{ + if(this.data_pointer < this.data_end) + { + dbg_assert(this.data_pointer + length - 1 < this.data_end); + dbg_assert(this.data_pointer % length === 0, h(this.data_pointer) + " " + length); + + if(length === 1) + { + var result = this.data[this.data_pointer]; + } + else if(length === 2) + { + var result = this.data16[this.data_pointer >>> 1]; + } + else + { + var result = this.data32[this.data_pointer >>> 2]; + } + + this.data_pointer += length; + + var align = (this.data_end & 0xFFF) === 0 ? 0xFFF : 0xFF; + if((this.data_pointer & align) === 0) + { + dbg_log("Read 1F0: " + h(this.data[this.data_pointer], 2) + + " cur=" + h(this.data_pointer) + + " cnt=" + h(this.data_length), LOG_DISK); + } + + if(this.data_pointer >= this.data_end) + { + this.read_end(); + } + + return result; + } + else + { + dbg_log("Read 1F0: empty", LOG_DISK); + + this.data_pointer += length; + return 0; + } +}; + +IDEInterface.prototype.read_end = function() +{ + dbg_log("read_end cmd=" + h(this.current_command) + " data_pointer=" + h(this.data_pointer) + + " end=" + h(this.data_end) + " length=" + h(this.data_length), LOG_DISK); + + if(this.current_command === 0xA0) + { + if(this.data_end === this.data_length) + { + this.status = 0x50; + this.bytecount = this.bytecount & ~7 | 3; + this.push_irq(); + } + else + { + this.status = 0x58; + this.bytecount = this.bytecount & ~7 | 2; + this.push_irq(); + var byte_count = this.cylinder_high << 8 & 0xFF00 | this.cylinder_low & 0xFF; + + if(this.data_end + byte_count > this.data_length) + { + this.cylinder_low = (this.data_length - this.data_end) & 0xFF; + this.cylinder_high = (this.data_length - this.data_end) >> 8 & 0xFF; + this.data_end = this.data_length; + } + else + { + this.data_end += byte_count; + } + dbg_log("data_end=" + h(this.data_end), LOG_DISK); + } + } + else + { + this.error = 0; + if(this.data_pointer >= this.data_length) + { + this.status = 0x50; + this.push_irq(); + } + else + { + if(this.current_command === 0xC4 || this.current_command === 0x29) + { + var sector_count = Math.min(this.sectors_per_drq, + (this.data_length - this.data_end) / 512); + dbg_assert(sector_count % 1 === 0); + } + else + { + dbg_assert(this.current_command === 0x20 || this.current_command === 0x24); + var sector_count = 1; + } + this.ata_advance(this.current_command, sector_count); + this.data_end += 512 * sector_count; + this.status = 0x58; + this.push_irq(); + } + } +}; + +IDEInterface.prototype.write_data_port = function(data, length) +{ + dbg_assert(this.data_pointer % length === 0); + + if(this.data_pointer >= this.data_end) + { + dbg_log("Redundant write to data port: " + h(data) + " count=" + h(this.data_end) + + " cur=" + h(this.data_pointer), LOG_DISK); + } + else + { + var align = (this.data_end & 0xFFF) === 0 ? 0xFFF : 0xFF; + if((this.data_pointer + length & align) === 0 || this.data_end < 20) + { + dbg_log("Data port: " + h(data >>> 0) + " count=" + h(this.data_end) + + " cur=" + h(this.data_pointer), LOG_DISK); + } + + if(length === 1) + { + this.data[this.data_pointer++] = data; + } + else if(length === 2) + { + this.data16[this.data_pointer >>> 1] = data; + this.data_pointer += 2; + } + else + { + this.data32[this.data_pointer >>> 2] = data; + this.data_pointer += 4; + } + + dbg_assert(this.data_pointer <= this.data_end); + if(this.data_pointer === this.data_end) + { + this.write_end(); + } + } +}; + +IDEInterface.prototype.write_data_port8 = function(data) +{ + this.write_data_port(data, 1); +}; + +IDEInterface.prototype.write_data_port16 = function(data) +{ + this.write_data_port(data, 2); +}; + +IDEInterface.prototype.write_data_port32 = function(data) +{ + this.write_data_port(data, 4); +}; + +IDEInterface.prototype.write_end = function() +{ + if(this.current_command === 0xA0) + { + this.atapi_handle(); + } + else + { + dbg_log("write_end data_pointer=" + h(this.data_pointer) + + " data_length=" + h(this.data_length), LOG_DISK); + + if(this.data_pointer >= this.data_length) + { + this.do_write(); + } + else + { + dbg_assert(this.current_command === 0x30 || + this.current_command === 0x34 || + this.current_command === 0xC5, + "Unexpected command: " + h(this.current_command)); + + // XXX: Should advance here, but do_write does all the advancing + //this.ata_advance(this.current_command, 1); + this.status = 0x58; + this.data_end += 512; + this.push_irq(); + } + } +}; + +IDEInterface.prototype.ata_advance = function(cmd, sectors) +{ + dbg_log("Advance sectors=" + sectors + " old_bytecount=" + this.bytecount, LOG_DISK); + this.bytecount -= sectors; + + if(cmd === 0x24 || cmd === 0x29 || cmd === 0x34 || cmd === 0x39 || + cmd === 0x25 || cmd === 0x35) + { + var new_sector = sectors + this.get_lba48(); + this.sector = new_sector & 0xFF | new_sector >> 16 & 0xFF00; + this.cylinder_low = new_sector >> 8 & 0xFF; + this.cylinder_high = new_sector >> 16 & 0xFF; + } + else if(this.is_lba) + { + var new_sector = sectors + this.get_lba28(); + this.sector = new_sector & 0xFF; + this.cylinder_low = new_sector >> 8 & 0xFF; + this.cylinder_high = new_sector >> 16 & 0xFF; + this.head = this.head & ~0xF | new_sector & 0xF; + } + else // chs + { + var new_sector = sectors + this.get_chs(); + + var c = new_sector / (this.head_count * this.sectors_per_track) | 0; + this.cylinder_low = c & 0xFF; + this.cylinder_high = c >> 8 & 0xFF; + this.head = (new_sector / this.sectors_per_track | 0) % this.head_count & 0xF; + this.sector = (new_sector % this.sectors_per_track + 1) & 0xFF; + + dbg_assert(new_sector === this.get_chs()); + } +}; + +IDEInterface.prototype.ata_read_sectors = function(cmd) +{ + var is_lba48 = cmd === 0x24 || cmd === 0x29; + var count = this.get_count(is_lba48); + var lba = this.get_lba(is_lba48); + + var is_single = cmd === 0x20 || cmd === 0x24; + + var byte_count = count * this.sector_size; + var start = lba * this.sector_size; + + dbg_log("ATA read cmd=" + h(cmd) + + " mode=" + (this.is_lba ? "lba" : "chs") + + " lba=" + h(lba) + + " lbacount=" + h(count) + + " bytecount=" + h(byte_count), LOG_DISK); + + if(start + byte_count > this.buffer.byteLength) + { + dbg_assert(false, "ATA read: Outside of disk", LOG_DISK); + + this.status = 0xFF; + this.push_irq(); + } + else + { + this.status = 0x80 | 0x40; + this.report_read_start(); + + this.read_buffer(start, byte_count, (data) => + { + //setTimeout(() => { + dbg_log("ata_read: Data arrived", LOG_DISK); + + this.data_set(data); + this.status = 0x58; + this.data_end = is_single ? 512 : Math.min(byte_count, this.sectors_per_drq * 512); + this.ata_advance(cmd, is_single ? 1 : Math.min(count, this.sectors_per_track)); + + this.push_irq(); + this.report_read_end(byte_count); + //}, 10); + }); + } +}; + +IDEInterface.prototype.ata_read_sectors_dma = function(cmd) +{ + var is_lba48 = cmd === 0x25; + var count = this.get_count(is_lba48); + var lba = this.get_lba(is_lba48); + + var byte_count = count * this.sector_size; + var start = lba * this.sector_size; + + dbg_log("ATA DMA read lba=" + h(lba) + + " lbacount=" + h(count) + + " bytecount=" + h(byte_count), LOG_DISK); + + if(start + byte_count > this.buffer.byteLength) + { + dbg_assert(false, "ATA read: Outside of disk", LOG_DISK); + + this.status = 0xFF; + this.push_irq(); + return; + } + + this.status = 0x58; + this.device.dma_status |= 1; +}; + +IDEInterface.prototype.do_ata_read_sectors_dma = function() +{ + var cmd = this.current_command; + + var is_lba48 = cmd === 0x25; + var count = this.get_count(is_lba48); + var lba = this.get_lba(is_lba48); + + var byte_count = count * this.sector_size; + var start = lba * this.sector_size; + + dbg_assert(lba < this.buffer.byteLength); + + this.report_read_start(); + + var orig_prdt_start = this.device.prdt_addr; + + this.read_buffer(start, byte_count, (data) => + { + //setTimeout(function() { + dbg_log("do_ata_read_sectors_dma: Data arrived", LOG_DISK); + var prdt_start = this.device.prdt_addr; + var offset = 0; + + dbg_assert(orig_prdt_start === prdt_start); + + do { + var prd_addr = this.cpu.read32s(prdt_start); + var prd_count = this.cpu.read16(prdt_start + 4); + var end = this.cpu.read8(prdt_start + 7) & 0x80; + + if(!prd_count) + { + prd_count = 0x10000; + dbg_log("dma: prd count was 0", LOG_DISK); + } + + dbg_log("dma read transfer dest=" + h(prd_addr) + + " prd_count=" + h(prd_count), LOG_DISK); + this.cpu.write_blob(data.subarray(offset, offset + prd_count), prd_addr); + + offset += prd_count; + prdt_start += 8; + } + while(!end); + + dbg_assert(offset === byte_count); + + this.ata_advance(this.current_command, count); + this.status = 0x50; + this.device.dma_status &= ~1; + this.current_command = -1; + + this.push_irq(); + + this.report_read_end(byte_count); + //}.bind(this), 10); + }); +}; + +IDEInterface.prototype.ata_write_sectors = function(cmd) +{ + var is_lba48 = cmd === 0x34 || cmd === 0x39; + var count = this.get_count(is_lba48); + var lba = this.get_lba(is_lba48); + + var is_single = cmd === 0x30 || cmd === 0x34; + + var byte_count = count * this.sector_size; + var start = lba * this.sector_size; + + dbg_log("ATA write lba=" + h(lba) + + " mode=" + (this.is_lba ? "lba" : "chs") + + " lbacount=" + h(count) + + " bytecount=" + h(byte_count), LOG_DISK); + + if(start + byte_count > this.buffer.byteLength) + { + dbg_assert(false, "ATA write: Outside of disk", LOG_DISK); + + this.status = 0xFF; + this.push_irq(); + } + else + { + this.status = 0x58; + this.data_allocate_noclear(byte_count); + this.data_end = is_single ? 512 : Math.min(byte_count, this.sectors_per_drq * 512); + this.write_dest = start; + } +}; + +IDEInterface.prototype.ata_write_sectors_dma = function(cmd) +{ + var is_lba48 = cmd === 0x35; + var count = this.get_count(is_lba48); + var lba = this.get_lba(is_lba48); + + var byte_count = count * this.sector_size; + var start = lba * this.sector_size; + + dbg_log("ATA DMA write lba=" + h(lba) + + " lbacount=" + h(count) + + " bytecount=" + h(byte_count), LOG_DISK); + + if(start + byte_count > this.buffer.byteLength) + { + dbg_assert(false, "ATA DMA write: Outside of disk", LOG_DISK); + + this.status = 0xFF; + this.push_irq(); + return; + } + + this.status = 0x58; + this.device.dma_status |= 1; +}; + +IDEInterface.prototype.do_ata_write_sectors_dma = function() +{ + var cmd = this.current_command; + + var is_lba48 = cmd === 0x35; + var count = this.get_count(is_lba48); + var lba = this.get_lba(is_lba48); + + var byte_count = count * this.sector_size; + var start = lba * this.sector_size; + + var prdt_start = this.device.prdt_addr; + var offset = 0; + + dbg_log("prdt addr: " + h(prdt_start, 8), LOG_DISK); + + const buffer = new Uint8Array(byte_count); + + do { + var prd_addr = this.cpu.read32s(prdt_start); + var prd_count = this.cpu.read16(prdt_start + 4); + var end = this.cpu.read8(prdt_start + 7) & 0x80; + + if(!prd_count) + { + prd_count = 0x10000; + dbg_log("dma: prd count was 0", LOG_DISK); + } + + dbg_log("dma write transfer dest=" + h(prd_addr) + " prd_count=" + h(prd_count), LOG_DISK); + + var slice = this.cpu.mem8.subarray(prd_addr, prd_addr + prd_count); + dbg_assert(slice.length === prd_count); + + buffer.set(slice, offset); + + //if(DEBUG) + //{ + // dbg_log(hex_dump(slice), LOG_DISK); + //} + + offset += prd_count; + prdt_start += 8; + } + while(!end); + + dbg_assert(offset === buffer.length); + + this.buffer.set(start, buffer, () => + { + dbg_log("dma write completed", LOG_DISK); + this.ata_advance(this.current_command, count); + this.status = 0x50; + this.push_irq(); + this.device.dma_status &= ~1; + this.current_command = -1; + }); + + this.report_write(byte_count); +}; + +IDEInterface.prototype.get_chs = function() +{ + var c = this.cylinder_low & 0xFF | this.cylinder_high << 8 & 0xFF00; + var h = this.head; + var s = this.sector & 0xFF; + + dbg_log("get_chs: c=" + c + " h=" + h + " s=" + s, LOG_DISK); + + return (c * this.head_count + h) * this.sectors_per_track + s - 1; +}; + +IDEInterface.prototype.get_lba28 = function() +{ + return this.sector & 0xFF | + this.cylinder_low << 8 & 0xFF00 | + this.cylinder_high << 16 & 0xFF0000 | + (this.head & 0xF) << 24; +}; + +IDEInterface.prototype.get_lba48 = function() +{ + // Note: Bits over 32 missing + return (this.sector & 0xFF | + this.cylinder_low << 8 & 0xFF00 | + this.cylinder_high << 16 & 0xFF0000 | + (this.sector >> 8) << 24 & 0xFF000000) >>> 0; +}; + +IDEInterface.prototype.get_lba = function(is_lba48) +{ + if(is_lba48) + { + return this.get_lba48(); + } + else if(this.is_lba) + { + return this.get_lba28(); + } + else + { + return this.get_chs(); + } +}; + +IDEInterface.prototype.get_count = function(is_lba48) +{ + if(is_lba48) + { + var count = this.bytecount; + if(count === 0) count = 0x10000; + return count; + } + else + { + var count = this.bytecount & 0xFF; + if(count === 0) count = 0x100; + return count; + } +}; + +IDEInterface.prototype.create_identify_packet = function() +{ + // http://bochs.sourceforge.net/cgi-bin/lxr/source/iodev/harddrv.cc#L2821 + + if(this.drive_head & 0x10) + { + // slave + this.data_allocate(0); + return; + } + + for(var i = 0; i < 512; i++) + { + this.data[i] = 0; + } + + var cylinder_count = Math.min(16383, this.cylinder_count); + + this.data_set([ + 0x40, this.is_atapi ? 0x85 : 0, + // 1 cylinders + cylinder_count, cylinder_count >> 8, + 0, 0, + + // 3 heads + this.head_count, this.head_count >> 8, + this.sectors_per_track / 512, this.sectors_per_track / 512 >> 8, + // 5 + 0, 512 >> 8, + // sectors per track + this.sectors_per_track, this.sectors_per_track >> 8, + 0, 0, 0, 0, 0, 0, + // 10-19 serial number + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // 20 + 3, 0, + 0, 2, + 4, 0, + // 23-26 firmware revision + 0, 0, 0, 0, 0, 0, 0, 0, + + // 27 model number + 56, 118, 32, 54, 68, 72, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, + 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, + + // 47 max value for set multiple mode + 0x80, 0, + 1, 0, + //0, 3, // capabilities, 2: Only LBA / 3: LBA and DMA + 0, 2, // capabilities, 2: Only LBA / 3: LBA and DMA + // 50 + 0, 0, + 0, 2, + 0, 2, + 7, 0, + + // 54 cylinders + cylinder_count, cylinder_count >> 8, + // 55 heads + this.head_count, this.head_count >> 8, + // 56 sectors per track + this.sectors_per_track, 0, + // capacity in sectors + this.sector_count & 0xFF, this.sector_count >> 8 & 0xFF, + this.sector_count >> 16 & 0xFF, this.sector_count >> 24 & 0xFF, + + 0, 0, + // 60 + this.sector_count & 0xFF, this.sector_count >> 8 & 0xFF, + this.sector_count >> 16 & 0xFF, this.sector_count >> 24 & 0xFF, + + 0, 0, + // 63, dma supported mode, dma selected mode + this.current_command === 0xA0 ? 0 : 7, this.current_command === 0xA0 ? 0 : 4, + //0, 0, // no DMA + + 0, 0, + // 65 + 30, 0, 30, 0, 30, 0, 30, 0, 0, 0, + // 70 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // 75 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // 80 + 0x7E, 0, 0, 0, 0, 0, 0, 0x74, 0, 0x40, + // 85 + 0, 0x40, 0, 0x74, 0, 0x40, 0, 0, 0, 0, + // 90 + 0, 0, 0, 0, 0, 0, 1, 0x60, 0, 0, + // 95 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // 100 + this.sector_count & 0xFF, this.sector_count >> 8 & 0xFF, + this.sector_count >> 16 & 0xFF, this.sector_count >> 24 & 0xFF, + ]); + + this.data_length = 512; + this.data_end = 512; +}; + +IDEInterface.prototype.data_allocate = function(len) +{ + this.data_allocate_noclear(len); + + for(var i = 0; i < (len + 3 >> 2); i++) + { + this.data32[i] = 0; + } +}; + +IDEInterface.prototype.data_allocate_noclear = function(len) +{ + if(this.data.length < len) + { + this.data = new Uint8Array(len + 3 & ~3); + this.data16 = new Uint16Array(this.data.buffer); + this.data32 = new Int32Array(this.data.buffer); + } + + this.data_length = len; + this.data_pointer = 0; +}; + +IDEInterface.prototype.data_set = function(data) +{ + this.data_allocate_noclear(data.length); + this.data.set(data); +}; + +IDEInterface.prototype.report_read_start = function() +{ + this.stats.loading = true; + this.bus.send("ide-read-start"); +}; + +IDEInterface.prototype.report_read_end = function(byte_count) +{ + this.stats.loading = false; + + var sector_count = byte_count / this.sector_size | 0; + this.stats.sectors_read += sector_count; + this.stats.bytes_read += byte_count; + + this.bus.send("ide-read-end", [this.nr, byte_count, sector_count]); +}; + +IDEInterface.prototype.report_write = function(byte_count) +{ + var sector_count = byte_count / this.sector_size | 0; + this.stats.sectors_written += sector_count; + this.stats.bytes_written += byte_count; + + this.bus.send("ide-write-end", [this.nr, byte_count, sector_count]); +}; + +IDEInterface.prototype.read_buffer = function(start, length, callback) +{ + const id = this.last_io_id++; + this.in_progress_io_ids.add(id); + + this.buffer.get(start, length, data => + { + if(this.cancelled_io_ids.delete(id)) + { + dbg_assert(!this.in_progress_io_ids.has(id)); + return; + } + + const removed = this.in_progress_io_ids.delete(id); + dbg_assert(removed); + + callback(data); + }); +}; + +IDEInterface.prototype.cancel_io_operations = function() +{ + for(const id of this.in_progress_io_ids) + { + this.cancelled_io_ids.add(id); + } + this.in_progress_io_ids.clear(); +}; + +IDEInterface.prototype.get_state = function() +{ + var state = []; + state[0] = this.bytecount; + state[1] = this.cylinder_count; + state[2] = this.cylinder_high; + state[3] = this.cylinder_low; + state[4] = this.data_pointer; + state[5] = 0; + state[6] = 0; + state[7] = 0; + state[8] = 0; + state[9] = this.drive_head; + state[10] = this.error; + state[11] = this.head; + state[12] = this.head_count; + state[13] = this.is_atapi; + state[14] = this.is_lba; + state[15] = this.lba_count; + state[16] = this.data; + state[17] = this.data_length; + state[18] = this.sector; + state[19] = this.sector_count; + state[20] = this.sector_size; + state[21] = this.sectors_per_drq; + state[22] = this.sectors_per_track; + state[23] = this.status; + state[24] = this.write_dest; + state[25] = this.current_command; + state[26] = this.data_end; + state[27] = this.current_atapi_command; + state[28] = this.buffer; + return state; +}; + +IDEInterface.prototype.set_state = function(state) +{ + this.bytecount = state[0]; + this.cylinder_count = state[1]; + this.cylinder_high = state[2]; + this.cylinder_low = state[3]; + this.data_pointer = state[4]; + + this.drive_head = state[9]; + this.error = state[10]; + this.head = state[11]; + this.head_count = state[12]; + this.is_atapi = state[13]; + this.is_lba = state[14]; + this.lba_count = state[15]; + this.data = state[16]; + this.data_length = state[17]; + this.sector = state[18]; + this.sector_count = state[19]; + this.sector_size = state[20]; + this.sectors_per_drq = state[21]; + this.sectors_per_track = state[22]; + this.status = state[23]; + this.write_dest = state[24]; + this.current_command = state[25]; + + this.data_end = state[26]; + this.current_atapi_command = state[27]; + + this.data16 = new Uint16Array(this.data.buffer); + this.data32 = new Int32Array(this.data.buffer); + + this.buffer && this.buffer.set_state(state[28]); +}; diff --git a/src/io.js b/src/io.js new file mode 100644 index 0000000..39f2de9 --- /dev/null +++ b/src/io.js @@ -0,0 +1,461 @@ +"use strict"; + +/** + * The ISA IO bus + * Devices register their ports here + * + * @constructor + * @param {CPU} cpu + */ +function IO(cpu) +{ + /** @const */ + this.ports = []; + + /** @const @type {CPU} */ + this.cpu = cpu; + + for(var i = 0; i < 0x10000; i++) + { + this.ports[i] = this.create_empty_entry(); + } + + var memory_size = cpu.memory_size[0]; + + for(var i = 0; (i << MMAP_BLOCK_BITS) < memory_size; i++) + { + // avoid sparse arrays + cpu.memory_map_read8[i] = cpu.memory_map_write8[i] = undefined; + cpu.memory_map_read32[i] = cpu.memory_map_write32[i] = undefined; + } + + this.mmap_register(memory_size, 0x100000000 - memory_size, + function(addr) { + // read outside of the memory size + dbg_log("Read from unmapped memory space, addr=" + h(addr >>> 0, 8), LOG_IO); + return 0xFF; + }, + function(addr, value) { + // write outside of the memory size + dbg_log("Write to unmapped memory space, addr=" + h(addr >>> 0, 8) + " value=" + h(value, 2), LOG_IO); + }, + function(addr) { + dbg_log("Read from unmapped memory space, addr=" + h(addr >>> 0, 8), LOG_IO); + return -1; + }, + function(addr, value) { + dbg_log("Write to unmapped memory space, addr=" + h(addr >>> 0, 8) + " value=" + h(value >>> 0, 8), LOG_IO); + } + ); +} + +IO.prototype.create_empty_entry = function() +{ + return { + read8: this.empty_port_read8, + read16: this.empty_port_read16, + read32: this.empty_port_read32, + + write8: this.empty_port_write, + write16: this.empty_port_write, + write32: this.empty_port_write, + + device: undefined, + }; +}; + +IO.prototype.empty_port_read8 = function() +{ + return 0xFF; +}; + +IO.prototype.empty_port_read16 = function() +{ + return 0xFFFF; +}; + +IO.prototype.empty_port_read32 = function() +{ + return -1; +}; + +IO.prototype.empty_port_write = function(x) +{ +}; + + +/** + * @param {number} port_addr + * @param {Object} device + * @param {function():number=} r8 + * @param {function():number=} r16 + * @param {function():number=} r32 + */ +IO.prototype.register_read = function(port_addr, device, r8, r16, r32) +{ + dbg_assert(typeof port_addr === "number"); + dbg_assert(typeof device === "object"); + dbg_assert(!r8 || typeof r8 === "function"); + dbg_assert(!r16 || typeof r16 === "function"); + dbg_assert(!r32 || typeof r32 === "function"); + dbg_assert(r8 || r16 || r32); + + if(DEBUG) + { + var fail = function(n) { + dbg_assert(false, "Overlapped read" + n + " " + h(port_addr, 4) + " (" + device.name + ")"); + return -1 >>> (32 - n) | 0; + }; + if(!r8) r8 = fail.bind(this, 8); + if(!r16) r16 = fail.bind(this, 16); + if(!r32) r32 = fail.bind(this, 32); + } + + if(r8) this.ports[port_addr].read8 = r8; + if(r16) this.ports[port_addr].read16 = r16; + if(r32) this.ports[port_addr].read32 = r32; + this.ports[port_addr].device = device; +}; + +/** + * @param {number} port_addr + * @param {Object} device + * @param {function(number)=} w8 + * @param {function(number)=} w16 + * @param {function(number)=} w32 + */ +IO.prototype.register_write = function(port_addr, device, w8, w16, w32) +{ + dbg_assert(typeof port_addr === "number"); + dbg_assert(typeof device === "object"); + dbg_assert(!w8 || typeof w8 === "function"); + dbg_assert(!w16 || typeof w16 === "function"); + dbg_assert(!w32 || typeof w32 === "function"); + dbg_assert(w8 || w16 || w32); + + if(DEBUG) + { + var fail = function(n) { + dbg_assert(false, "Overlapped write" + n + " " + h(port_addr) + " (" + device.name + ")"); + }; + if(!w8) w8 = fail.bind(this, 8); + if(!w16) w16 = fail.bind(this, 16); + if(!w32) w32 = fail.bind(this, 32); + } + + if(w8) this.ports[port_addr].write8 = w8; + if(w16) this.ports[port_addr].write16 = w16; + if(w32) this.ports[port_addr].write32 = w32; + this.ports[port_addr].device = device; +}; + +/** + * > Any two consecutive 8-bit ports can be treated as a 16-bit port; + * > and four consecutive 8-bit ports can be treated as a 32-bit port + * > http://css.csail.mit.edu/6.858/2012/readings/i386/s08_01.htm + * + * This info is not correct for all ports, but handled by the following functions + * + * Register the write of 2 or 4 consecutive 8-bit ports, 1 or 2 16-bit + * ports and 0 or 1 32-bit ports + * + * @param {number} port_addr + * @param {!Object} device + * @param {function():number} r8_1 + * @param {function():number} r8_2 + * @param {function():number=} r8_3 + * @param {function():number=} r8_4 + */ +IO.prototype.register_read_consecutive = function(port_addr, device, r8_1, r8_2, r8_3, r8_4) +{ + dbg_assert(arguments.length === 4 || arguments.length === 6); + + function r16_1() + { + return r8_1.call(this) | + r8_2.call(this) << 8; + } + function r16_2() + { + return r8_3.call(this) | + r8_4.call(this) << 8; + } + function r32() + { + return r8_1.call(this) | + r8_2.call(this) << 8 | + r8_3.call(this) << 16 | + r8_4.call(this) << 24; + } + + if(r8_3 && r8_4) + { + this.register_read(port_addr, device, r8_1, r16_1, r32); + this.register_read(port_addr + 1, device, r8_2); + this.register_read(port_addr + 2, device, r8_3, r16_2); + this.register_read(port_addr + 3, device, r8_4); + } + else + { + this.register_read(port_addr, device, r8_1, r16_1); + this.register_read(port_addr + 1, device, r8_2); + } +}; + +/** + * @param {number} port_addr + * @param {!Object} device + * @param {function(number)} w8_1 + * @param {function(number)} w8_2 + * @param {function(number)=} w8_3 + * @param {function(number)=} w8_4 + */ +IO.prototype.register_write_consecutive = function(port_addr, device, w8_1, w8_2, w8_3, w8_4) +{ + dbg_assert(arguments.length === 4 || arguments.length === 6); + + function w16_1(data) + { + w8_1.call(this, data & 0xFF); + w8_2.call(this, data >> 8 & 0xFF); + } + function w16_2(data) + { + w8_3.call(this, data & 0xFF); + w8_4.call(this, data >> 8 & 0xFF); + } + function w32(data) + { + w8_1.call(this, data & 0xFF); + w8_2.call(this, data >> 8 & 0xFF); + w8_3.call(this, data >> 16 & 0xFF); + w8_4.call(this, data >>> 24); + } + + if(w8_3 && w8_4) + { + this.register_write(port_addr, device, w8_1, w16_1, w32); + this.register_write(port_addr + 1, device, w8_2); + this.register_write(port_addr + 2, device, w8_3, w16_2); + this.register_write(port_addr + 3, device, w8_4); + } + else + { + this.register_write(port_addr, device, w8_1, w16_1); + this.register_write(port_addr + 1, device, w8_2); + } +}; + +IO.prototype.mmap_read32_shim = function(addr) +{ + var aligned_addr = addr >>> MMAP_BLOCK_BITS; + var fn = this.cpu.memory_map_read8[aligned_addr]; + + return fn(addr) | fn(addr + 1) << 8 | + fn(addr + 2) << 16 | fn(addr + 3) << 24; +}; + +IO.prototype.mmap_write32_shim = function(addr, value) +{ + var aligned_addr = addr >>> MMAP_BLOCK_BITS; + var fn = this.cpu.memory_map_write8[aligned_addr]; + + fn(addr, value & 0xFF); + fn(addr + 1, value >> 8 & 0xFF); + fn(addr + 2, value >> 16 & 0xFF); + fn(addr + 3, value >>> 24); +}; + +/** + * @param {number} addr + * @param {number} size + * @param {*} read_func8 + * @param {*} write_func8 + * @param {*=} read_func32 + * @param {*=} write_func32 + */ +IO.prototype.mmap_register = function(addr, size, read_func8, write_func8, read_func32, write_func32) +{ + dbg_log("mmap_register addr=" + h(addr >>> 0, 8) + " size=" + h(size, 8), LOG_IO); + + dbg_assert((addr & MMAP_BLOCK_SIZE - 1) === 0); + dbg_assert(size && (size & MMAP_BLOCK_SIZE - 1) === 0); + + if(!read_func32) + read_func32 = this.mmap_read32_shim.bind(this); + + if(!write_func32) + write_func32 = this.mmap_write32_shim.bind(this); + + var aligned_addr = addr >>> MMAP_BLOCK_BITS; + + for(; size > 0; aligned_addr++) + { + this.cpu.memory_map_read8[aligned_addr] = read_func8; + this.cpu.memory_map_write8[aligned_addr] = write_func8; + this.cpu.memory_map_read32[aligned_addr] = read_func32; + this.cpu.memory_map_write32[aligned_addr] = write_func32; + + size -= MMAP_BLOCK_SIZE; + } +}; + + +IO.prototype.port_write8 = function(port_addr, data) +{ + var entry = this.ports[port_addr]; + + if(entry.write8 === this.empty_port_write || LOG_ALL_IO) + { + dbg_log( + "write8 port #" + h(port_addr, 4) + " <- " + h(data, 2) + this.get_port_description(port_addr), + LOG_IO + ); + } + return entry.write8.call(entry.device, data); +}; + +IO.prototype.port_write16 = function(port_addr, data) +{ + var entry = this.ports[port_addr]; + + if(entry.write16 === this.empty_port_write || LOG_ALL_IO) + { + dbg_log( + "write16 port #" + h(port_addr, 4) + " <- " + h(data, 4) + this.get_port_description(port_addr), + LOG_IO + ); + } + return entry.write16.call(entry.device, data); +}; + +IO.prototype.port_write32 = function(port_addr, data) +{ + var entry = this.ports[port_addr]; + + if(entry.write32 === this.empty_port_write || LOG_ALL_IO) + { + dbg_log( + "write32 port #" + h(port_addr, 4) + " <- " + h(data >>> 0, 8) + this.get_port_description(port_addr), + LOG_IO + ); + } + return entry.write32.call(entry.device, data); +}; + +IO.prototype.port_read8 = function(port_addr) +{ + var entry = this.ports[port_addr]; + + if(entry.read8 === this.empty_port_read8 || LOG_ALL_IO) + { + dbg_log( + "read8 port #" + h(port_addr, 4) + this.get_port_description(port_addr), + LOG_IO + ); + } + var value = entry.read8.call(entry.device); + dbg_assert(value < 0x100, "8 bit port returned large value: " + h(port_addr)); + return value; +}; + +IO.prototype.port_read16 = function(port_addr) +{ + var entry = this.ports[port_addr]; + + if(entry.read16 === this.empty_port_read16 || LOG_ALL_IO) + { + dbg_log( + "read16 port #" + h(port_addr, 4) + this.get_port_description(port_addr), + LOG_IO + ); + } + var value = entry.read16.call(entry.device); + dbg_assert(value < 0x10000 && value >= 0, "16 bit port returned large value: " + h(port_addr)); + return value; +}; + +IO.prototype.port_read32 = function(port_addr) +{ + var entry = this.ports[port_addr]; + + if(entry.read32 === this.empty_port_read32 || LOG_ALL_IO) + { + dbg_log( + "read32 port #" + h(port_addr, 4) + this.get_port_description(port_addr), + LOG_IO + ); + } + var value = entry.read32.call(entry.device); + dbg_assert((value | 0) === value); + return value; +}; + +// via seabios ioport.h +var debug_port_list = { + 0x0004: "PORT_DMA_ADDR_2", + 0x0005: "PORT_DMA_CNT_2", + 0x000a: "PORT_DMA1_MASK_REG", + 0x000b: "PORT_DMA1_MODE_REG", + 0x000c: "PORT_DMA1_CLEAR_FF_REG", + 0x000d: "PORT_DMA1_MASTER_CLEAR", + 0x0020: "PORT_PIC1_CMD", + 0x0021: "PORT_PIC1_DATA", + 0x0040: "PORT_PIT_COUNTER0", + 0x0041: "PORT_PIT_COUNTER1", + 0x0042: "PORT_PIT_COUNTER2", + 0x0043: "PORT_PIT_MODE", + 0x0060: "PORT_PS2_DATA", + 0x0061: "PORT_PS2_CTRLB", + 0x0064: "PORT_PS2_STATUS", + 0x0070: "PORT_CMOS_INDEX", + 0x0071: "PORT_CMOS_DATA", + 0x0080: "PORT_DIAG", + 0x0081: "PORT_DMA_PAGE_2", + 0x0092: "PORT_A20", + 0x00a0: "PORT_PIC2_CMD", + 0x00a1: "PORT_PIC2_DATA", + 0x00b2: "PORT_SMI_CMD", + 0x00b3: "PORT_SMI_STATUS", + 0x00d4: "PORT_DMA2_MASK_REG", + 0x00d6: "PORT_DMA2_MODE_REG", + 0x00da: "PORT_DMA2_MASTER_CLEAR", + 0x00f0: "PORT_MATH_CLEAR", + 0x0170: "PORT_ATA2_CMD_BASE", + 0x01f0: "PORT_ATA1_CMD_BASE", + 0x0278: "PORT_LPT2", + 0x02e8: "PORT_SERIAL4", + 0x02f8: "PORT_SERIAL2", + 0x0374: "PORT_ATA2_CTRL_BASE", + 0x0378: "PORT_LPT1", + 0x03e8: "PORT_SERIAL3", + //0x03f4: "PORT_ATA1_CTRL_BASE", + 0x03f0: "PORT_FD_BASE", + 0x03f2: "PORT_FD_DOR", + 0x03f4: "PORT_FD_STATUS", + 0x03f5: "PORT_FD_DATA", + 0x03f6: "PORT_HD_DATA", + 0x03f7: "PORT_FD_DIR", + 0x03f8: "PORT_SERIAL1", + 0x0cf8: "PORT_PCI_CMD", + 0x0cf9: "PORT_PCI_REBOOT", + 0x0cfc: "PORT_PCI_DATA", + 0x0402: "PORT_BIOS_DEBUG", + 0x0510: "PORT_QEMU_CFG_CTL", + 0x0511: "PORT_QEMU_CFG_DATA", + 0xb000: "PORT_ACPI_PM_BASE", + 0xb100: "PORT_SMB_BASE", + 0x8900: "PORT_BIOS_APM" +}; + +IO.prototype.get_port_description = function(addr) +{ + if(debug_port_list[addr]) + { + return " (" + debug_port_list[addr] + ")"; + } + else + { + return ""; + } +}; diff --git a/src/ioapic.js b/src/ioapic.js new file mode 100644 index 0000000..793ff85 --- /dev/null +++ b/src/ioapic.js @@ -0,0 +1,364 @@ +"use strict"; + +// http://download.intel.com/design/chipsets/datashts/29056601.pdf + +/** @const */ +var IOAPIC_ADDRESS = 0xFEC00000; + +/** @const */ +var IOREGSEL = 0; + +/** @const */ +var IOWIN = 0x10; + +/** @const */ +var IOAPIC_IRQ_COUNT = 24; + +/** @const */ +var IOAPIC_ID = 0; // must match value in seabios + + +/** @const */ +var IOAPIC_CONFIG_TRIGGER_MODE_LEVEL = 1 << 15; + +/** @const */ +var IOAPIC_CONFIG_MASKED = 1 << 16; + +/** @const */ +var IOAPIC_CONFIG_DELIVS = 1 << 12; + +/** @const */ +var IOAPIC_CONFIG_REMOTE_IRR = 1 << 14; + +/** @const */ +var IOAPIC_CONFIG_READONLY_MASK = IOAPIC_CONFIG_REMOTE_IRR | IOAPIC_CONFIG_DELIVS | 0xFFFE0000; + +/** @const */ +var IOAPIC_DELIVERY_FIXED = 0; + +/** @const */ +var IOAPIC_DELIVERY_LOWEST_PRIORITY = 1; + +/** @const */ +var IOAPIC_DELIVERY_NMI = 4; + +/** @const */ +var IOAPIC_DELIVERY_INIT = 5; + + +/** + * @constructor + * @param {CPU} cpu + */ +function IOAPIC(cpu) +{ + /** @type {CPU} */ + this.cpu = cpu; + + this.ioredtbl_config = new Int32Array(IOAPIC_IRQ_COUNT); + this.ioredtbl_destination = new Int32Array(IOAPIC_IRQ_COUNT); + + for(var i = 0; i < this.ioredtbl_config.length; i++) + { + // disable interrupts + this.ioredtbl_config[i] = IOAPIC_CONFIG_MASKED; + } + + // IOAPIC register selection + this.ioregsel = 0; + + this.ioapic_id = IOAPIC_ID; + + this.irr = 0; + this.irq_value = 0; + + dbg_assert(MMAP_BLOCK_SIZE >= 0x20); + cpu.io.mmap_register(IOAPIC_ADDRESS, MMAP_BLOCK_SIZE, + (addr) => + { + addr = addr - IOAPIC_ADDRESS | 0; + + if(addr >= IOWIN && addr < IOWIN + 4) + { + const byte = addr - IOWIN; + dbg_log("ioapic read8 byte " + byte + " " + h(this.ioregsel), LOG_APIC); + return this.read(this.ioregsel) >> (8 * byte) & 0xFF; + } + else + { + dbg_log("Unexpected IOAPIC register read: " + h(addr >>> 0), LOG_APIC); + dbg_assert(false); + return 0; + } + }, + (addr, value) => + { + dbg_assert(false, "unsupported write8 from ioapic: " + h(addr >>> 0)); + }, + (addr) => + { + addr = addr - IOAPIC_ADDRESS | 0; + + if(addr === IOREGSEL) + { + return this.ioregsel; + } + else if(addr === IOWIN) + { + return this.read(this.ioregsel); + } + else + { + dbg_log("Unexpected IOAPIC register read: " + h(addr >>> 0), LOG_APIC); + dbg_assert(false); + return 0; + } + }, + (addr, value) => + { + addr = addr - IOAPIC_ADDRESS | 0; + + if(addr === IOREGSEL) + { + this.ioregsel = value; + } + else if(addr === IOWIN) + { + this.write(this.ioregsel, value); + } + else + { + dbg_log("Unexpected IOAPIC register write: " + h(addr >>> 0) + " <- " + h(value >>> 0, 8), LOG_APIC); + dbg_assert(false); + } + }); +} + +IOAPIC.prototype.remote_eoi = function(vector) +{ + for(var i = 0; i < IOAPIC_IRQ_COUNT; i++) + { + var config = this.ioredtbl_config[i]; + + if((config & 0xFF) === vector && (config & IOAPIC_CONFIG_REMOTE_IRR)) + { + dbg_log("Clear remote IRR for irq=" + h(i), LOG_APIC); + this.ioredtbl_config[i] &= ~IOAPIC_CONFIG_REMOTE_IRR; + this.check_irq(i); + } + } +}; + +IOAPIC.prototype.check_irq = function(irq) +{ + var mask = 1 << irq; + + if((this.irr & mask) === 0) + { + return; + } + + var config = this.ioredtbl_config[irq]; + + if((config & IOAPIC_CONFIG_MASKED) === 0) + { + var delivery_mode = config >> 8 & 7; + var destination_mode = config >> 11 & 1; + var vector = config & 0xFF; + var destination = this.ioredtbl_destination[irq] >>> 24; + var is_level = (config & IOAPIC_CONFIG_TRIGGER_MODE_LEVEL) === IOAPIC_CONFIG_TRIGGER_MODE_LEVEL; + + if((config & IOAPIC_CONFIG_TRIGGER_MODE_LEVEL) === 0) + { + this.irr &= ~mask; + } + else + { + this.ioredtbl_config[irq] |= IOAPIC_CONFIG_REMOTE_IRR; + + if(config & IOAPIC_CONFIG_REMOTE_IRR) + { + dbg_log("No route: level interrupt and remote IRR still set", LOG_APIC); + return; + } + } + + if(delivery_mode === IOAPIC_DELIVERY_FIXED || delivery_mode === IOAPIC_DELIVERY_LOWEST_PRIORITY) + { + this.cpu.devices.apic.route(vector, delivery_mode, is_level, destination, destination_mode); + } + else + { + dbg_assert(false, "TODO"); + } + + this.ioredtbl_config[irq] &= ~IOAPIC_CONFIG_DELIVS; + } +}; + +IOAPIC.prototype.set_irq = function(i) +{ + if(i >= IOAPIC_IRQ_COUNT) + { + dbg_assert(false, "Bad irq: " + i, LOG_APIC); + return; + } + + var mask = 1 << i; + + if((this.irq_value & mask) === 0) + { + APIC_LOG_VERBOSE && dbg_log("apic set irq " + i, LOG_APIC); + + this.irq_value |= mask; + + var config = this.ioredtbl_config[i]; + if((config & (IOAPIC_CONFIG_TRIGGER_MODE_LEVEL|IOAPIC_CONFIG_MASKED)) === + IOAPIC_CONFIG_MASKED) + { + // edge triggered and masked + return; + } + + this.irr |= mask; + + this.check_irq(i); + } +}; + +IOAPIC.prototype.clear_irq = function(i) +{ + if(i >= IOAPIC_IRQ_COUNT) + { + dbg_assert(false, "Bad irq: " + i, LOG_APIC); + return; + } + + var mask = 1 << i; + + if((this.irq_value & mask) === mask) + { + this.irq_value &= ~mask; + + var config = this.ioredtbl_config[i]; + if(config & IOAPIC_CONFIG_TRIGGER_MODE_LEVEL) + { + this.irr &= ~mask; + } + } +}; + +IOAPIC.prototype.read = function(reg) +{ + if(reg === 0) + { + dbg_log("IOAPIC Read id", LOG_APIC); + return this.ioapic_id << 24; + } + else if(reg === 1) + { + dbg_log("IOAPIC Read version", LOG_APIC); + return 0x11 | IOAPIC_IRQ_COUNT - 1 << 16; + } + else if(reg === 2) + { + dbg_log("IOAPIC Read arbitration id", LOG_APIC); + return this.ioapic_id << 24; + } + else if(reg >= 0x10 && reg < 0x10 + 2 * IOAPIC_IRQ_COUNT) + { + var irq = reg - 0x10 >> 1; + var index = reg & 1; + + if(index) + { + var value = this.ioredtbl_destination[irq]; + dbg_log("IOAPIC Read destination irq=" + h(irq) + " -> " + h(value, 8), LOG_APIC); + } + else + { + var value = this.ioredtbl_config[irq]; + dbg_log("IOAPIC Read config irq=" + h(irq) + " -> " + h(value, 8), LOG_APIC); + } + return value; + } + else + { + dbg_log("IOAPIC register read outside of range " + h(reg), LOG_APIC); + dbg_assert(false); + return 0; + } +}; + +IOAPIC.prototype.write = function(reg, value) +{ + //dbg_log("IOAPIC write " + h(reg) + " <- " + h(value, 8), LOG_APIC); + + if(reg === 0) + { + this.ioapic_id = value >>> 24 & 0x0F; + } + else if(reg === 1 || reg === 2) + { + dbg_log("Invalid write: " + reg, LOG_APIC); + } + else if(reg >= 0x10 && reg < 0x10 + 2 * IOAPIC_IRQ_COUNT) + { + var irq = reg - 0x10 >> 1; + var index = reg & 1; + + if(index) + { + this.ioredtbl_destination[irq] = value & 0xFF000000; + dbg_log("Write destination " + h(value >>> 0, 8) + " irq=" + h(irq) + " dest=" + h(value >>> 24, 2), LOG_APIC); + } + else + { + var old_value = this.ioredtbl_config[irq]; + this.ioredtbl_config[irq] = value & ~IOAPIC_CONFIG_READONLY_MASK | old_value & IOAPIC_CONFIG_READONLY_MASK; + + var vector = value & 0xFF; + var delivery_mode = value >> 8 & 7; + var destination_mode = value >> 11 & 1; + var is_level = value >> 15 & 1; + var disabled = value >> 16 & 1; + + dbg_log("Write config " + h(value >>> 0, 8) + + " irq=" + h(irq) + + " vector=" + h(vector, 2) + + " deliverymode=" + DELIVERY_MODES[delivery_mode] + + " destmode=" + DESTINATION_MODES[destination_mode] + + " is_level=" + is_level + + " disabled=" + disabled, LOG_APIC); + + this.check_irq(irq); + } + } + else + { + dbg_log("IOAPIC register write outside of range " + h(reg) + ": " + h(value >>> 0, 8), LOG_APIC); + dbg_assert(false); + } +}; + +IOAPIC.prototype.get_state = function() +{ + var state = []; + state[0] = this.ioredtbl_config; + state[1] = this.ioredtbl_destination; + state[2] = this.ioregsel; + state[3] = this.ioapic_id; + state[4] = this.irr; + state[5] = this.irq_value; + return state; +}; + +IOAPIC.prototype.set_state = function(state) +{ + this.ioredtbl_config = state[0]; + this.ioredtbl_destination = state[1]; + this.ioregsel = state[2]; + this.ioapic_id = state[3]; + this.irr = state[4]; + this.irq_value = state[5]; +}; diff --git a/src/kernel.js b/src/kernel.js new file mode 100644 index 0000000..16a0a89 --- /dev/null +++ b/src/kernel.js @@ -0,0 +1,235 @@ +"use strict"; + +// https://www.kernel.org/doc/Documentation/x86/boot.txt + +const LINUX_BOOT_HDR_SETUP_SECTS = 0x1F1; +const LINUX_BOOT_HDR_SYSSIZE = 0x1F4; +const LINUX_BOOT_HDR_VIDMODE = 0x1FA; +const LINUX_BOOT_HDR_BOOT_FLAG = 0x1FE; +const LINUX_BOOT_HDR_HEADER = 0x202; +const LINUX_BOOT_HDR_VERSION = 0x206; +const LINUX_BOOT_HDR_TYPE_OF_LOADER = 0x210; +const LINUX_BOOT_HDR_LOADFLAGS = 0x211; +const LINUX_BOOT_HDR_CODE32_START = 0x214; +const LINUX_BOOT_HDR_RAMDISK_IMAGE = 0x218; +const LINUX_BOOT_HDR_RAMDISK_SIZE = 0x21C; +const LINUX_BOOT_HDR_HEAP_END_PTR = 0x224; +const LINUX_BOOT_HDR_CMD_LINE_PTR = 0x228; +const LINUX_BOOT_HDR_INITRD_ADDR_MAX = 0x22C; +const LINUX_BOOT_HDR_KERNEL_ALIGNMENT = 0x230; +const LINUX_BOOT_HDR_RELOCATABLE_KERNEL = 0x234; +const LINUX_BOOT_HDR_MIN_ALIGNMENT = 0x235; +const LINUX_BOOT_HDR_XLOADFLAGS = 0x236; +const LINUX_BOOT_HDR_CMDLINE_SIZE = 0x238; +const LINUX_BOOT_HDR_PAYLOAD_OFFSET = 0x248; +const LINUX_BOOT_HDR_PAYLOAD_LENGTH = 0x24C; +const LINUX_BOOT_HDR_PREF_ADDRESS = 0x258; +const LINUX_BOOT_HDR_INIT_SIZE = 0x260; + +const LINUX_BOOT_HDR_CHECKSUM1 = 0xAA55; +const LINUX_BOOT_HDR_CHECKSUM2 = 0x53726448; + +const LINUX_BOOT_HDR_TYPE_OF_LOADER_NOT_ASSIGNED = 0xFF; + +const LINUX_BOOT_HDR_LOADFLAGS_LOADED_HIGH = 1 << 0; +const LINUX_BOOT_HDR_LOADFLAGS_QUIET_FLAG = 1 << 5; +const LINUX_BOOT_HDR_LOADFLAGS_KEEP_SEGMENTS = 1 << 6; +const LINUX_BOOT_HDR_LOADFLAGS_CAN_USE_HEAPS = 1 << 7; + + +function load_kernel(mem8, bzimage, initrd, cmdline) +{ + dbg_log("Trying to load kernel of size " + bzimage.byteLength); + + const KERNEL_HIGH_ADDRESS = 0x100000; + + // Put the initrd at the 64 MB boundary. This means the minimum memory size + // is 64 MB plus the size of the initrd. + // Note: If set too low, kernel may fail to load the initrd with "invalid magic at start of compressed archive" + const INITRD_ADDRESS = 64 << 20; + + const quiet = false; + + const bzimage8 = new Uint8Array(bzimage); + const bzimage16 = new Uint16Array(bzimage); + const bzimage32 = new Uint32Array(bzimage); + + const setup_sects = bzimage8[LINUX_BOOT_HDR_SETUP_SECTS] || 4; + const syssize = bzimage32[LINUX_BOOT_HDR_SYSSIZE >> 2] << 4; + + const vidmode = bzimage16[LINUX_BOOT_HDR_VIDMODE >> 1]; + + const checksum1 = bzimage16[LINUX_BOOT_HDR_BOOT_FLAG >> 1]; + if(checksum1 !== LINUX_BOOT_HDR_CHECKSUM1) + { + dbg_log("Bad checksum1: " + h(checksum1)); + return; + } + + // Not aligned, so split into two 16-bit reads + const checksum2 = + bzimage16[LINUX_BOOT_HDR_HEADER >> 1] | + bzimage16[LINUX_BOOT_HDR_HEADER + 2 >> 1] << 16; + if(checksum2 !== LINUX_BOOT_HDR_CHECKSUM2) + { + dbg_log("Bad checksum2: " + h(checksum2)); + return; + } + + const protocol = bzimage16[LINUX_BOOT_HDR_VERSION >> 1]; + dbg_assert(protocol >= 0x202); // older not supported by us + + const flags = bzimage8[LINUX_BOOT_HDR_LOADFLAGS]; + dbg_assert(flags & LINUX_BOOT_HDR_LOADFLAGS_LOADED_HIGH); // low kernels not supported by us + + // we don't relocate the kernel, so we don't care much about most of these + + const flags2 = bzimage16[LINUX_BOOT_HDR_XLOADFLAGS >> 1]; + const initrd_addr_max = bzimage32[LINUX_BOOT_HDR_INITRD_ADDR_MAX >> 2]; + const kernel_alignment = bzimage32[LINUX_BOOT_HDR_KERNEL_ALIGNMENT >> 2]; + const relocatable_kernel = bzimage8[LINUX_BOOT_HDR_RELOCATABLE_KERNEL]; + const min_alignment = bzimage8[LINUX_BOOT_HDR_MIN_ALIGNMENT]; + const cmdline_size = bzimage32[LINUX_BOOT_HDR_CMDLINE_SIZE >> 2]; + const payload_offset = bzimage32[LINUX_BOOT_HDR_PAYLOAD_OFFSET >> 2]; + const payload_length = bzimage32[LINUX_BOOT_HDR_PAYLOAD_LENGTH >> 2]; + const pref_address = bzimage32[LINUX_BOOT_HDR_PREF_ADDRESS >> 2]; + const pref_address_high = bzimage32[LINUX_BOOT_HDR_PREF_ADDRESS + 4 >> 2]; + const init_size = bzimage32[LINUX_BOOT_HDR_INIT_SIZE >> 2]; + + dbg_log("kernel boot protocol version: " + h(protocol)); + dbg_log("flags=" + h(flags) + " xflags=" + h(flags2)); + dbg_log("code32_start=" + h(bzimage32[LINUX_BOOT_HDR_CODE32_START >> 2])); + dbg_log("initrd_addr_max=" + h(initrd_addr_max)); + dbg_log("kernel_alignment=" + h(kernel_alignment)); + dbg_log("relocatable=" + relocatable_kernel); + dbg_log("min_alignment=" + h(min_alignment)); + dbg_log("cmdline max=" + h(cmdline_size)); + dbg_log("payload offset=" + h(payload_offset) + " size=" + h(payload_length)); + dbg_log("pref_address=" + h(pref_address_high) + ":" + h(pref_address)); + dbg_log("init_size=" + h(init_size)); + + const real_mode_segment = 0x8000; + const base_ptr = real_mode_segment << 4; + + const heap_end = 0xE000; + const heap_end_ptr = heap_end - 0x200; + + // fill in the kernel boot header with infos the kernel needs to know + + bzimage8[LINUX_BOOT_HDR_TYPE_OF_LOADER] = LINUX_BOOT_HDR_TYPE_OF_LOADER_NOT_ASSIGNED; + + const new_flags = + (quiet ? flags | LINUX_BOOT_HDR_LOADFLAGS_QUIET_FLAG : flags & ~LINUX_BOOT_HDR_LOADFLAGS_QUIET_FLAG) + & ~LINUX_BOOT_HDR_LOADFLAGS_KEEP_SEGMENTS + | LINUX_BOOT_HDR_LOADFLAGS_CAN_USE_HEAPS; + bzimage8[LINUX_BOOT_HDR_LOADFLAGS] = new_flags; + + bzimage16[LINUX_BOOT_HDR_HEAP_END_PTR >> 1] = heap_end_ptr; + + // should parse the vga=... paramter from cmdline here, but we don't really care + bzimage16[LINUX_BOOT_HDR_VIDMODE >> 1] = 0xFFFF; // normal + + dbg_log("heap_end_ptr=" + h(heap_end_ptr)); + + cmdline += "\x00"; + dbg_assert(cmdline.length < cmdline_size); + + const cmd_line_ptr = base_ptr + heap_end; + dbg_log("cmd_line_ptr=" + h(cmd_line_ptr)); + + bzimage32[LINUX_BOOT_HDR_CMD_LINE_PTR >> 2] = cmd_line_ptr; + for(let i = 0; i < cmdline.length; i++) + { + mem8[cmd_line_ptr + i] = cmdline.charCodeAt(i); + } + + const prot_mode_kernel_start = (setup_sects + 1) * 512; + dbg_log("prot_mode_kernel_start=" + h(prot_mode_kernel_start)); + + const real_mode_kernel = new Uint8Array(bzimage, 0, prot_mode_kernel_start); + const protected_mode_kernel = new Uint8Array(bzimage, prot_mode_kernel_start); + + let ramdisk_address = 0; + let ramdisk_size = 0; + + if(initrd) + { + ramdisk_address = INITRD_ADDRESS; + ramdisk_size = initrd.byteLength; + + dbg_assert(KERNEL_HIGH_ADDRESS + protected_mode_kernel.length < ramdisk_address); + + mem8.set(new Uint8Array(initrd), ramdisk_address); + } + + bzimage32[LINUX_BOOT_HDR_RAMDISK_IMAGE >> 2] = ramdisk_address; + bzimage32[LINUX_BOOT_HDR_RAMDISK_SIZE >> 2] = ramdisk_size; + + dbg_assert(base_ptr + real_mode_kernel.length < 0xA0000); + + mem8.set(real_mode_kernel, base_ptr); + mem8.set(protected_mode_kernel, KERNEL_HIGH_ADDRESS); + + return { + option_rom: + { + name: "genroms/kernel.bin", + data: make_linux_boot_rom(real_mode_segment, heap_end), + } + }; +} + +function make_linux_boot_rom(real_mode_segment, heap_end) +{ + // This rom will be executed by seabios after its initialisation + // It sets up segment registers, the stack and calls the kernel real mode entry point + + const SIZE = 0x200; + + const data8 = new Uint8Array(0x100); + const data16 = new Uint16Array(data8.buffer); + + data16[0] = 0xAA55; + data8[2] = SIZE / 0x200; + + let i = 3; + + data8[i++] = 0xFA; // cli + data8[i++] = 0xB8; // mov ax, real_mode_segment + data8[i++] = real_mode_segment >> 0; + data8[i++] = real_mode_segment >> 8; + data8[i++] = 0x8E; // mov es, ax + data8[i++] = 0xC0; + data8[i++] = 0x8E; // mov ds, ax + data8[i++] = 0xD8; + data8[i++] = 0x8E; // mov fs, ax + data8[i++] = 0xE0; + data8[i++] = 0x8E; // mov gs, ax + data8[i++] = 0xE8; + data8[i++] = 0x8E; // mov ss, ax + data8[i++] = 0xD0; + data8[i++] = 0xBC; // mov sp, heap_end + data8[i++] = heap_end >> 0; + data8[i++] = heap_end >> 8; + data8[i++] = 0xEA; // jmp (real_mode_segment+0x20):0x0 + data8[i++] = 0x00; + data8[i++] = 0x00; + data8[i++] = real_mode_segment + 0x20 >> 0; + data8[i++] = real_mode_segment + 0x20 >> 8; + + dbg_assert(i < SIZE); + + const checksum_index = i; + data8[checksum_index] = 0; + + let checksum = 0; + + for(let i = 0; i < data8.length; i++) + { + checksum += data8[i]; + } + + data8[checksum_index] = -checksum; + + return data8; +} diff --git a/src/lib.js b/src/lib.js new file mode 100644 index 0000000..683bce7 --- /dev/null +++ b/src/lib.js @@ -0,0 +1,703 @@ +"use strict"; + +var goog = goog || {}; +goog.exportSymbol = function() {}; +goog.exportProperty = function() {}; + +var v86util = v86util || {}; + +// pad string with spaces on the right +v86util.pads = function(str, len) +{ + str = (str || str === 0) ? str + "" : ""; + return str.padEnd(len, " "); +}; + +// pad string with zeros on the left +v86util.pad0 = function(str, len) +{ + str = (str || str === 0) ? str + "" : ""; + return str.padStart(len, "0"); +}; + +// generates array given size with zeros +v86util.zeros = function(size) +{ + return Array(size).fill(0); +}; + +// generates [0, 1, 2, ..., size-1] +v86util.range = function(size) +{ + return Array.from(Array(size).keys()); +}; + +v86util.view = function(constructor, memory, offset, length) +{ + return new Proxy({}, + { + get: function(target, property, receiver) + { + const b = new constructor(memory.buffer, offset, length); + const x = b[property]; + if(typeof x === "function") + { + return x.bind(b); + } + dbg_assert(/^\d+$/.test(property) || property === "buffer" || property === "length" || + property === "BYTES_PER_ELEMENT" || property === "byteOffset"); + return x; + }, + set: function(target, property, value, receiver) + { + dbg_assert(/^\d+$/.test(property)); + new constructor(memory.buffer, offset, length)[property] = value; + return true; + }, + }); +}; + +/** + * number to hex + * @param {number} n + * @param {number=} len + * @return {string} + */ +function h(n, len) +{ + if(!n) + { + var str = ""; + } + else + { + var str = n.toString(16); + } + + return "0x" + v86util.pad0(str.toUpperCase(), len || 1); +} + +function hex_dump(buffer) +{ + function hex(n, len) + { + return v86util.pad0(n.toString(16).toUpperCase(), len); + } + + const result = []; + let offset = 0; + + for(; offset + 15 < buffer.length; offset += 16) + { + let line = hex(offset, 5) + " "; + + for(let j = 0; j < 0x10; j++) + { + line += hex(buffer[offset + j], 2) + " "; + } + + line += " "; + + for(let j = 0; j < 0x10; j++) + { + const x = buffer[offset + j]; + line += (x >= 33 && x !== 34 && x !== 92 && x <= 126) ? String.fromCharCode(x) : "."; + } + + result.push(line); + } + + let line = hex(offset, 5) + " "; + + for(; offset < buffer.length; offset++) + { + line += hex(buffer[offset], 2) + " "; + } + + const remainder = offset & 0xF; + line += " ".repeat(0x10 - remainder); + line += " "; + + for(let j = 0; j < remainder; j++) + { + const x = buffer[offset + j]; + line += (x >= 33 && x !== 34 && x !== 92 && x <= 126) ? String.fromCharCode(x) : "."; + } + + result.push(line); + + return "\n" + result.join("\n") + "\n"; +} + +if(typeof crypto !== "undefined" && crypto.getRandomValues) +{ + let rand_data = new Int32Array(1); + + v86util.get_rand_int = function() + { + crypto.getRandomValues(rand_data); + return rand_data[0]; + }; +} +else if(typeof require !== "undefined") +{ + /** @type {{ randomBytes: Function }} */ + const crypto = require("crypto"); + + v86util.get_rand_int = function() + { + return crypto.randomBytes(4)["readInt32LE"](0); + }; +} +else +{ + dbg_assert(false, "Unsupported platform: No cryptographic random values"); +} + +(function() +{ + if(typeof Math.clz32 === "function" && Math.clz32(0) === 32 && + Math.clz32(0x12345) === 15 && Math.clz32(-1) === 0) + { + /** + * calculate the integer logarithm base 2 of a byte + * @param {number} x + * @return {number} + */ + v86util.int_log2_byte = function(x) + { + dbg_assert(x > 0); + dbg_assert(x < 0x100); + + return 31 - Math.clz32(x); + }; + + /** + * calculate the integer logarithm base 2 + * @param {number} x + * @return {number} + */ + v86util.int_log2 = function(x) + { + dbg_assert(x > 0); + + return 31 - Math.clz32(x); + }; + + return; + } + + var int_log2_table = new Int8Array(256); + + for(var i = 0, b = -2; i < 256; i++) + { + if(!(i & i - 1)) + b++; + + int_log2_table[i] = b; + } + + /** + * calculate the integer logarithm base 2 of a byte + * @param {number} x + * @return {number} + */ + v86util.int_log2_byte = function(x) + { + dbg_assert(x > 0); + dbg_assert(x < 0x100); + + return int_log2_table[x]; + }; + + /** + * calculate the integer logarithm base 2 + * @param {number} x + * @return {number} + */ + v86util.int_log2 = function(x) + { + x >>>= 0; + dbg_assert(x > 0); + + // http://jsperf.com/integer-log2/6 + var tt = x >>> 16; + + if(tt) + { + var t = tt >>> 8; + if(t) + { + return 24 + int_log2_table[t]; + } + else + { + return 16 + int_log2_table[tt]; + } + } + else + { + var t = x >>> 8; + if(t) + { + return 8 + int_log2_table[t]; + } + else + { + return int_log2_table[x]; + } + } + }; +})(); + + +/** + * @constructor + * + * Queue wrapper around Uint8Array + * Used by devices such as the PS2 controller + */ +function ByteQueue(size) +{ + var data = new Uint8Array(size), + start, + end; + + dbg_assert((size & size - 1) === 0); + + this.length = 0; + + this.push = function(item) + { + if(this.length === size) + { + // intentional overwrite + } + else + { + this.length++; + } + + data[end] = item; + end = end + 1 & size - 1; + }; + + this.shift = function() + { + if(!this.length) + { + return -1; + } + else + { + var item = data[start]; + + start = start + 1 & size - 1; + this.length--; + + return item; + } + }; + + this.peek = function() + { + if(!this.length) + { + return -1; + } + else + { + return data[start]; + } + }; + + this.clear = function() + { + start = 0; + end = 0; + this.length = 0; + }; + + this.clear(); +} + + +/** + * @constructor + * + * Queue wrapper around Float32Array + * Used by devices such as the sound blaster sound card + */ +function FloatQueue(size) +{ + this.size = size; + this.data = new Float32Array(size); + this.start = 0; + this.end = 0; + this.length = 0; + + dbg_assert((size & size - 1) === 0); +} + +FloatQueue.prototype.push = function(item) +{ + if(this.length === this.size) + { + // intentional overwrite + this.start = this.start + 1 & this.size - 1; + } + else + { + this.length++; + } + + this.data[this.end] = item; + this.end = this.end + 1 & this.size - 1; +}; + +FloatQueue.prototype.shift = function() +{ + if(!this.length) + { + return undefined; + } + else + { + var item = this.data[this.start]; + + this.start = this.start + 1 & this.size - 1; + this.length--; + + return item; + } +}; + +FloatQueue.prototype.shift_block = function(count) +{ + var slice = new Float32Array(count); + + if(count > this.length) + { + count = this.length; + } + var slice_end = this.start + count; + + var partial = this.data.subarray(this.start, slice_end); + + slice.set(partial); + if(slice_end >= this.size) + { + slice_end -= this.size; + slice.set(this.data.subarray(0, slice_end), partial.length); + } + this.start = slice_end; + + this.length -= count; + + return slice; +}; + +FloatQueue.prototype.peek = function() +{ + if(!this.length) + { + return undefined; + } + else + { + return this.data[this.start]; + } +}; + +FloatQueue.prototype.clear = function() +{ + this.start = 0; + this.end = 0; + this.length = 0; +}; + + +/** + * Simple circular queue for logs + * + * @param {number} size + * @constructor + */ +function CircularQueue(size) +{ + this.data = []; + this.index = 0; + this.size = size; +} + +CircularQueue.prototype.add = function(item) +{ + this.data[this.index] = item; + this.index = (this.index + 1) % this.size; +}; + +CircularQueue.prototype.toArray = function() +{ + return [].slice.call(this.data, this.index).concat([].slice.call(this.data, 0, this.index)); +}; + +CircularQueue.prototype.clear = function() +{ + this.data = []; + this.index = 0; +}; + +/** + * @param {Array} new_data + */ +CircularQueue.prototype.set = function(new_data) +{ + this.data = new_data; + this.index = 0; +}; + +function dump_file(ab, name) +{ + if(!(ab instanceof Array)) + { + ab = [ab]; + } + + var blob = new Blob(ab); + download(blob, name); +} + +function download(file_or_blob, name) +{ + var a = document.createElement("a"); + a["download"] = name; + a.href = window.URL.createObjectURL(file_or_blob); + a.dataset["downloadurl"] = ["application/octet-stream", a["download"], a.href].join(":"); + + if(document.createEvent) + { + var ev = document.createEvent("MouseEvent"); + ev.initMouseEvent("click", true, true, window, + 0, 0, 0, 0, 0, false, false, false, false, 0, null); + a.dispatchEvent(ev); + } + else + { + a.click(); + } + + window.URL.revokeObjectURL(a.href); +} + +/** + * A simple 1d bitmap + * @constructor + */ +v86util.Bitmap = function(length_or_buffer) +{ + if(typeof length_or_buffer === "number") + { + this.view = new Uint8Array(length_or_buffer + 7 >> 3); + } + else if(length_or_buffer instanceof ArrayBuffer) + { + this.view = new Uint8Array(length_or_buffer); + } + else + { + dbg_assert(false, "v86util.Bitmap: Invalid argument"); + } +}; + +v86util.Bitmap.prototype.set = function(index, value) +{ + const bit_index = index & 7; + const byte_index = index >> 3; + const bit_mask = 1 << bit_index; + + this.view[byte_index] = + value ? this.view[byte_index] | bit_mask : this.view[byte_index] & ~bit_mask; +}; + +v86util.Bitmap.prototype.get = function(index) +{ + const bit_index = index & 7; + const byte_index = index >> 3; + + return this.view[byte_index] >> bit_index & 1; +}; + +v86util.Bitmap.prototype.get_buffer = function() +{ + return this.view.buffer; +}; + + +if(typeof XMLHttpRequest === "undefined") +{ + v86util.load_file = load_file_nodejs; +} +else +{ + v86util.load_file = load_file; +} + +/** + * @param {string} filename + * @param {Object} options + * @param {number=} n_tries + */ +function load_file(filename, options, n_tries) +{ + var http = new XMLHttpRequest(); + + http.open(options.method || "get", filename, true); + + if(options.as_json) + { + http.responseType = "json"; + } + else + { + http.responseType = "arraybuffer"; + } + + if(options.headers) + { + var header_names = Object.keys(options.headers); + + for(var i = 0; i < header_names.length; i++) + { + var name = header_names[i]; + http.setRequestHeader(name, options.headers[name]); + } + } + + if(options.range) + { + let start = options.range.start; + let end = start + options.range.length - 1; + http.setRequestHeader("Range", "bytes=" + start + "-" + end); + + // Abort if server responds with complete file in response to range + // request, to prevent downloading large files from broken http servers + http.onreadystatechange = function() + { + if(http.status === 200) + { + http.abort(); + } + }; + } + + http.onload = function(e) + { + if(http.readyState === 4) + { + if(http.status !== 200 && http.status !== 206) + { + console.error("Loading the image " + filename + " failed (status %d)", http.status); + if(http.status >= 500 && http.status < 600) + { + retry(); + } + } + else if(http.response) + { + options.done && options.done(http.response, http); + } + } + }; + + http.onerror = function(e) + { + console.error("Loading the image " + filename + " failed", e); + retry(); + }; + + if(options.progress) + { + http.onprogress = function(e) + { + options.progress(e); + }; + } + + http.send(null); + + function retry() + { + const number_of_tries = n_tries || 0; + const timeout = [1, 1, 2, 3, 5, 8, 13, 21][number_of_tries] || 34; + setTimeout(() => { + load_file(filename, options, number_of_tries + 1); + }, 1000 * timeout); + } +} + +function load_file_nodejs(filename, options) +{ + let fs = require("fs"); + + if(options.range) + { + dbg_assert(!options.as_json); + + fs["open"](filename, "r", (err, fd) => + { + if(err) throw err; + + let length = options.range.length; + var buffer = Buffer.allocUnsafe(length); + + fs["read"](fd, buffer, 0, length, options.range.start, (err, bytes_read) => + { + if(err) throw err; + + dbg_assert(bytes_read === length); + options.done && options.done(new Uint8Array(buffer)); + + fs["close"](fd, (err) => { + if(err) throw err; + }); + }); + }); + } + else + { + var o = { + encoding: options.as_json ? "utf-8" : null, + }; + + fs["readFile"](filename, o, function(err, data) + { + if(err) + { + console.log("Could not read file:", filename, err); + } + else + { + var result = data; + + if(options.as_json) + { + result = JSON.parse(result); + } + else + { + result = new Uint8Array(result).buffer; + } + + options.done(result); + } + }); + } +} + +// Reads len characters at offset from Memory object mem as a JS string +v86util.read_sized_string_from_mem = function read_sized_string_from_mem(mem, offset, len) +{ + offset >>>= 0; + len >>>= 0; + return String.fromCharCode(...new Uint8Array(mem.buffer, offset, len)); +}; diff --git a/src/log.js b/src/log.js new file mode 100644 index 0000000..277316a --- /dev/null +++ b/src/log.js @@ -0,0 +1,129 @@ +"use strict"; + +var log_data = []; + +function do_the_log(message) +{ + if(LOG_TO_FILE) + { + log_data.push(message, "\n"); + } + else + { + console.log(message); + } +} + +/** + * @type {function((string|number), number=)} + * @const + */ +var dbg_log = (function() +{ + if(!DEBUG) + { + return function() {}; + } + + /** @const @type {Object.} */ + var dbg_names = LOG_NAMES.reduce(function(a, x) + { + a[x[0]] = x[1]; + return a; + }, {}); + + var log_last_message = ""; + var log_message_repetitions = 0; + + /** + * @param {number=} level + */ + function dbg_log_(stuff, level) + { + if(!DEBUG) return; + + level = level || 1; + + if(level & LOG_LEVEL) + { + var level_name = dbg_names[level] || "", + message = "[" + v86util.pads(level_name, 4) + "] " + stuff; + + if(message === log_last_message) + { + log_message_repetitions++; + + if(log_message_repetitions < 2048) + { + return; + } + } + + var now = new Date(); + var time_str = v86util.pad0(now.getHours(), 2) + ":" + + v86util.pad0(now.getMinutes(), 2) + ":" + + v86util.pad0(now.getSeconds(), 2) + "+" + + v86util.pad0(now.getMilliseconds(), 3) + " "; + + if(log_message_repetitions) + { + if(log_message_repetitions === 1) + { + do_the_log(time_str + log_last_message); + } + else + { + do_the_log("Previous message repeated " + log_message_repetitions + " times"); + } + + log_message_repetitions = 0; + } + + do_the_log(time_str + message); + log_last_message = message; + } + } + + return dbg_log_; +})(); + +/** + * @param {number=} level + */ +function dbg_trace(level) +{ + if(!DEBUG) return; + + dbg_log(Error().stack, level); +} + +/** + * console.assert is fucking slow + * @param {string=} msg + * @param {number=} level + */ +function dbg_assert(cond, msg, level) +{ + if(!DEBUG) return; + + if(!cond) + { + dbg_assert_failed(msg); + } +} + + +function dbg_assert_failed(msg) +{ + debugger; + console.trace(); + + if(msg) + { + throw "Assert failed: " + msg; + } + else + { + throw "Assert failed"; + } +} diff --git a/src/main.js b/src/main.js new file mode 100644 index 0000000..d8af210 --- /dev/null +++ b/src/main.js @@ -0,0 +1,228 @@ +"use strict"; + +/** + * @constructor + * @param {Object=} wasm + */ +function v86(bus, wasm) +{ + /** @type {boolean} */ + this.running = false; + + /** @type {boolean} */ + this.stopping = false; + + this.tick_counter = 0; + this.worker = null; + + /** @type {CPU} */ + this.cpu = new CPU(bus, wasm, () => { this.idle && this.next_tick(0); }); + + this.bus = bus; + bus.register("cpu-init", this.init, this); + bus.register("cpu-run", this.run, this); + bus.register("cpu-stop", this.stop, this); + bus.register("cpu-restart", this.restart, this); + + this.register_yield(); +} + +v86.prototype.run = function() +{ + this.stopping = false; + + if(!this.running) + { + this.running = true; + this.bus.send("emulator-started"); + } + + this.next_tick(0); +}; + +v86.prototype.do_tick = function() +{ + if(this.stopping || !this.running) + { + this.stopping = this.running = false; + this.bus.send("emulator-stopped"); + return; + } + + this.idle = false; + const t = this.cpu.main_run(); + + this.next_tick(t); +}; + +v86.prototype.next_tick = function(t) +{ + const tick = ++this.tick_counter; + this.idle = true; + this.yield(t, tick); +}; + +v86.prototype.yield_callback = function(tick) +{ + if(tick === this.tick_counter) + { + this.do_tick(); + } +}; + +v86.prototype.stop = function() +{ + if(this.running) + { + this.stopping = true; + } +}; + +v86.prototype.destroy = function() +{ + this.unregister_yield(); +}; + +v86.prototype.restart = function() +{ + this.cpu.reset_cpu(); + this.cpu.load_bios(); +}; + +v86.prototype.init = function(settings) +{ + this.cpu.init(settings, this.bus); + this.bus.send("emulator-ready"); +}; + +if(typeof process !== "undefined") +{ + v86.prototype.yield = function(t, tick) + { + if(t < 1) + { + global.setImmediate(tick => this.yield_callback(tick), tick); + } + else + { + setTimeout(tick => this.yield_callback(tick), t, tick); + } + }; + + v86.prototype.register_yield = function() {}; + v86.prototype.unregister_yield = function() {}; +} +else if(typeof Worker !== "undefined") +{ + // XXX: This has a slightly lower throughput compared to window.postMessage + + function the_worker() + { + globalThis.onmessage = function(e) + { + const t = e.data.t; + if(t < 1) postMessage(e.data.tick); + else setTimeout(() => postMessage(e.data.tick), t); + }; + } + + v86.prototype.register_yield = function() + { + const url = URL.createObjectURL(new Blob(["(" + the_worker.toString() + ")()"], { type: "text/javascript" })); + this.worker = new Worker(url); + this.worker.onmessage = e => this.yield_callback(e.data); + URL.revokeObjectURL(url); + }; + + v86.prototype.yield = function(t, tick) + { + this.worker.postMessage({ t, tick }); + }; + + v86.prototype.unregister_yield = function() + { + this.worker.terminate(); + this.worker = null; + }; +} +//else if(typeof window !== "undefined" && typeof postMessage !== "undefined") +//{ +// // setImmediate shim for the browser. +// // TODO: Make this deactivatable, for other applications +// // using postMessage +// +// /** @const */ +// let MAGIC_POST_MESSAGE = 0xAA55; +// +// v86.prototype.yield = function(t) +// { +// // XXX: Use t +// window.postMessage(MAGIC_POST_MESSAGE, "*"); +// }; +// +// let tick; +// +// v86.prototype.register_yield = function() +// { +// tick = e => +// { +// if(e.source === window && e.data === MAGIC_POST_MESSAGE) +// { +// this.do_tick(); +// } +// }; +// +// window.addEventListener("message", tick, false); +// }; +// +// v86.prototype.unregister_yield = function() +// { +// window.removeEventListener("message", tick); +// tick = null; +// }; +//} +else +{ + v86.prototype.yield = function(t) + { + setTimeout(() => { this.do_tick(); }, t); + }; + + v86.prototype.register_yield = function() {}; + v86.prototype.unregister_yield = function() {}; +} + +v86.prototype.save_state = function() +{ + // TODO: Should be implemented here, not on cpu + return this.cpu.save_state(); +}; + +v86.prototype.restore_state = function(state) +{ + // TODO: Should be implemented here, not on cpu + return this.cpu.restore_state(state); +}; + + +if(typeof performance === "object" && performance.now) +{ + v86.microtick = performance.now.bind(performance); +} +else if(typeof require === "function") +{ + const { performance } = require("perf_hooks"); + v86.microtick = performance.now.bind(performance); +} +else if(typeof process === "object" && process.hrtime) +{ + v86.microtick = function() + { + var t = process.hrtime(); + return t[0] * 1000 + t[1] / 1e6; + }; +} +else +{ + v86.microtick = Date.now; +} diff --git a/src/memory.js b/src/memory.js new file mode 100644 index 0000000..60445e4 --- /dev/null +++ b/src/memory.js @@ -0,0 +1,98 @@ +"use strict"; + + +CPU.prototype.mmap_read8 = function(addr) +{ + const value = this.memory_map_read8[addr >>> MMAP_BLOCK_BITS](addr); + dbg_assert(value >= 0 && value <= 0xFF); + return value; +}; + +CPU.prototype.mmap_write8 = function(addr, value) +{ + dbg_assert(value >= 0 && value <= 0xFF); + this.memory_map_write8[addr >>> MMAP_BLOCK_BITS](addr, value); +}; + +CPU.prototype.mmap_read16 = function(addr) +{ + var fn = this.memory_map_read8[addr >>> MMAP_BLOCK_BITS]; + const value = fn(addr) | fn(addr + 1 | 0) << 8; + dbg_assert(value >= 0 && value <= 0xFFFF); + return value; +}; + +CPU.prototype.mmap_write16 = function(addr, value) +{ + var fn = this.memory_map_write8[addr >>> MMAP_BLOCK_BITS]; + + dbg_assert(value >= 0 && value <= 0xFFFF); + fn(addr, value & 0xFF); + fn(addr + 1 | 0, value >> 8); +}; + +CPU.prototype.mmap_read32 = function(addr) +{ + var aligned_addr = addr >>> MMAP_BLOCK_BITS; + + return this.memory_map_read32[aligned_addr](addr); +}; + +CPU.prototype.mmap_write32 = function(addr, value) +{ + var aligned_addr = addr >>> MMAP_BLOCK_BITS; + + this.memory_map_write32[aligned_addr](addr, value); +}; + +CPU.prototype.mmap_write64 = function(addr, value0, value1) +{ + var aligned_addr = addr >>> MMAP_BLOCK_BITS; + // This should hold since writes across pages are split up + dbg_assert(aligned_addr === (addr + 7) >>> MMAP_BLOCK_BITS); + + var write_func32 = this.memory_map_write32[aligned_addr]; + write_func32(addr, value0); + write_func32(addr + 4, value1); +}; + +CPU.prototype.mmap_write128 = function(addr, value0, value1, value2, value3) +{ + var aligned_addr = addr >>> MMAP_BLOCK_BITS; + // This should hold since writes across pages are split up + dbg_assert(aligned_addr === (addr + 12) >>> MMAP_BLOCK_BITS); + + var write_func32 = this.memory_map_write32[aligned_addr]; + write_func32(addr, value0); + write_func32(addr + 4, value1); + write_func32(addr + 8, value2); + write_func32(addr + 12, value3); +}; + +/** + * @param {Array.|Uint8Array} blob + * @param {number} offset + */ +CPU.prototype.write_blob = function(blob, offset) +{ + dbg_assert(blob && blob.length >= 0); + + if(blob.length) + { + dbg_assert(!this.in_mapped_range(offset)); + dbg_assert(!this.in_mapped_range(offset + blob.length - 1)); + + this.jit_dirty_cache(offset, offset + blob.length); + this.mem8.set(blob, offset); + } +}; + +CPU.prototype.read_blob = function(offset, length) +{ + if(length) + { + dbg_assert(!this.in_mapped_range(offset)); + dbg_assert(!this.in_mapped_range(offset + length - 1)); + } + return this.mem8.subarray(offset, offset + length); +}; diff --git a/src/ne2k.js b/src/ne2k.js new file mode 100644 index 0000000..308bfe7 --- /dev/null +++ b/src/ne2k.js @@ -0,0 +1,1291 @@ +"use strict"; + +// http://www.ethernut.de/pdf/8019asds.pdf + +const NE2K_LOG_VERBOSE = false; +const NE2K_LOG_PACKETS = false; + +/** @const */ var E8390_CMD = 0x00; /* The command register (for all pages) */ + +/* Page 0 register offsets. */ +/** @const */ var EN0_CLDALO = 0x01; /* Low byte of current local dma addr RD */ +/** @const */ var EN0_STARTPG = 0x01; /* Starting page of ring bfr WR */ +/** @const */ var EN0_CLDAHI = 0x02; /* High byte of current local dma addr RD */ +/** @const */ var EN0_STOPPG = 0x02; /* Ending page +1 of ring bfr WR */ +/** @const */ var EN0_BOUNDARY = 0x03; /* Boundary page of ring bfr RD WR */ +/** @const */ var EN0_TSR = 0x04; /* Transmit status reg RD */ +/** @const */ var EN0_TPSR = 0x04; /* Transmit starting page WR */ +/** @const */ var EN0_NCR = 0x05; /* Number of collision reg RD */ +/** @const */ var EN0_TCNTLO = 0x05; /* Low byte of tx byte count WR */ +/** @const */ var EN0_FIFO = 0x06; /* FIFO RD */ +/** @const */ var EN0_TCNTHI = 0x06; /* High byte of tx byte count WR */ +/** @const */ var EN0_ISR = 0x07; /* Interrupt status reg RD WR */ +/** @const */ var EN0_CRDALO = 0x08; /* low byte of current remote dma address RD */ +/** @const */ var EN0_RSARLO = 0x08; /* Remote start address reg 0 */ +/** @const */ var EN0_CRDAHI = 0x09; /* high byte, current remote dma address RD */ +/** @const */ var EN0_RSARHI = 0x09; /* Remote start address reg 1 */ +/** @const */ var EN0_RCNTLO = 0x0a; /* Remote byte count reg WR */ +/** @const */ var EN0_RCNTHI = 0x0b; /* Remote byte count reg WR */ +/** @const */ var EN0_RSR = 0x0c; /* rx status reg RD */ +/** @const */ var EN0_RXCR = 0x0c; /* RX configuration reg WR */ +/** @const */ var EN0_TXCR = 0x0d; /* TX configuration reg WR */ +/** @const */ var EN0_COUNTER0 = 0x0d; /* Rcv alignment error counter RD */ +/** @const */ var EN0_DCFG = 0x0e; /* Data configuration reg WR */ +/** @const */ var EN0_COUNTER1 = 0x0e; /* Rcv CRC error counter RD */ +/** @const */ var EN0_IMR = 0x0f; /* Interrupt mask reg WR */ +/** @const */ var EN0_COUNTER2 = 0x0f; /* Rcv missed frame error counter RD */ + +/** @const */ var NE_DATAPORT = 0x10; /* NatSemi-defined port window offset. */ +/** @const */ var NE_RESET = 0x1f; /* Issue a read to reset, a write to clear. */ + +/* Bits in EN0_ISR - Interrupt status register */ +/** @const */ var ENISR_RX = 0x01; /* Receiver, no error */ +/** @const */ var ENISR_TX = 0x02; /* Transmitter, no error */ +/** @const */ var ENISR_RX_ERR = 0x04; /* Receiver, with error */ +/** @const */ var ENISR_TX_ERR = 0x08; /* Transmitter, with error */ +/** @const */ var ENISR_OVER = 0x10; /* Receiver overwrote the ring */ +/** @const */ var ENISR_COUNTERS = 0x20; /* Counters need emptying */ +/** @const */ var ENISR_RDC = 0x40; /* remote dma complete */ +/** @const */ var ENISR_RESET = 0x80; /* Reset completed */ +/** @const */ var ENISR_ALL = 0x3f; /* Interrupts we will enable */ + +/** @const */ var ENRSR_RXOK = 0x01; /* Received a good packet */ + +/** @const */ var START_PAGE = 0x40; +/** @const */ var START_RX_PAGE = 0x40 + 12; +/** @const */ var STOP_PAGE = 0x80; + + +// Search and replace MAC addresses in ethernet, arp and dhcp packets. +// Used after restoring an OS from memory dump, so that multiple instances of +// that OS can run at the same time with different external MAC addresses. +// Crude but seems to work. +function translate_mac_address(packet, search_mac, replacement_mac) +{ + if(packet[0] === search_mac[0] && + packet[1] === search_mac[1] && + packet[2] === search_mac[2] && + packet[3] === search_mac[3] && + packet[4] === search_mac[4] && + packet[5] === search_mac[5]) + { + dbg_log("Replace mac in eth destination field", LOG_NET); + + packet[0] = replacement_mac[0]; + packet[1] = replacement_mac[1]; + packet[2] = replacement_mac[2]; + packet[3] = replacement_mac[3]; + packet[4] = replacement_mac[4]; + packet[5] = replacement_mac[5]; + } + + if(packet[6 + 0] === search_mac[0] && + packet[6 + 1] === search_mac[1] && + packet[6 + 2] === search_mac[2] && + packet[6 + 3] === search_mac[3] && + packet[6 + 4] === search_mac[4] && + packet[6 + 5] === search_mac[5]) + { + dbg_log("Replace mac in eth source field", LOG_NET); + + packet[6 + 0] = replacement_mac[0]; + packet[6 + 1] = replacement_mac[1]; + packet[6 + 2] = replacement_mac[2]; + packet[6 + 3] = replacement_mac[3]; + packet[6 + 4] = replacement_mac[4]; + packet[6 + 5] = replacement_mac[5]; + } + + const ethertype = packet[12] << 8 | packet[13]; + + if(ethertype === 0x0800) + { + // ipv4 + const ipv4_packet = packet.subarray(14); + const ipv4_version = ipv4_packet[0] >> 4; + + if(ipv4_version !== 4) + { + dbg_log("Expected ipv4.version==4 but got: " + ipv4_version, LOG_NET); + return; + } + + const ipv4_ihl = ipv4_packet[0] & 0xF; + dbg_assert(ipv4_ihl === 5, "TODO: ihl!=5"); + + const ipv4_proto = ipv4_packet[9]; + if(ipv4_proto === 0x11) + { + // udp + const udp_packet = ipv4_packet.subarray(5 * 4); + const source_port = udp_packet[0] << 8 | udp_packet[1]; + const destination_port = udp_packet[2] << 8 | udp_packet[3]; + const checksum = udp_packet[6] << 8 | udp_packet[7]; + + dbg_log("udp srcport=" + source_port + " dstport=" + destination_port + " checksum=" + h(checksum, 4), LOG_NET); + + if(source_port === 67 || destination_port === 67) + { + // dhcp + const dhcp_packet = udp_packet.subarray(8); + const dhcp_magic = dhcp_packet[0xEC] << 24 | dhcp_packet[0xED] << 16 | dhcp_packet[0xEE] << 8 | dhcp_packet[0xEF]; + + if(dhcp_magic !== 0x63825363) + { + dbg_log("dhcp packet didn't match magic: " + h(dhcp_magic, 8)); + return; + } + + if(dhcp_packet[28 + 0] === search_mac[0] && + dhcp_packet[28 + 1] === search_mac[1] && + dhcp_packet[28 + 2] === search_mac[2] && + dhcp_packet[28 + 3] === search_mac[3] && + dhcp_packet[28 + 4] === search_mac[4] && + dhcp_packet[28 + 5] === search_mac[5]) + { + dbg_log("Replace mac in dhcp.chaddr", LOG_NET); + + dhcp_packet[28 + 0] = replacement_mac[0]; + dhcp_packet[28 + 1] = replacement_mac[1]; + dhcp_packet[28 + 2] = replacement_mac[2]; + dhcp_packet[28 + 3] = replacement_mac[3]; + dhcp_packet[28 + 4] = replacement_mac[4]; + dhcp_packet[28 + 5] = replacement_mac[5]; + + udp_packet[6] = udp_packet[7] = 0; // zero udp checksum + } + + let offset = 0xF0; + while(offset < dhcp_packet.length) + { + const dhcp_option_type = dhcp_packet[offset++]; + + if(dhcp_option_type === 0xFF) + { + break; + } + + const length = dhcp_packet[offset++]; + + if(dhcp_option_type === 0x3D && // client identifier + dhcp_packet[offset + 0] === 0x01 && // ethernet + dhcp_packet[offset + 1] === search_mac[0] && + dhcp_packet[offset + 2] === search_mac[1] && + dhcp_packet[offset + 3] === search_mac[2] && + dhcp_packet[offset + 4] === search_mac[3] && + dhcp_packet[offset + 5] === search_mac[4] && + dhcp_packet[offset + 6] === search_mac[5]) + { + dbg_log("Replace mac in dhcp.clientidentifier", LOG_NET); + + dhcp_packet[offset + 1] = replacement_mac[0]; + dhcp_packet[offset + 2] = replacement_mac[1]; + dhcp_packet[offset + 3] = replacement_mac[2]; + dhcp_packet[offset + 4] = replacement_mac[3]; + dhcp_packet[offset + 5] = replacement_mac[4]; + dhcp_packet[offset + 6] = replacement_mac[5]; + + udp_packet[6] = udp_packet[7] = 0; // zero udp checksum + } + + offset += length; + } + } + } + else + { + // tcp, ... + } + } + else if(ethertype === 0x0806) + { + // arp + const arp_packet = packet.subarray(14); + dbg_log("arp oper=" + arp_packet[7] + " " + format_mac(arp_packet.subarray(8, 8+6)) + " " + format_mac(arp_packet.subarray(18, 18+6)), LOG_NET); + + if(arp_packet[8 + 0] === search_mac[0] && + arp_packet[8 + 1] === search_mac[1] && + arp_packet[8 + 2] === search_mac[2] && + arp_packet[8 + 3] === search_mac[3] && + arp_packet[8 + 4] === search_mac[4] && + arp_packet[8 + 5] === search_mac[5]) + { + dbg_log("Replace mac in arp.sha", LOG_NET); + + arp_packet[8 + 0] = replacement_mac[0]; + arp_packet[8 + 1] = replacement_mac[1]; + arp_packet[8 + 2] = replacement_mac[2]; + arp_packet[8 + 3] = replacement_mac[3]; + arp_packet[8 + 4] = replacement_mac[4]; + arp_packet[8 + 5] = replacement_mac[5]; + } + } + else + { + // TODO: ipv6, ... + } +} + +function format_mac(mac) +{ + return [ + mac[0].toString(16).padStart(2, "0"), + mac[1].toString(16).padStart(2, "0"), + mac[2].toString(16).padStart(2, "0"), + mac[3].toString(16).padStart(2, "0"), + mac[4].toString(16).padStart(2, "0"), + mac[5].toString(16).padStart(2, "0"), + ].join(":"); +} + +function dump_packet(packet, prefix) +{ + const ethertype = packet[12] << 8 | packet[13] << 0; + if(ethertype === 0x0800) + { + const ipv4_packet = packet.subarray(14); + const ipv4_len = ipv4_packet[2] << 8 | ipv4_packet[3]; + const ipv4_proto = ipv4_packet[9]; + if(ipv4_proto === 0x11) + { + const udp_packet = ipv4_packet.subarray(5 * 4); + const source_port = udp_packet[0] << 8 | udp_packet[1]; + const destination_port = udp_packet[2] << 8 | udp_packet[3]; + const checksum = udp_packet[6] << 8 | udp_packet[7]; + + if(source_port === 67 || destination_port === 67) + { + const dhcp_packet = udp_packet.subarray(8); + const dhcp_chaddr = dhcp_packet.subarray(28, 28+6); + dbg_log(prefix + " len=" + packet.length + " ethertype=" + h(ethertype) + " ipv4.len=" + ipv4_len + " ipv4.proto=" + h(packet[14 + 9]) + " udp.srcport=" + source_port + " udp.dstport=" + destination_port + " udp.chksum=" + h(checksum, 4) + " dhcp.chaddr=" + format_mac(dhcp_chaddr)); + } + else + { + dbg_log(prefix + " len=" + packet.length + " ethertype=" + h(ethertype) + " ipv4.len=" + ipv4_len + " ipv4.proto=" + h(packet[14 + 9]) + " udp.srcport=" + source_port + " udp.dstport=" + destination_port + " udp.chksum=" + h(checksum, 4)); + } + } + else if(ipv4_proto === 0x01) + { + } + else + { + dbg_log(prefix + " len=" + packet.length + " ethertype=" + h(ethertype) + " ipv4.len=" + ipv4_len + " ipv4.proto=" + h(packet[14 + 9])); + } + } + else + { + const arp_packet = packet.subarray(14); + dbg_log(prefix + " len=" + packet.length + " ethertype=" + h(ethertype) + " arp"); + } + dbg_log(hex_dump(packet)); +} + +/** + * @constructor + * @param {CPU} cpu + * @param {BusConnector} bus + * @param {Boolean} preserve_mac_from_state_image + * @param {Boolean} mac_address_translation + */ +function Ne2k(cpu, bus, preserve_mac_from_state_image, mac_address_translation) +{ + /** @const @type {CPU} */ + this.cpu = cpu; + + /** @const @type {PCI} */ + this.pci = cpu.devices.pci; + + this.preserve_mac_from_state_image = preserve_mac_from_state_image; + this.mac_address_translation = mac_address_translation; + + /** @const @type {BusConnector} */ + this.bus = bus; + this.bus.register("net0-receive", function(data) + { + this.receive(data); + }, this); + + this.port = 0x300; + + this.name = "ne2k"; + + /** @const */ + var use_pci = true; + + if(use_pci) + { + this.pci_space = [ + 0xec, 0x10, 0x29, 0x80, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, + this.port & 0xFF | 1, this.port >> 8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf4, 0x1a, 0x00, 0x11, + 0x00, 0x00, 0xb8, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + ]; + this.pci_id = 0x05 << 3; + this.pci_bars = [ + { + size: 32, + }, + ]; + } + + this.isr = 0; + this.imr = 0; // interrupt mask register + + this.cr = 1; + + this.dcfg = 0; + + this.rcnt = 0; + + this.tcnt = 0; + this.tpsr = 0; + this.memory = new Uint8Array(256 * 0x80); + + this.rxcr = 0; + this.txcr = 0; + this.tsr = 1; + + // mac address + this.mac = new Uint8Array([ + 0x00, 0x22, 0x15, + Math.random() * 255 | 0, + Math.random() * 255 | 0, + Math.random() * 255 | 0, + ]); + + // Used for mac address translation + // The mac the OS thinks it has + this.mac_address_in_state = null; + + for(var i = 0; i < 6; i++) + { + this.memory[i << 1] = this.memory[i << 1 | 1] = this.mac[i]; + } + + // the PROM signature of 0x57, 0x57 is also doubled + // resulting in setting the 4 bytes at the end, 28, 29, 30 and 31 to 0x57 + this.memory[14 << 1] = this.memory[14 << 1 | 1] = 0x57; + this.memory[15 << 1] = this.memory[15 << 1 | 1] = 0x57; + + dbg_log("Mac: " + format_mac(this.mac), LOG_NET); + + this.rsar = 0; + + this.pstart = START_PAGE; + this.pstop = STOP_PAGE; + + this.curpg = START_RX_PAGE; + this.boundary = START_RX_PAGE; + + var io = cpu.io; + + io.register_read(this.port | E8390_CMD, this, function() + { + dbg_log("Read cmd", LOG_NET); + return this.cr; + }); + + io.register_write(this.port | E8390_CMD, this, function(data_byte) + { + this.cr = data_byte; + dbg_log("Write command: " + h(data_byte, 2) + " newpg=" + (this.cr >> 6) + " txcr=" + h(this.txcr, 2), LOG_NET); + + if(this.cr & 1) + { + return; + } + + if((data_byte & 0x18) && this.rcnt === 0) + { + this.do_interrupt(ENISR_RDC); + } + + if(data_byte & 4) + { + var start = this.tpsr << 8; + var data = this.memory.subarray(start, start + this.tcnt); + + if(NE2K_LOG_PACKETS) + { + dump_packet(data, "send"); + } + + if(this.mac_address_in_state) + { + data = new Uint8Array(data); // make a copy + translate_mac_address(data, this.mac_address_in_state, this.mac); + } + + this.bus.send("net0-send", data); + this.bus.send("eth-transmit-end", [data.length]); + this.cr &= ~4; + this.do_interrupt(ENISR_TX); + + dbg_log("Command: Transfer. length=" + h(data.byteLength), LOG_NET); + } + }); + + io.register_read(this.port | EN0_COUNTER0, this, function() + { + dbg_log("Read counter0", LOG_NET); + return 0; + }); + + io.register_read(this.port | EN0_COUNTER1, this, function() + { + dbg_log("Read8 counter1", LOG_NET); + return 0; + }, function() + { + dbg_log("Read16 counter1", LOG_NET); + // openbsd + return 0; + } + ); + + io.register_read(this.port | EN0_COUNTER2, this, function() + { + dbg_log("Read counter2", LOG_NET); + return 0; + }); + + io.register_read(this.port | NE_RESET, this, function() + { + var pg = this.get_page(); + dbg_log("Read reset", LOG_NET); + this.do_interrupt(ENISR_RESET); + return 0; + }); + + io.register_write(this.port | NE_RESET, this, function(data_byte) + { + var pg = this.get_page(); + dbg_log("Write reset: " + h(data_byte, 2), LOG_NET); + //this.isr &= ~ENISR_RESET; + }); + + io.register_read(this.port | EN0_STARTPG, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + return this.pstart; + } + else if(pg === 1) + { + dbg_log("Read pg1/01 (mac[0])", LOG_NET); + return this.mac[0]; + } + else if(pg === 2) + { + return this.pstart; + } + else + { + dbg_log("Read pg" + pg + "/01"); + dbg_assert(false); + return 0; + } + }); + + io.register_write(this.port | EN0_STARTPG, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("start page: " + h(data_byte, 2), LOG_NET); + this.pstart = data_byte; + } + else if(pg === 1) + { + dbg_log("mac[0] = " + h(data_byte), LOG_NET); + this.mac[0] = data_byte; + } + else if(pg === 3) + { + dbg_log("Unimplemented: Write pg3/01 (9346CR): " + h(data_byte), LOG_NET); + } + else + { + dbg_log("Write pg" + pg + "/01: " + h(data_byte), LOG_NET); + dbg_assert(false); + } + }); + + + io.register_read(this.port | EN0_STOPPG, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + return this.pstop; + } + else if(pg === 1) + { + dbg_log("Read pg1/02 (mac[1])", LOG_NET); + return this.mac[1]; + } + else if(pg === 2) + { + return this.pstop; + } + else + { + dbg_log("Read pg" + pg + "/02", LOG_NET); + dbg_assert(false); + return 0; + } + }); + + io.register_write(this.port | EN0_STOPPG, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("stop page: " + h(data_byte, 2), LOG_NET); + if(data_byte > (this.memory.length >> 8)) + { + data_byte = this.memory.length >> 8; + dbg_log("XXX: Adjusting stop page to " + h(data_byte), LOG_NET); + } + this.pstop = data_byte; + } + else if(pg === 1) + { + dbg_log("mac[1] = " + h(data_byte), LOG_NET); + this.mac[1] = data_byte; + } + else + { + dbg_log("Write pg" + pg + "/02: " + h(data_byte), LOG_NET); + dbg_assert(false); + } + }); + + io.register_read(this.port | EN0_ISR, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Read isr: " + h(this.isr, 2), LOG_NET); + return this.isr; + } + else if(pg === 1) + { + dbg_log("Read curpg: " + h(this.curpg, 2), LOG_NET); + return this.curpg; + } + else + { + dbg_assert(false); + } + }); + + io.register_write(this.port | EN0_ISR, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + // acknowledge interrupts where bit is set + dbg_log("Write isr: " + h(data_byte, 2), LOG_NET); + this.isr &= ~data_byte; + this.update_irq(); + } + else if(pg === 1) + { + dbg_log("Write curpg: " + h(data_byte, 2), LOG_NET); + this.curpg = data_byte; + } + else + { + dbg_assert(false); + } + }); + + io.register_write(this.port | EN0_TXCR, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + this.txcr = data_byte; + dbg_log("Write tx config: " + h(data_byte, 2), LOG_NET); + } + else + { + dbg_log("Unimplemented: Write pg" + pg + "/0d " + h(data_byte, 2), LOG_NET); + } + }); + + io.register_write(this.port | EN0_DCFG, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write data configuration: " + h(data_byte, 2), LOG_NET); + this.dcfg = data_byte; + } + else + { + dbg_log("Unimplemented: Write pg" + pg + "/0e " + h(data_byte, 2), LOG_NET); + } + }); + + io.register_read(this.port | EN0_RCNTLO, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Read pg0/0a", LOG_NET); + return 0x50; + } + else + { + dbg_assert(false, "TODO"); + return 0; + } + }); + + io.register_write(this.port | EN0_RCNTLO, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write remote byte count low: " + h(data_byte, 2), LOG_NET); + this.rcnt = this.rcnt & 0xFF00 | data_byte & 0xFF; + } + else + { + dbg_log("Unimplemented: Write pg" + pg + "/0a " + h(data_byte, 2), LOG_NET); + } + }); + + io.register_read(this.port | EN0_RCNTHI, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Read pg0/0b", LOG_NET); + return 0x43; + } + else + { + dbg_assert(false, "TODO"); + return 0; + } + }); + + io.register_write(this.port | EN0_RCNTHI, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write remote byte count high: " + h(data_byte, 2), LOG_NET); + this.rcnt = this.rcnt & 0xFF | data_byte << 8 & 0xFF00; + } + else + { + dbg_log("Unimplemented: Write pg" + pg + "/0b " + h(data_byte, 2), LOG_NET); + } + }); + + io.register_read(this.port | EN0_RSARLO, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Read remote start address low", LOG_NET); + return this.rsar & 0xFF; + } + else + { + dbg_log("Unimplemented: Read pg" + pg + "/08", LOG_NET); + dbg_assert(false); + } + }); + + io.register_write(this.port | EN0_RSARLO, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write remote start address low: " + h(data_byte, 2), LOG_NET); + this.rsar = this.rsar & 0xFF00 | data_byte & 0xFF; + } + else + { + dbg_log("Unimplemented: Write pg" + pg + "/08 " + h(data_byte, 2), LOG_NET); + } + }); + + io.register_read(this.port | EN0_RSARHI, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Read remote start address high", LOG_NET); + return this.rsar >> 8 & 0xFF; + } + else + { + dbg_log("Unimplemented: Read pg" + pg + "/09", LOG_NET); + dbg_assert(false); + } + }); + + io.register_write(this.port | EN0_RSARHI, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write remote start address low: " + h(data_byte, 2), LOG_NET); + this.rsar = this.rsar & 0xFF | data_byte << 8 & 0xFF00; + } + else + { + dbg_log("Unimplemented: Write pg" + pg + "/09 " + h(data_byte, 2), LOG_NET); + } + }); + + io.register_write(this.port | EN0_IMR, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write interrupt mask register: " + h(data_byte, 2) + " isr=" + h(this.isr, 2), LOG_NET); + this.imr = data_byte; + this.update_irq(); + } + else + { + dbg_log("Unimplemented: Write pg" + pg + "/0f " + h(data_byte, 2), LOG_NET); + } + }); + + io.register_read(this.port | EN0_BOUNDARY, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Read boundary: " + h(this.boundary, 2), LOG_NET); + return this.boundary; + } + else if(pg === 1) + { + dbg_log("Read pg1/03 (mac[2])", LOG_NET); + return this.mac[2]; + } + else if(pg === 3) + { + dbg_log("Unimplemented: Read pg3/03 (CONFIG0)", LOG_NET); + return 0; + } + else + { + dbg_log("Read pg" + pg + "/03", LOG_NET); + dbg_assert(false); + return 0; + } + }); + + io.register_write(this.port | EN0_BOUNDARY, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write boundary: " + h(data_byte, 2), LOG_NET); + this.boundary = data_byte; + } + else if(pg === 1) + { + dbg_log("mac[2] = " + h(data_byte), LOG_NET); + this.mac[2] = data_byte; + } + else + { + dbg_log("Write pg" + pg + "/03: " + h(data_byte), LOG_NET); + dbg_assert(false); + } + }); + + io.register_read(this.port | EN0_TSR, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + return this.tsr; + } + else if(pg === 1) + { + dbg_log("Read pg1/04 (mac[3])", LOG_NET); + return this.mac[3]; + } + else + { + dbg_log("Read pg" + pg + "/04", LOG_NET); + dbg_assert(false); + return 0; + } + }); + + io.register_write(this.port | EN0_TPSR, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write tpsr: " + h(data_byte, 2), LOG_NET); + this.tpsr = data_byte; + } + else if(pg === 1) + { + dbg_log("mac[3] = " + h(data_byte), LOG_NET); + this.mac[3] = data_byte; + } + else + { + dbg_log("Write pg" + pg + "/04: " + h(data_byte), LOG_NET); + dbg_assert(false); + } + }); + + io.register_read(this.port | EN0_TCNTLO, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Unimplemented: Read pg0/05 (NCR: Number of Collisions Register)", LOG_NET); + return 0; + } + else if(pg === 1) + { + dbg_log("Read pg1/05 (mac[4])", LOG_NET); + return this.mac[4]; + } + else if(pg === 3) + { + dbg_log("Unimplemented: Read pg3/05 (CONFIG2)", LOG_NET); + return 0; + } + else + { + dbg_log("Read pg" + pg + "/05", LOG_NET); + dbg_assert(false); + return 0; + } + }); + + io.register_write(this.port | EN0_TCNTLO, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write tcnt low: " + h(data_byte, 2), LOG_NET); + this.tcnt = this.tcnt & ~0xFF | data_byte; + } + else if(pg === 1) + { + dbg_log("mac[4] = " + h(data_byte), LOG_NET); + this.mac[4] = data_byte; + } + else if(pg === 3) + { + dbg_log("Unimplemented: Write pg3/05 (CONFIG2): " + h(data_byte), LOG_NET); + } + else + { + dbg_log("Write pg" + pg + "/05: " + h(data_byte), LOG_NET); + dbg_assert(false); + } + }); + + io.register_read(this.port | EN0_TCNTHI, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_assert(false, "TODO"); + return 0; + } + else if(pg === 1) + { + dbg_log("Read pg1/06 (mac[5])", LOG_NET); + return this.mac[5]; + } + else if(pg === 3) + { + dbg_log("Unimplemented: Read pg3/06 (CONFIG3)", LOG_NET); + return 0; + } + else + { + dbg_log("Read pg" + pg + "/06", LOG_NET); + dbg_assert(false); + return 0; + } + }); + + io.register_write(this.port | EN0_TCNTHI, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("Write tcnt high: " + h(data_byte, 2), LOG_NET); + this.tcnt = this.tcnt & 0xFF | data_byte << 8; + } + else if(pg === 1) + { + dbg_log("mac[5] = " + h(data_byte), LOG_NET); + this.mac[5] = data_byte; + } + else if(pg === 3) + { + dbg_log("Unimplemented: Write pg3/06 (CONFIG3): " + h(data_byte), LOG_NET); + } + else + { + dbg_log("Write pg" + pg + "/06: " + h(data_byte), LOG_NET); + dbg_assert(false); + } + }); + + io.register_read(this.port | EN0_RSR, this, function() + { + var pg = this.get_page(); + if(pg === 0) + { + return 1 | 1 << 3; // receive status ok + } + else + { + dbg_log("Unimplemented: Read pg" + pg + "/0c", LOG_NET); + dbg_assert(false); + return 0; + } + }); + + io.register_write(this.port | EN0_RXCR, this, function(data_byte) + { + var pg = this.get_page(); + if(pg === 0) + { + dbg_log("RX configuration reg write: " + h(data_byte, 2), LOG_NET); + this.rxcr = data_byte; + } + else + { + dbg_log("Unimplemented: Write pg" + pg + "/0c: " + h(data_byte), LOG_NET); + } + }); + + io.register_read(this.port | NE_DATAPORT | 0, this, + this.data_port_read8, + this.data_port_read16, + this.data_port_read32); + io.register_write(this.port | NE_DATAPORT | 0, this, + this.data_port_write16, + this.data_port_write16, + this.data_port_write32); + + if(use_pci) + { + cpu.devices.pci.register_device(this); + } +} + +Ne2k.prototype.get_state = function() +{ + var state = []; + + state[0] = this.isr; + state[1] = this.imr; + state[2] = this.cr; + state[3] = this.dcfg; + state[4] = this.rcnt; + state[5] = this.tcnt; + state[6] = this.tpsr; + state[7] = this.rsar; + state[8] = this.pstart; + state[9] = this.curpg; + state[10] = this.boundary; + state[11] = this.pstop; + state[12] = this.rxcr; + state[13] = this.txcr; + state[14] = this.tsr; + state[15] = this.mac; + state[16] = this.memory; + + return state; +}; + +Ne2k.prototype.set_state = function(state) +{ + this.isr = state[0]; + this.imr = state[1]; + this.cr = state[2]; + this.dcfg = state[3]; + this.rcnt = state[4]; + this.tcnt = state[5]; + this.tpsr = state[6]; + this.rsar = state[7]; + this.pstart = state[8]; + this.curpg = state[9]; + this.boundary = state[10]; + this.pstop = state[11]; + this.rxcr = state[12]; + this.txcr = state[13]; + this.tsr = state[14]; + + if(this.preserve_mac_from_state_image) + { + this.mac = state[15]; + this.memory = state[16]; + } + else if(this.mac_address_translation) + { + this.mac_address_in_state = state[15]; + this.memory = state[16]; + + dbg_log("Using mac address translation" + + " guest_os_mac=" + format_mac(this.mac_address_in_state) + + " real_mac=" + format_mac(this.mac), LOG_NET); + } +}; + +Ne2k.prototype.do_interrupt = function(ir_mask) +{ + dbg_log("Do interrupt " + h(ir_mask, 2), LOG_NET); + this.isr |= ir_mask; + this.update_irq(); +}; + +Ne2k.prototype.update_irq = function() +{ + if(this.imr & this.isr) + { + this.pci.raise_irq(this.pci_id); + } + else + { + this.pci.lower_irq(this.pci_id); + } +}; + +Ne2k.prototype.data_port_write = function(data_byte) +{ + if(NE2K_LOG_VERBOSE) + { + dbg_log("Write data port: data=" + h(data_byte & 0xFF, 2) + + " rsar=" + h(this.rsar, 4) + + " rcnt=" + h(this.rcnt, 4), LOG_NET); + } + + if(this.rsar <= 0x10 || this.rsar >= (START_PAGE << 8) && this.rsar < (STOP_PAGE << 8)) + { + this.memory[this.rsar] = data_byte; + } + + this.rsar++; + this.rcnt--; + + if(this.rsar >= (this.pstop << 8)) + { + this.rsar += (this.pstart - this.pstop) << 8; + } + + if(this.rcnt === 0) + { + this.do_interrupt(ENISR_RDC); + } +}; + +Ne2k.prototype.data_port_write16 = function(data) +{ + this.data_port_write(data); + + if(this.dcfg & 1) + { + this.data_port_write(data >> 8); + } +}; + +Ne2k.prototype.data_port_write32 = function(data) +{ + this.data_port_write(data); + this.data_port_write(data >> 8); + this.data_port_write(data >> 16); + this.data_port_write(data >> 24); +}; + +Ne2k.prototype.data_port_read = function() +{ + let data = 0; + + if(this.rsar < (STOP_PAGE << 8)) + { + data = this.memory[this.rsar]; + } + + if(NE2K_LOG_VERBOSE) + { + dbg_log("Read data port: data=" + h(data, 2) + + " rsar=" + h(this.rsar, 4) + + " rcnt=" + h(this.rcnt, 4), LOG_NET); + } + + this.rsar++; + this.rcnt--; + + if(this.rsar >= (this.pstop << 8)) + { + this.rsar += (this.pstart - this.pstop) << 8; + } + + if(this.rcnt === 0) + { + this.do_interrupt(ENISR_RDC); + } + + return data; +}; + +Ne2k.prototype.data_port_read8 = function() +{ + return this.data_port_read16() & 0xFF; +}; + +Ne2k.prototype.data_port_read16 = function() +{ + if(this.dcfg & 1) + { + return this.data_port_read() | this.data_port_read() << 8; + } + else + { + return this.data_port_read(); + } +}; + +Ne2k.prototype.data_port_read32 = function() +{ + return this.data_port_read() | this.data_port_read() << 8 | + this.data_port_read() << 16 | this.data_port_read() << 24; +}; + +Ne2k.prototype.receive = function(data) +{ + // called from the adapter when data is received over the network + + if(this.cr & 1) + { + // stop bit set + return; + } + + if(NE2K_LOG_PACKETS) + { + dump_packet(data, "receive"); + } + + this.bus.send("eth-receive-end", [data.length]); + + if(this.rxcr & 0x10) + { + // promiscuous + } + else if((this.rxcr & 4) && + data[0] === 0xFF && data[1] === 0xFF && data[2] === 0xFF && + data[3] === 0xFF && data[4] === 0xFF && data[5] === 0xFF) + { + // broadcast + } + else if((this.rxcr & 8) && (data[0] & 1) === 1) + { + // multicast + // XXX + return; + } + else if(data[0] === this.mac[0] && data[1] === this.mac[1] && + data[2] === this.mac[2] && data[3] === this.mac[3] && + data[4] === this.mac[4] && data[5] === this.mac[5]) + { + } + else + { + return; + } + + if(this.mac_address_in_state) + { + data = new Uint8Array(data); // make a copy + translate_mac_address(data, this.mac, this.mac_address_in_state); + } + + var packet_length = Math.max(60, data.length); + + var offset = this.curpg << 8; + var total_length = packet_length + 4; + var data_start = offset + 4; + var next = this.curpg + 1 + (total_length >> 8); + + var end = offset + total_length; + + const needed = 1 + (total_length >> 8); + + // boundary == curpg interpreted as ringbuffer empty + const available = this.boundary > this.curpg ? + this.boundary - this.curpg : + this.pstop - this.curpg + this.boundary - this.pstart; + + if(available < needed && + this.boundary !== 0 // XXX: ReactOS sets this to 0 initially and never updates it unless it receives a packet + ) + { + dbg_log("Buffer full, dropping packet pstart=" + h(this.pstart) + " pstop=" + h(this.pstop) + + " curpg=" + h(this.curpg) + " needed=" + h(needed) + " boundary=" + h(this.boundary) + " available=" + h(available), LOG_NET); + return; + } + + if(end > (this.pstop << 8)) + { + // Shouldn't happen because at this size it can't cross a page, + // so we can skip filling with zeroes + dbg_assert(data.length >= 60); + + var cut = (this.pstop << 8) - data_start; + dbg_assert(cut >= 0); + + this.memory.set(data.subarray(0, cut), data_start); + this.memory.set(data.subarray(cut), this.pstart << 8); + dbg_log("rcv cut=" + h(cut), LOG_NET); + } + else + { + this.memory.set(data, data_start); + + if(data.length < 60) + { + this.memory.fill(0, data_start + data.length, data_start + 60); + } + } + + if(next >= this.pstop) + { + next += this.pstart - this.pstop; + } + + // write packet header + this.memory[offset] = ENRSR_RXOK; // status + this.memory[offset + 1] = next; + this.memory[offset + 2] = total_length; + this.memory[offset + 3] = total_length >> 8; + + this.curpg = next; + + dbg_log("rcv offset=" + h(offset) + " len=" + h(total_length) + " next=" + h(next), LOG_NET); + + this.do_interrupt(ENISR_RX); +}; + +Ne2k.prototype.get_page = function() +{ + return this.cr >> 6 & 3; +}; diff --git a/src/pci.js b/src/pci.js new file mode 100644 index 0000000..f708f7c --- /dev/null +++ b/src/pci.js @@ -0,0 +1,618 @@ +"use strict"; + +// http://wiki.osdev.org/PCI + +var +/** @const */ PCI_CONFIG_ADDRESS = 0xCF8, +/** @const */ PCI_CONFIG_DATA = 0xCFC; + +/** + * @constructor + * @param {CPU} cpu + */ +function PCI(cpu) +{ + this.pci_addr = new Uint8Array(4); + this.pci_value = new Uint8Array(4); + this.pci_response = new Uint8Array(4); + this.pci_status = new Uint8Array(4); + + this.pci_addr32 = new Int32Array(this.pci_addr.buffer); + this.pci_value32 = new Int32Array(this.pci_value.buffer); + this.pci_response32 = new Int32Array(this.pci_response.buffer); + this.pci_status32 = new Int32Array(this.pci_status.buffer); + + this.device_spaces = []; + this.devices = []; + + /** @const @type {CPU} */ + this.cpu = cpu; + + for(var i = 0; i < 256; i++) + { + this.device_spaces[i] = undefined; + this.devices[i] = undefined; + } + + this.io = cpu.io; + + cpu.io.register_write(PCI_CONFIG_DATA, this, + function(value) + { + this.pci_write8(this.pci_addr32[0], value); + }, + function(value) + { + this.pci_write16(this.pci_addr32[0], value); + }, + function(value) + { + this.pci_write32(this.pci_addr32[0], value); + }); + + cpu.io.register_write(PCI_CONFIG_DATA + 1, this, + function(value) + { + this.pci_write8(this.pci_addr32[0] + 1 | 0, value); + }); + + cpu.io.register_write(PCI_CONFIG_DATA + 2, this, + function(value) + { + this.pci_write8(this.pci_addr32[0] + 2 | 0, value); + }, + function(value) + { + this.pci_write16(this.pci_addr32[0] + 2 | 0, value); + }); + + cpu.io.register_write(PCI_CONFIG_DATA + 3, this, + function(value) + { + this.pci_write8(this.pci_addr32[0] + 3 | 0, value); + }); + + cpu.io.register_read_consecutive(PCI_CONFIG_DATA, this, + function() + { + return this.pci_response[0]; + }, + function() + { + return this.pci_response[1]; + }, + function() + { + return this.pci_response[2]; + }, + function() + { + return this.pci_response[3]; + } + ); + + cpu.io.register_read_consecutive(PCI_CONFIG_ADDRESS, this, + function() + { + return this.pci_status[0]; + }, + function() + { + return this.pci_status[1]; + }, + function() + { + return this.pci_status[2]; + }, + function() + { + return this.pci_status[3]; + } + ); + + cpu.io.register_write_consecutive(PCI_CONFIG_ADDRESS, this, + function(out_byte) + { + this.pci_addr[0] = out_byte & 0xFC; + }, + function(out_byte) + { + if((this.pci_addr[1] & 0x06) === 0x02 && (out_byte & 0x06) === 0x06) + { + dbg_log("CPU reboot via PCI"); + cpu.reboot_internal(); + return; + } + + this.pci_addr[1] = out_byte; + }, + function(out_byte) + { + this.pci_addr[2] = out_byte; + }, + function(out_byte) + { + this.pci_addr[3] = out_byte; + this.pci_query(); + } + ); + + + // Some experimental PCI devices taken from my PC: + + // 00:00.0 Host bridge: Intel Corporation 4 Series Chipset DRAM Controller (rev 02) + //var host_bridge = { + // pci_id: 0, + // pci_space: [ + // 0x86, 0x80, 0x20, 0x2e, 0x06, 0x00, 0x90, 0x20, 0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, + // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x10, 0xd3, 0x82, + // 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // ], + // pci_bars: [], + //}; + + // This needs to be set in order for seabios to not execute code outside of + // mapped memory. While we map the BIOS into high memory, we don't allow + // executing code there, which enables optimisations in read_imm8. + // See [make_bios_writable_intel] in src/fw/shadow.c in seabios for details + const PAM0 = 0x10; + + var host_bridge = { + pci_id: 0, + pci_space: [ + // 00:00.0 Host bridge: Intel Corporation 440FX - 82441FX PMC [Natoma] (rev 02) + 0x86, 0x80, 0x37, 0x12, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, PAM0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ], + pci_bars: [], + name: "82441FX PMC", + }; + this.register_device(host_bridge); + + this.isa_bridge = { + pci_id: 1 << 3, + pci_space: [ + // 00:01.0 ISA bridge: Intel Corporation 82371SB PIIX3 ISA [Natoma/Triton II] + 0x86, 0x80, 0x00, 0x70, 0x07, 0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0x06, 0x00, 0x00, 0x80, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ], + pci_bars: [], + name: "82371SB PIIX3 ISA", + }; + this.isa_bridge_space = this.register_device(this.isa_bridge); + this.isa_bridge_space8 = new Uint8Array(this.isa_bridge_space.buffer); + + // 00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev 90) + //this.register_device([ + // 0x86, 0x80, 0x4e, 0x24, 0x07, 0x01, 0x10, 0x00, 0x90, 0x01, 0x04, 0x06, 0x00, 0x00, 0x01, 0x00, + // 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x05, 0x20, 0xe0, 0xe0, 0x80, 0x22, + // 0xb0, 0xfe, 0xb0, 0xfe, 0xf1, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x02, 0x00, + //], 0x1e << 3); +} + +PCI.prototype.get_state = function() +{ + var state = []; + + for(var i = 0; i < 256; i++) + { + state[i] = this.device_spaces[i]; + } + + state[256] = this.pci_addr; + state[257] = this.pci_value; + state[258] = this.pci_response; + state[259] = this.pci_status; + + return state; +}; + +PCI.prototype.set_state = function(state) +{ + for(var i = 0; i < 256; i++) + { + var device = this.devices[i]; + var space = state[i]; + + if(!device || !space) + { + if(device) + { + dbg_log("Warning: While restoring PCI device: Device exists in current " + + "configuration but not in snapshot (" + device.name + ")"); + } + if(space) + { + dbg_log("Warning: While restoring PCI device: Device doesn't exist in current " + + "configuration but does in snapshot (device " + h(i, 2) + ")"); + } + continue; + } + + for(var bar_nr = 0; bar_nr < device.pci_bars.length; bar_nr++) + { + var value = space[(0x10 >> 2) + bar_nr]; + + if(value & 1) + { + var bar = device.pci_bars[bar_nr]; + var from = bar.original_bar & ~1 & 0xFFFF; + var to = value & ~1 & 0xFFFF; + this.set_io_bars(bar, from, to); + } + else + { + // memory, cannot be changed + } + } + + this.device_spaces[i].set(space); + } + + this.pci_addr.set(state[256]); + this.pci_value.set(state[257]); + this.pci_response.set(state[258]); + this.pci_status.set(state[259]); +}; + +PCI.prototype.pci_query = function() +{ + var dbg_line = "query"; + + // Bit | .31 .0 + // Fmt | EBBBBBBBBDDDDDFFFRRRRRR00 + + var bdf = this.pci_addr[2] << 8 | this.pci_addr[1], + addr = this.pci_addr[0] & 0xFC, + //devfn = bdf & 0xFF, + //bus = bdf >> 8, + dev = bdf >> 3 & 0x1F, + //fn = bdf & 7, + enabled = this.pci_addr[3] >> 7; + + dbg_line += " enabled=" + enabled; + dbg_line += " bdf=" + h(bdf, 4); + dbg_line += " dev=" + h(dev, 2); + dbg_line += " addr=" + h(addr, 2); + + var device = this.device_spaces[bdf]; + + if(device !== undefined) + { + this.pci_status32[0] = 0x80000000 | 0; + + if(addr < device.byteLength) + { + this.pci_response32[0] = device[addr >> 2]; + } + else + { + // required by freebsd-9.1 + this.pci_response32[0] = 0; + } + + dbg_line += " " + h(this.pci_addr32[0] >>> 0, 8) + " -> " + h(this.pci_response32[0] >>> 0, 8); + + if(addr >= device.byteLength) + { + dbg_line += " (undef)"; + } + + dbg_line += " (" + this.devices[bdf].name + ")"; + + dbg_log(dbg_line, LOG_PCI); + } + else + { + this.pci_response32[0] = -1; + this.pci_status32[0] = 0; + } +}; + +PCI.prototype.pci_write8 = function(address, written) +{ + var bdf = address >> 8 & 0xFFFF; + var addr = address & 0xFF; + + var space = new Uint8Array(this.device_spaces[bdf].buffer); + var device = this.devices[bdf]; + + if(!space) + { + return; + } + + dbg_assert(!(addr >= 0x10 && addr < 0x2C || addr >= 0x30 && addr < 0x34), + "PCI: Expected 32-bit write, got 8-bit (addr: " + h(addr) + ")"); + + dbg_log("PCI write8 dev=" + h(bdf >> 3, 2) + " (" + device.name + ") addr=" + h(addr, 4) + + " value=" + h(written, 2), LOG_PCI); + + space[addr] = written; +}; + +PCI.prototype.pci_write16 = function(address, written) +{ + dbg_assert((address & 1) === 0); + + var bdf = address >> 8 & 0xFFFF; + var addr = address & 0xFF; + + var space = new Uint16Array(this.device_spaces[bdf].buffer); + var device = this.devices[bdf]; + + if(!space) + { + return; + } + + if(addr >= 0x10 && addr < 0x2C) + { + // Bochs bios + dbg_log("Warning: PCI: Expected 32-bit write, got 16-bit (addr: " + h(addr) + ")"); + return; + } + + dbg_assert(!(addr >= 0x30 && addr < 0x34), + "PCI: Expected 32-bit write, got 16-bit (addr: " + h(addr) + ")"); + + dbg_log("PCI writ16 dev=" + h(bdf >> 3, 2) + " (" + device.name + ") addr=" + h(addr, 4) + + " value=" + h(written, 4), LOG_PCI); + + space[addr >>> 1] = written; +}; + +PCI.prototype.pci_write32 = function(address, written) +{ + dbg_assert((address & 3) === 0); + + var bdf = address >> 8 & 0xFFFF; + var addr = address & 0xFF; + + var space = this.device_spaces[bdf]; + var device = this.devices[bdf]; + + if(!space) + { + return; + } + + if(addr >= 0x10 && addr < 0x28) + { + var bar_nr = addr - 0x10 >> 2; + var bar = device.pci_bars[bar_nr]; + + dbg_log("BAR" + bar_nr + " exists=" + (bar ? "y" : "n") + " changed to " + + h(written >>> 0) + " dev=" + h(bdf >> 3, 2) + " (" + device.name + ") ", LOG_PCI); + + if(bar) + { + dbg_assert(!(bar.size & bar.size - 1), "bar size should be power of 2"); + + var space_addr = addr >> 2; + var type = space[space_addr] & 1; + + if((written | 3 | bar.size - 1) === -1) // size check + { + written = ~(bar.size - 1) | type; + + if(type === 0) + { + space[space_addr] = written; + } + } + else + { + if(type === 0) + { + // memory + var original_bar = bar.original_bar; + + if((written & ~0xF) !== (original_bar & ~0xF)) + { + // seabios + dbg_log("Warning: Changing memory bar not supported, ignored", LOG_PCI); + } + + // changing isn't supported yet, reset to default + space[space_addr] = original_bar; + } + } + + if(type === 1) + { + // io + dbg_assert(type === 1); + + var from = space[space_addr] & ~1 & 0xFFFF; + var to = written & ~1 & 0xFFFF; + dbg_log("io bar changed from " + h(from >>> 0, 8) + + " to " + h(to >>> 0, 8) + " size=" + bar.size, LOG_PCI); + this.set_io_bars(bar, from, to); + space[space_addr] = written | 1; + } + } + else + { + space[addr >> 2] = 0; + } + + dbg_log("BAR effective value: " + h(space[addr >> 2] >>> 0), LOG_PCI); + } + else if(addr === 0x30) + { + dbg_log("PCI write rom address dev=" + h(bdf >> 3, 2) + " (" + device.name + ")" + + " value=" + h(written >>> 0, 8), LOG_PCI); + + if(device.pci_rom_size) + { + if((written | 0x7FF) === (0xFFFFFFFF|0)) + { + space[addr >> 2] = -device.pci_rom_size | 0; + } + else + { + space[addr >> 2] = device.pci_rom_address | 0; + } + } + else + { + space[addr >> 2] = 0; + } + } + else if(addr === 0x04) + { + dbg_log("PCI write dev=" + h(bdf >> 3, 2) + " (" + device.name + ") addr=" + h(addr, 4) + + " value=" + h(written >>> 0, 8), LOG_PCI); + } + else + { + dbg_log("PCI write dev=" + h(bdf >> 3, 2) + " (" + device.name + ") addr=" + h(addr, 4) + + " value=" + h(written >>> 0, 8), LOG_PCI); + space[addr >>> 2] = written; + } +}; + +PCI.prototype.register_device = function(device) +{ + dbg_assert(device.pci_id !== undefined); + dbg_assert(device.pci_space !== undefined); + dbg_assert(device.pci_bars !== undefined); + + var device_id = device.pci_id; + + dbg_log("PCI register bdf=" + h(device_id) + " (" + device.name + ")", LOG_PCI); + + dbg_assert(!this.devices[device_id]); + dbg_assert(device.pci_space.length >= 64); + dbg_assert(device_id < this.devices.length); + + // convert bytewise notation from lspci to double words + var space = new Int32Array(64); + space.set(new Int32Array(new Uint8Array(device.pci_space).buffer)); + this.device_spaces[device_id] = space; + this.devices[device_id] = device; + + var bar_space = space.slice(4, 10); + + for(var i = 0; i < device.pci_bars.length; i++) + { + var bar = device.pci_bars[i]; + + if(!bar) + { + continue; + } + + var bar_base = bar_space[i]; + var type = bar_base & 1; + + bar.original_bar = bar_base; + bar.entries = []; + + if(type === 0) + { + // memory, not needed currently + } + else + { + dbg_assert(type === 1); + var port = bar_base & ~1; + + for(var j = 0; j < bar.size; j++) + { + bar.entries[j] = this.io.ports[port + j]; + } + } + } + + return space; +}; + +PCI.prototype.set_io_bars = function(bar, from, to) +{ + var count = bar.size; + dbg_log("Move io bars: from=" + h(from) + " to=" + h(to) + " count=" + count, LOG_PCI); + + var ports = this.io.ports; + + for(var i = 0; i < count; i++) + { + var old_entry = ports[from + i]; + + if(from + i >= 0x1000) + { + ports[from + i] = this.io.create_empty_entry(); + } + + if(old_entry.read8 === this.io.empty_port_read8 && + old_entry.read16 === this.io.empty_port_read16 && + old_entry.read32 === this.io.empty_port_read32 && + old_entry.write8 === this.io.empty_port_write && + old_entry.write16 === this.io.empty_port_write && + old_entry.write32 === this.io.empty_port_write) + { + // happens when a device doesn't register its full range (currently ne2k and virtio) + dbg_log("Warning: Bad IO bar: Source not mapped, port=" + h(from + i, 4), LOG_PCI); + } + + var entry = bar.entries[i]; + var empty_entry = ports[to + i]; + dbg_assert(entry && empty_entry); + + if(to + i >= 0x1000) + { + ports[to + i] = entry; + } + + if(empty_entry.read8 === this.io.empty_port_read8 || + empty_entry.read16 === this.io.empty_port_read16 || + empty_entry.read32 === this.io.empty_port_read32 || + empty_entry.write8 === this.io.empty_port_write || + empty_entry.write16 === this.io.empty_port_write || + empty_entry.write32 === this.io.empty_port_write) + { + // These can fail if the os maps an io port in multiple bars (indicating a bug) + // XXX: Fails during restore_state + dbg_log("Warning: Bad IO bar: Target already mapped, port=" + h(to + i, 4), LOG_PCI); + } + } +}; + +PCI.prototype.raise_irq = function(pci_id) +{ + var space = this.device_spaces[pci_id]; + dbg_assert(space); + + var pin = (space[0x3C >>> 2] >> 8 & 0xFF) - 1; + var device = (pci_id >> 3) - 1 & 0xFF; + var parent_pin = pin + device & 3; + var irq = this.isa_bridge_space8[0x60 + parent_pin]; + + //dbg_log("PCI raise irq " + h(irq) + " dev=" + h(device, 2) + + // " (" + this.devices[pci_id].name + ")", LOG_PCI); + this.cpu.device_raise_irq(irq); +}; + +PCI.prototype.lower_irq = function(pci_id) +{ + var space = this.device_spaces[pci_id]; + dbg_assert(space); + + var pin = space[0x3C >>> 2] >> 8 & 0xFF; + var device = pci_id >> 3 & 0xFF; + var parent_pin = pin + device - 2 & 3; + var irq = this.isa_bridge_space8[0x60 + parent_pin]; + + //dbg_log("PCI lower irq " + h(irq) + " dev=" + h(device, 2) + + // " (" + this.devices[pci_id].name + ")", LOG_PCI); + this.cpu.device_lower_irq(irq); +}; diff --git a/src/pic.js b/src/pic.js new file mode 100644 index 0000000..0e6ad0f --- /dev/null +++ b/src/pic.js @@ -0,0 +1,574 @@ +"use strict"; + +/** @const */ +var PIC_LOG_VERBOSE = false; + +/** + * Programmable Interrupt Controller + * http://stanislavs.org/helppc/8259.html + * + * @constructor + * @param {CPU} cpu + * @param {PIC=} master + */ +function PIC(cpu, master) +{ + /** + * all irqs off + * @type {number} + */ + this.irq_mask = 0; + + /** + * @type {number} + * + * Bogus default value (both master and slave mapped to 0). + * Will be initialized by the BIOS + */ + this.irq_map = 0; + + /** + * in-service register + * Holds interrupts that are currently being serviced + * @type {number} + */ + this.isr = 0; + + /** + * interrupt request register + * Holds interrupts that have been requested + * @type {number} + */ + this.irr = 0; + + this.irq_value = 0; + + /** + * @type {number} + */ + this.requested_irq = -1; + + this.master = master; + this.is_master = this.master === undefined; + this.slave = undefined; + + this.name = this.is_master ? "master" : "slave "; + + this.expect_icw4 = false; + this.state = 0; + this.read_isr = 0; + this.auto_eoi = 1; + this.special_mask_mode = 0; + + this.elcr = 0; + + this.cpu = cpu; + + // Checking for callable interrupts: + // (cpu changes interrupt flag) -> cpu.handle_irqs -> pic.check_irqs -> cpu.pic_call_irq + // (pic changes isr/irr) -> cpu.handle_irqs -> ... + + // triggering irqs: + // (io device has irq) -> cpu.device_raise_irq -> pic.set_irq -> cpu.handle_irqs -> (see above) + + + if(this.is_master) + { + this.slave = new PIC(this.cpu, this); + + this.check_irqs = function() + { + if(this.requested_irq >= 0) + { + PIC_LOG_VERBOSE && dbg_log("master> Already requested irq: " + this.requested_irq, LOG_PIC); + this.cpu.handle_irqs(); + return; + } + + var enabled_irr = this.irr & this.irq_mask; + + if(!enabled_irr) + { + if(PIC_LOG_VERBOSE) + { + dbg_log("master> no unmasked irrs. irr=" + h(this.irr, 2) + + " mask=" + h(this.irq_mask & 0xff, 2) + " isr=" + h(this.isr, 2), LOG_PIC); + } + return; + } + + var irq_mask = enabled_irr & -enabled_irr; + var special_mask = this.special_mask_mode ? this.irq_mask : -1; + + if(this.isr && (this.isr & -this.isr & special_mask) <= irq_mask) + { + // wait for eoi of higher or same priority interrupt + dbg_log("master> higher prio: isr=" + h(this.isr, 2) + + " mask=" + h(this.irq_mask & 0xff, 2) + " irq=" + h(irq_mask, 2), LOG_PIC); + return; + } + + dbg_assert(irq_mask !== 0); + var irq_number = v86util.int_log2_byte(irq_mask); + dbg_assert(irq_mask === (1 << irq_number)); + + PIC_LOG_VERBOSE && dbg_log("master> request irq " + irq_number, LOG_PIC); + + this.requested_irq = irq_number; + this.cpu.handle_irqs(); + }; + + this.acknowledge_irq = function() + { + if(this.requested_irq === -1) + { + return; + } + + if(this.irr === 0) + { + PIC_LOG_VERBOSE && dbg_log("master> spurious requested=" + this.requested_irq, LOG_PIC); + this.requested_irq = -1; + //this.cpu.pic_call_irq(this.irq_map | 7); + return; + } + dbg_assert(this.irr); // spurious + dbg_assert(this.requested_irq >= 0); + + var irq_mask = 1 << this.requested_irq; + + if((this.elcr & irq_mask) === 0) // not in level mode + { + this.irr &= ~irq_mask; + } + + if(!this.auto_eoi) + { + this.isr |= irq_mask; + } + + PIC_LOG_VERBOSE && dbg_log("master> acknowledge " + this.requested_irq, LOG_PIC); + if(this.requested_irq === 2) + { + this.slave.acknowledge_irq(); + } + else + { + this.cpu.pic_call_irq(this.irq_map | this.requested_irq); + } + + this.requested_irq = -1; + this.check_irqs(); + }; + } + else + { + // is slave + this.check_irqs = function() + { + if(this.requested_irq >= 0) + { + PIC_LOG_VERBOSE && dbg_log("slave > Already requested irq: " + this.requested_irq, LOG_PIC); + this.cpu.handle_irqs(); + return; + } + + var enabled_irr = this.irr & this.irq_mask; + + if(!enabled_irr) + { + if(PIC_LOG_VERBOSE) + { + dbg_log("slave > no unmasked irrs. irr=" + h(this.irr, 2) + + " mask=" + h(this.irq_mask & 0xff, 2) + " isr=" + h(this.isr, 2), LOG_PIC); + } + return; + } + + var irq_mask = enabled_irr & -enabled_irr; + var special_mask = this.special_mask_mode ? this.irq_mask : -1; + + if(this.isr && (this.isr & -this.isr & special_mask) <= irq_mask) + { + // wait for eoi of higher or same priority interrupt + PIC_LOG_VERBOSE && dbg_log("slave > higher prio: isr=" + h(this.isr, 2) + " irq=" + h(irq_mask, 2), LOG_PIC); + return; + } + + dbg_assert(irq_mask !== 0); + var irq_number = v86util.int_log2_byte(irq_mask); + dbg_assert(irq_mask === (1 << irq_number)); + + PIC_LOG_VERBOSE && dbg_log("slave > request irq " + irq_number, LOG_PIC); + this.requested_irq = irq_number; + this.master.set_irq(2); + }; + + this.acknowledge_irq = function() + { + if(this.requested_irq === -1) + { + return; + } + + if(this.irr === 0) + { + PIC_LOG_VERBOSE && dbg_log("slave > spurious requested=" + this.requested_irq, LOG_PIC); + this.requested_irq = -1; + this.master.irq_value &= ~(1 << 2); + this.cpu.pic_call_irq(this.irq_map | 7); + return; + } + + dbg_assert(this.irr); // spurious + dbg_assert(this.requested_irq >= 0); + + var irq_mask = 1 << this.requested_irq; + + if((this.elcr & irq_mask) === 0) // not in level mode + { + this.irr &= ~irq_mask; + } + + if(!this.auto_eoi) + { + this.isr |= irq_mask; + } + + this.master.irq_value &= ~(1 << 2); + PIC_LOG_VERBOSE && dbg_log("slave > acknowledge " + this.requested_irq, LOG_PIC); + this.cpu.pic_call_irq(this.irq_map | this.requested_irq); + + this.requested_irq = -1; + this.check_irqs(); + }; + } + + this.dump = function() + { + dbg_log("mask: " + h(this.irq_mask & 0xFF), LOG_PIC); + dbg_log("base: " + h(this.irq_map), LOG_PIC); + dbg_log("requested: " + h(this.irr), LOG_PIC); + dbg_log("serviced: " + h(this.isr), LOG_PIC); + + if(this.is_master) + { + this.slave.dump(); + } + }; + + var io_base; + var iobase_high; + if(this.is_master) + { + io_base = 0x20; + iobase_high = 0x4D0; + } + else + { + io_base = 0xA0; + iobase_high = 0x4D1; + } + + this.cpu.io.register_write(io_base, this, this.port20_write); + this.cpu.io.register_read(io_base, this, this.port20_read); + + this.cpu.io.register_write(io_base | 1, this, this.port21_write); + this.cpu.io.register_read(io_base | 1, this, this.port21_read); + + this.cpu.io.register_write(iobase_high, this, this.port4D0_write); + this.cpu.io.register_read(iobase_high, this, this.port4D0_read); + + + if(this.is_master) + { + this.set_irq = function(irq_number) + { + dbg_assert(irq_number >= 0 && irq_number < 16); + + if(irq_number >= 8) + { + this.slave.set_irq(irq_number - 8); + return; + } + + var irq_mask = 1 << irq_number; + if((this.irq_value & irq_mask) === 0) + { + if(PIC_LOG_VERBOSE) + { + dbg_log("master> set irq " + irq_number, LOG_PIC); + } + + this.irr |= irq_mask; + this.irq_value |= irq_mask; + this.check_irqs(); + } + else + { + if(PIC_LOG_VERBOSE) + { + dbg_log("master> set irq " + irq_number + ": already set!", LOG_PIC); + } + } + }; + + this.clear_irq = function(irq_number) + { + dbg_assert(irq_number >= 0 && irq_number < 16); + if(PIC_LOG_VERBOSE) + { + dbg_log("master> clear irq " + irq_number, LOG_PIC); + } + + if(irq_number >= 8) + { + this.slave.clear_irq(irq_number - 8); + return; + } + + var irq_mask = 1 << irq_number; + if(this.irq_value & irq_mask) + { + this.irq_value &= ~irq_mask; + this.irr &= ~irq_mask; + this.check_irqs(); + } + }; + } + else + { + this.set_irq = function(irq_number) + { + dbg_assert(irq_number >= 0 && irq_number < 8); + + var irq_mask = 1 << irq_number; + if((this.irq_value & irq_mask) === 0) + { + if(PIC_LOG_VERBOSE) + { + dbg_log("slave > set irq " + irq_number, LOG_PIC); + } + + this.irr |= irq_mask; + this.irq_value |= irq_mask; + this.check_irqs(); + } + else + { + if(PIC_LOG_VERBOSE) + { + dbg_log("slave > set irq " + irq_number + ": already set!", LOG_PIC); + } + } + }; + + this.clear_irq = function(irq_number) + { + dbg_assert(irq_number >= 0 && irq_number < 8); + if(PIC_LOG_VERBOSE) + { + dbg_log("slave > clear irq " + irq_number, LOG_PIC); + } + + var irq_mask = 1 << irq_number; + if(this.irq_value & irq_mask) + { + this.irq_value &= ~irq_mask; + this.irr &= ~irq_mask; + this.check_irqs(); + } + }; + } + + this.get_isr = function() + { + return this.isr; + }; +} + +PIC.prototype.get_state = function() +{ + var state = []; + + state[0] = this.irq_mask; + state[1] = this.irq_map; + state[2] = this.isr; + state[3] = this.irr; + state[4] = this.is_master; + state[5] = this.slave; + state[6] = this.expect_icw4; + state[7] = this.state; + state[8] = this.read_isr; + state[9] = this.auto_eoi; + state[10] = this.elcr; + + return state; +}; + +PIC.prototype.set_state = function(state) +{ + this.irq_mask = state[0]; + this.irq_map = state[1]; + this.isr = state[2]; + this.irr = state[3]; + this.is_master = state[4]; + this.slave && this.slave.set_state(state[5]); + this.expect_icw4 = state[6]; + this.state = state[7]; + this.read_isr = state[8]; + this.auto_eoi = state[9]; + this.elcr = state[10]; +}; + +PIC.prototype.port20_write = function(data_byte) +{ + //dbg_log("20 write: " + h(data_byte), LOG_PIC); + if(data_byte & 0x10) // xxxx1xxx + { + // icw1 + dbg_log("icw1 = " + h(data_byte), LOG_PIC); + this.isr = 0; + this.irr = 0; + this.irq_mask = 0; + this.irq_value = 0; + this.auto_eoi = 1; + this.requested_irq = -1; + + this.expect_icw4 = data_byte & 1; + this.state = 1; + } + else if(data_byte & 8) // xxx01xxx + { + // ocw3 + dbg_log("ocw3: " + h(data_byte), LOG_PIC); + if(data_byte & 2) + { + this.read_isr = data_byte & 1; + } + if(data_byte & 4) + { + dbg_assert(false, "unimplemented: polling", LOG_PIC); + } + if(data_byte & 0x40) + { + this.special_mask_mode = (data_byte & 0x20) === 0x20; + dbg_log("special mask mode: " + this.special_mask_mode, LOG_PIC); + } + } + else // xxx00xxx + { + // ocw2 + // end of interrupt + dbg_log("eoi: " + h(data_byte) + " (" + this.name + ")", LOG_PIC); + + var eoi_type = data_byte >> 5; + + if(eoi_type === 1) + { + // non-specific eoi + this.isr &= this.isr - 1; + dbg_log("new isr: " + h(this.isr, 2), LOG_PIC); + } + else if(eoi_type === 3) + { + // specific eoi + this.isr &= ~(1 << (data_byte & 7)); + } + else if((data_byte & 0xC8) === 0xC0) + { + // os2 v4 + let priority = data_byte & 7; + dbg_log("lowest priority: " + h(priority), LOG_PIC); + } + else + { + dbg_log("Unknown eoi: " + h(data_byte), LOG_PIC); + dbg_assert(false); + this.isr &= this.isr - 1; + } + + this.check_irqs(); + } +}; + +PIC.prototype.port20_read = function() +{ + if(this.read_isr) + { + dbg_log("read port 20h (isr): " + h(this.isr), LOG_PIC); + return this.isr; + } + else + { + dbg_log("read port 20h (irr): " + h(this.irr), LOG_PIC); + return this.irr; + } +}; + +PIC.prototype.port21_write = function(data_byte) +{ + //dbg_log("21 write: " + h(data_byte), LOG_PIC); + if(this.state === 0) + { + if(this.expect_icw4) + { + // icw4 + this.expect_icw4 = false; + this.auto_eoi = data_byte & 2; + dbg_log("icw4: " + h(data_byte) + " autoeoi=" + this.auto_eoi, LOG_PIC); + + if((data_byte & 1) === 0) + { + dbg_assert(false, "unimplemented: not 8086 mode", LOG_PIC); + } + } + else + { + // ocw1 + this.irq_mask = ~data_byte; + + if(PIC_LOG_VERBOSE) + { + dbg_log("interrupt mask: " + (this.irq_mask & 0xFF).toString(2) + + " (" + this.name + ")", LOG_PIC); + } + + this.check_irqs(); + } + } + else if(this.state === 1) + { + // icw2 + this.irq_map = data_byte; + dbg_log("interrupts are mapped to " + h(this.irq_map) + + " (" + this.name + ")", LOG_PIC); + this.state++; + } + else if(this.state === 2) + { + // icw3 + this.state = 0; + dbg_log("icw3: " + h(data_byte), LOG_PIC); + } +}; + +PIC.prototype.port21_read = function() +{ + dbg_log("21h read " + h(~this.irq_mask & 0xff), LOG_PIC); + return ~this.irq_mask & 0xFF; +}; + +PIC.prototype.port4D0_read = function() +{ + dbg_log("elcr read: " + h(this.elcr, 2), LOG_PIC); + return this.elcr; +}; + +PIC.prototype.port4D0_write = function(value) +{ + dbg_log("elcr write: " + h(value, 2), LOG_PIC); + // set by seabios to 00 0C (only set for pci interrupts) + this.elcr = value; +}; + diff --git a/src/pit.js b/src/pit.js new file mode 100644 index 0000000..f7813c1 --- /dev/null +++ b/src/pit.js @@ -0,0 +1,352 @@ +"use strict"; + +/** + * @const + * In kHz + */ +var OSCILLATOR_FREQ = 1193.1816666; // 1.193182 MHz + +/** + * @constructor + * + * Programmable Interval Timer + */ +function PIT(cpu, bus) +{ + /** @const @type {CPU} */ + this.cpu = cpu; + + this.bus = bus; + + this.counter_start_time = new Float64Array(3); + this.counter_start_value = new Uint16Array(3); + + this.counter_next_low = new Uint8Array(4); + this.counter_enabled = new Uint8Array(4); + this.counter_mode = new Uint8Array(4); + this.counter_read_mode = new Uint8Array(4); + + // 2 = latch low, 1 = latch high, 0 = no latch + this.counter_latch = new Uint8Array(4); + this.counter_latch_value = new Uint16Array(3); + + this.counter_reload = new Uint16Array(3); + + // TODO: + // - counter2 can be controlled by an input + + cpu.io.register_read(0x61, this, function() + { + var now = v86.microtick(); + + var ref_toggle = (now * (1000 * 1000 / 15000)) & 1; + var counter2_out = this.did_rollover(2, now); + + return ref_toggle << 4 | counter2_out << 5; + }); + cpu.io.register_write(0x61, this, function(data) + { + if(data & 1) + { + this.bus.send("pcspeaker-enable"); + } + else + { + this.bus.send("pcspeaker-disable"); + } + }); + + cpu.io.register_read(0x40, this, function() { return this.counter_read(0); }); + cpu.io.register_read(0x41, this, function() { return this.counter_read(1); }); + cpu.io.register_read(0x42, this, function() { return this.counter_read(2); }); + + cpu.io.register_write(0x40, this, function(data) { this.counter_write(0, data); }); + cpu.io.register_write(0x41, this, function(data) { this.counter_write(1, data); }); + cpu.io.register_write(0x42, this, function(data) { + this.counter_write(2, data); + this.bus.send("pcspeaker-update", [this.counter_mode[2], this.counter_reload[2]]); + }); + + cpu.io.register_write(0x43, this, this.port43_write); +} + +PIT.prototype.get_state = function() +{ + var state = []; + + state[0] = this.counter_next_low; + state[1] = this.counter_enabled; + state[2] = this.counter_mode; + state[3] = this.counter_read_mode; + state[4] = this.counter_latch; + state[5] = this.counter_latch_value; + state[6] = this.counter_reload; + state[7] = this.counter_start_time; + state[8] = this.counter_start_value; + + return state; +}; + +PIT.prototype.set_state = function(state) +{ + this.counter_next_low = state[0]; + this.counter_enabled = state[1]; + this.counter_mode = state[2]; + this.counter_read_mode = state[3]; + this.counter_latch = state[4]; + this.counter_latch_value = state[5]; + this.counter_reload = state[6]; + this.counter_start_time = state[7]; + this.counter_start_value = state[8]; +}; + +PIT.prototype.timer = function(now, no_irq) +{ + var time_to_next_interrupt = 100; + + // counter 0 produces interrupts + if(!no_irq) + { + if(this.counter_enabled[0] && this.did_rollover(0, now)) + { + this.counter_start_value[0] = this.get_counter_value(0, now); + this.counter_start_time[0] = now; + + dbg_log("pit interrupt. new value: " + this.counter_start_value[0], LOG_PIT); + + // This isn't strictly correct, but it's necessary since browsers + // may sleep longer than necessary to trigger the else branch below + // and clear the irq + this.cpu.device_lower_irq(0); + + this.cpu.device_raise_irq(0); + var mode = this.counter_mode[0]; + + if(mode === 0) + { + this.counter_enabled[0] = 0; + } + } + else + { + this.cpu.device_lower_irq(0); + } + + if(this.counter_enabled[0]) + { + const diff = now - this.counter_start_time[0]; + const diff_in_ticks = Math.floor(diff * OSCILLATOR_FREQ); + const ticks_missing = this.counter_start_value[0] - diff_in_ticks; // XXX: to simplify + time_to_next_interrupt = ticks_missing / OSCILLATOR_FREQ; + } + } + + return time_to_next_interrupt; +}; + +PIT.prototype.get_counter_value = function(i, now) +{ + if(!this.counter_enabled[i]) + { + return 0; + } + + var diff = now - this.counter_start_time[i]; + var diff_in_ticks = Math.floor(diff * OSCILLATOR_FREQ); + + var value = this.counter_start_value[i] - diff_in_ticks; + + dbg_log("diff=" + diff + " dticks=" + diff_in_ticks + " value=" + value + " reload=" + this.counter_reload[i], LOG_PIT); + + var reload = this.counter_reload[i]; + + if(value >= reload) + { + dbg_log("Warning: Counter" + i + " value " + value + " is larger than reload " + reload, LOG_PIT); + value %= reload; + } + else if(value < 0) + { + value = value % reload + reload; + } + + return value; +}; + +PIT.prototype.did_rollover = function(i, now) +{ + var diff = now - this.counter_start_time[i]; + + if(diff < 0) + { + // should only happen after restore_state + dbg_log("Warning: PIT timer difference is negative, resetting (timer " + i + ")"); + return true; + } + var diff_in_ticks = Math.floor(diff * OSCILLATOR_FREQ); + //dbg_log(i + ": diff=" + diff + " start_time=" + this.counter_start_time[i] + " diff_in_ticks=" + diff_in_ticks + " (" + diff * OSCILLATOR_FREQ + ") start_value=" + this.counter_start_value[i] + " did_rollover=" + (this.counter_start_value[i] < diff_in_ticks), LOG_PIT); + + return this.counter_start_value[i] < diff_in_ticks; +}; + +PIT.prototype.counter_read = function(i) +{ + var latch = this.counter_latch[i]; + + if(latch) + { + this.counter_latch[i]--; + + if(latch === 2) + { + return this.counter_latch_value[i] & 0xFF; + } + else + { + return this.counter_latch_value[i] >> 8; + } + } + else + { + var next_low = this.counter_next_low[i]; + + if(this.counter_mode[i] === 3) + { + this.counter_next_low[i] ^= 1; + } + + var value = this.get_counter_value(i, v86.microtick()); + + if(next_low) + { + return value & 0xFF; + } + else + { + return value >> 8; + } + } +}; + +PIT.prototype.counter_write = function(i, value) +{ + if(this.counter_next_low[i]) + { + this.counter_reload[i] = this.counter_reload[i] & ~0xFF | value; + } + else + { + this.counter_reload[i] = this.counter_reload[i] & 0xFF | value << 8; + } + + if(this.counter_read_mode[i] !== 3 || !this.counter_next_low[i]) + { + if(!this.counter_reload[i]) + { + this.counter_reload[i] = 0xFFFF; + } + + // depends on the mode, should actually + // happen on the first tick + this.counter_start_value[i] = this.counter_reload[i]; + + this.counter_enabled[i] = true; + + this.counter_start_time[i] = v86.microtick(); + + dbg_log("counter" + i + " reload=" + h(this.counter_reload[i]) + + " tick=" + (this.counter_reload[i] || 0x10000) / OSCILLATOR_FREQ + "ms", LOG_PIT); + } + + if(this.counter_read_mode[i] === 3) + { + this.counter_next_low[i] ^= 1; + } +}; + +PIT.prototype.port43_write = function(reg_byte) +{ + var mode = reg_byte >> 1 & 7, + binary_mode = reg_byte & 1, + i = reg_byte >> 6 & 3, + read_mode = reg_byte >> 4 & 3; + + if(i === 1) + { + dbg_log("Unimplemented timer1", LOG_PIT); + } + + if(i === 3) + { + dbg_log("Unimplemented read back", LOG_PIT); + return; + } + + if(read_mode === 0) + { + // latch + this.counter_latch[i] = 2; + var value = this.get_counter_value(i, v86.microtick()); + dbg_log("latch: " + value, LOG_PIT); + this.counter_latch_value[i] = value ? value - 1 : 0; + + return; + } + + if(mode >= 6) + { + // 6 and 7 are aliased to 2 and 3 + mode &= ~4; + } + + dbg_log("Control: mode=" + mode + " ctr=" + i + + " read_mode=" + read_mode + " bcd=" + binary_mode, LOG_PIT); + + if(read_mode === 1) + { + // msb + this.counter_next_low[i] = 0; + } + else if(read_mode === 2) + { + // lsb + this.counter_next_low[i] = 1; + } + else + { + // first lsb then msb + this.counter_next_low[i] = 1; + } + + if(i === 0) + { + this.cpu.device_lower_irq(0); + } + + if(mode === 0) + { + } + else if(mode === 3 || mode === 2) + { + // what is the difference + } + else + { + dbg_log("Unimplemented counter mode: " + h(mode), LOG_PIT); + } + + this.counter_mode[i] = mode; + this.counter_read_mode[i] = read_mode; + + if(i === 2) + { + this.bus.send("pcspeaker-update", [this.counter_mode[2], this.counter_reload[2]]); + } +}; + +PIT.prototype.dump = function() +{ + const reload = this.counter_reload[0]; + const time = (reload || 0x10000) / OSCILLATOR_FREQ; + dbg_log("counter0 ticks every " + time + "ms (reload=" + reload + ")"); +}; diff --git a/src/ps2.js b/src/ps2.js new file mode 100644 index 0000000..c1cf93b --- /dev/null +++ b/src/ps2.js @@ -0,0 +1,813 @@ +"use strict"; + +/** @const */ +let PS2_LOG_VERBOSE = false; + +/** + * @constructor + * @param {CPU} cpu + * @param {BusConnector} bus + */ +function PS2(cpu, bus) +{ + /** @const @type {CPU} */ + this.cpu = cpu; + + /** @const @type {BusConnector} */ + this.bus = bus; + + /** @type {boolean} */ + this.enable_mouse_stream = false; + + /** @type {boolean} */ + this.use_mouse = false; + + /** @type {boolean} */ + this.have_mouse = true; + + /** @type {number} */ + this.mouse_delta_x = 0; + /** @type {number} */ + this.mouse_delta_y = 0; + /** @type {number} */ + this.mouse_clicks = 0; + + /** @type {boolean} */ + this.have_keyboard = true; + + /** @type {boolean} */ + this.enable_keyboard_stream = false; + + /** @type {boolean} */ + this.next_is_mouse_command = false; + + /** @type {boolean} */ + this.next_read_sample = false; + + /** @type {boolean} */ + this.next_read_led = false; + + /** @type {boolean} */ + this.next_handle_scan_code_set = false; + + /** @type {boolean} */ + this.next_read_rate = false; + + /** @type {boolean} */ + this.next_read_resolution = false; + + /** + * @type {ByteQueue} + */ + this.kbd_buffer = new ByteQueue(1024); + + this.last_port60_byte = 0; + + /** @type {number} */ + this.sample_rate = 100; + + /** @type {number} */ + this.mouse_detect_state = 0; + + /** @type {number} */ + this.mouse_id = 0x00; + + /** @type {boolean} */ + this.mouse_reset_workaround = false; + + /** @type {number} */ + this.wheel_movement = 0; + + /** @type {number} */ + this.resolution = 4; + + /** @type {boolean} */ + this.scaling2 = false; + + /** @type {number} */ + this.last_mouse_packet = -1; + + /** + * @type {ByteQueue} + */ + this.mouse_buffer = new ByteQueue(1024); + + /** + * @type {boolean} + * Also known as DBBOUT OBF - Output Buffer Full flag + */ + this.next_byte_is_ready = false; + + /** @type {boolean} */ + this.next_byte_is_aux = false; + + this.bus.register("keyboard-code", function(code) + { + this.kbd_send_code(code); + }, this); + + this.bus.register("mouse-click", function(data) + { + this.mouse_send_click(data[0], data[1], data[2]); + }, this); + + this.bus.register("mouse-delta", function(data) + { + this.mouse_send_delta(data[0], data[1]); + }, this); + + this.bus.register("mouse-wheel", function(data) + { + this.wheel_movement -= data[0]; + this.wheel_movement -= data[1] * 2; // X Wheel Movement + this.wheel_movement = Math.min(7, Math.max(-8, this.wheel_movement)); + this.send_mouse_packet(0, 0); + }, this); + + this.command_register = 1 | 4; + // TODO: What should be the initial value? + this.controller_output_port = 0; + this.read_output_register = false; + this.read_command_register = false; + this.read_controller_output_port = false; + + cpu.io.register_read(0x60, this, this.port60_read); + cpu.io.register_read(0x64, this, this.port64_read); + + cpu.io.register_write(0x60, this, this.port60_write); + cpu.io.register_write(0x64, this, this.port64_write); +} + +PS2.prototype.get_state = function() +{ + var state = []; + + state[0] = this.enable_mouse_stream; + state[1] = this.use_mouse; + state[2] = this.have_mouse; + state[3] = this.mouse_delta_x; + state[4] = this.mouse_delta_y; + state[5] = this.mouse_clicks; + state[6] = this.have_keyboard; + state[7] = this.enable_keyboard_stream; + state[8] = this.next_is_mouse_command; + state[9] = this.next_read_sample; + state[10] = this.next_read_led; + state[11] = this.next_handle_scan_code_set; + state[12] = this.next_read_rate; + state[13] = this.next_read_resolution; + //state[14] = this.kbd_buffer; + state[15] = this.last_port60_byte; + state[16] = this.sample_rate; + state[17] = this.resolution; + state[18] = this.scaling2; + //state[19] = this.mouse_buffer; + state[20] = this.command_register; + state[21] = this.read_output_register; + state[22] = this.read_command_register; + state[23] = this.controller_output_port; + state[24] = this.read_controller_output_port; + state[25] = this.mouse_id; + state[26] = this.mouse_detect_state; + state[27] = this.mouse_reset_workaround; + + return state; +}; + +PS2.prototype.set_state = function(state) +{ + this.enable_mouse_stream = state[0]; + this.use_mouse = state[1]; + this.have_mouse = state[2]; + this.mouse_delta_x = state[3]; + this.mouse_delta_y = state[4]; + this.mouse_clicks = state[5]; + this.have_keyboard = state[6]; + this.enable_keyboard_stream = state[7]; + this.next_is_mouse_command = state[8]; + this.next_read_sample = state[9]; + this.next_read_led = state[10]; + this.next_handle_scan_code_set = state[11]; + this.next_read_rate = state[12]; + this.next_read_resolution = state[13]; + //this.kbd_buffer = state[14]; + this.last_port60_byte = state[15]; + this.sample_rate = state[16]; + this.resolution = state[17]; + this.scaling2 = state[18]; + //this.mouse_buffer = state[19]; + this.command_register = state[20]; + this.read_output_register = state[21]; + this.read_command_register = state[22]; + this.controller_output_port = state[23]; + this.read_controller_output_port = state[24]; + this.mouse_id = state[25] || 0; + this.mouse_detect_state = state[26] || 0; + this.mouse_reset_workaround = state[27] || false; + + this.next_byte_is_ready = false; + this.next_byte_is_aux = false; + this.kbd_buffer.clear(); + this.mouse_buffer.clear(); + + this.bus.send("mouse-enable", this.use_mouse); +}; + +PS2.prototype.raise_irq = function() +{ + if(this.next_byte_is_ready) + { + // Wait until previous byte is read + // http://halicery.com/Hardware/8042/8042_1503033_TXT.htm + return; + } + + // Kbd has priority over aux + if(this.kbd_buffer.length) + { + this.kbd_irq(); + } + else if(this.mouse_buffer.length) + { + this.mouse_irq(); + } +}; + +PS2.prototype.mouse_irq = function() +{ + this.next_byte_is_ready = true; + this.next_byte_is_aux = true; + + if(this.command_register & 2) + { + dbg_log("Mouse irq", LOG_PS2); + + // Pulse the irq line + // Note: can't lower immediately after rising, so lower before rising + // http://www.os2museum.com/wp/ibm-ps2-model-50-keyboard-controller/ + this.cpu.device_lower_irq(12); + this.cpu.device_raise_irq(12); + } +}; + +PS2.prototype.kbd_irq = function() +{ + this.next_byte_is_ready = true; + this.next_byte_is_aux = false; + + if(this.command_register & 1) + { + dbg_log("Keyboard irq", LOG_PS2); + + // Pulse the irq line + // Note: can't lower immediately after rising, so lower before rising + // http://www.os2museum.com/wp/ibm-ps2-model-50-keyboard-controller/ + this.cpu.device_lower_irq(1); + this.cpu.device_raise_irq(1); + } +}; + +PS2.prototype.kbd_send_code = function(code) +{ + if(this.enable_keyboard_stream) + { + dbg_log("adding kbd code: " + h(code), LOG_PS2); + this.kbd_buffer.push(code); + this.raise_irq(); + } +}; + +PS2.prototype.mouse_send_delta = function(delta_x, delta_y) +{ + if(!this.have_mouse || !this.use_mouse) + { + return; + } + + // note: delta_x or delta_y can be floating point numbers + + var factor = this.resolution * this.sample_rate / 80; + + this.mouse_delta_x += delta_x * factor; + this.mouse_delta_y += delta_y * factor; + + if(this.enable_mouse_stream) + { + var change_x = this.mouse_delta_x | 0, + change_y = this.mouse_delta_y | 0; + + if(change_x || change_y) + { + var now = Date.now(); + + //if(now - this.last_mouse_packet < 1000 / this.sample_rate) + //{ + // // TODO: set timeout + // return; + //} + + this.mouse_delta_x -= change_x; + this.mouse_delta_y -= change_y; + + this.send_mouse_packet(change_x, change_y); + } + } +}; + +PS2.prototype.mouse_send_click = function(left, middle, right) +{ + if(!this.have_mouse || !this.use_mouse) + { + return; + } + + this.mouse_clicks = left | right << 1 | middle << 2; + + if(this.enable_mouse_stream) + { + this.send_mouse_packet(0, 0); + } +}; + +PS2.prototype.send_mouse_packet = function(dx, dy) +{ + var info_byte = + (dy < 0) << 5 | + (dx < 0) << 4 | + 1 << 3 | + this.mouse_clicks, + delta_x = dx, + delta_y = dy; + + this.last_mouse_packet = Date.now(); + + //if(this.scaling2) + //{ + // // only in automatic packets, not 0xEB requests + // delta_x = this.apply_scaling2(delta_x); + // delta_y = this.apply_scaling2(delta_y); + //} + + this.mouse_buffer.push(info_byte); + this.mouse_buffer.push(delta_x); + this.mouse_buffer.push(delta_y); + + if(this.mouse_id === 0x04) + { + this.mouse_buffer.push( + 0 << 5 | // TODO: 5th button + 0 << 4 | // TODO: 4th button + this.wheel_movement & 0x0F + ); + this.wheel_movement = 0; + } + else if(this.mouse_id === 0x03) + { + this.mouse_buffer.push(this.wheel_movement & 0xFF); // Byte 4 - Z Movement + this.wheel_movement = 0; + } + + if(PS2_LOG_VERBOSE) + { + dbg_log("adding mouse packets: " + [info_byte, dx, dy], LOG_PS2); + } + + this.raise_irq(); +}; + +PS2.prototype.apply_scaling2 = function(n) +{ + // http://www.computer-engineering.org/ps2mouse/#Inputs.2C_Resolution.2C_and_Scaling + var abs = Math.abs(n), + sign = n >> 31; + + switch(abs) + { + case 0: + case 1: + case 3: + return n; + case 2: + return sign; + case 4: + return 6 * sign; + case 5: + return 9 * sign; + default: + return n << 1; + } +}; + +PS2.prototype.port60_read = function() +{ + //dbg_log("port 60 read: " + (buffer[0] || "(none)")); + + this.next_byte_is_ready = false; + + if(!this.kbd_buffer.length && !this.mouse_buffer.length) + { + // should not happen + dbg_log("Port 60 read: Empty", LOG_PS2); + return this.last_port60_byte; + } + + if(this.next_byte_is_aux) + { + this.cpu.device_lower_irq(12); + this.last_port60_byte = this.mouse_buffer.shift(); + dbg_log("Port 60 read (mouse): " + h(this.last_port60_byte), LOG_PS2); + } + else + { + this.cpu.device_lower_irq(1); + this.last_port60_byte = this.kbd_buffer.shift(); + dbg_log("Port 60 read (kbd) : " + h(this.last_port60_byte), LOG_PS2); + } + + if(this.kbd_buffer.length || this.mouse_buffer.length) + { + this.raise_irq(); + } + + return this.last_port60_byte; +}; + +PS2.prototype.port64_read = function() +{ + // status port + + var status_byte = 0x10; + + if(this.next_byte_is_ready) + { + status_byte |= 0x1; + } + if(this.next_byte_is_aux) + { + status_byte |= 0x20; + } + + dbg_log("port 64 read: " + h(status_byte), LOG_PS2); + + return status_byte; +}; + +PS2.prototype.port60_write = function(write_byte) +{ + dbg_log("port 60 write: " + h(write_byte), LOG_PS2); + + if(this.read_command_register) + { + this.command_register = write_byte; + this.read_command_register = false; + + // not sure, causes "spurious ack" in Linux + //this.kbd_buffer.push(0xFA); + //this.kbd_irq(); + + dbg_log("Keyboard command register = " + h(this.command_register), LOG_PS2); + } + else if(this.read_output_register) + { + this.read_output_register = false; + + this.mouse_buffer.clear(); + this.mouse_buffer.push(write_byte); + this.mouse_irq(); + } + else if(this.next_read_sample) + { + this.next_read_sample = false; + this.mouse_buffer.clear(); + this.mouse_buffer.push(0xFA); + + this.sample_rate = write_byte; + + switch(this.mouse_detect_state) + { + case -1: + if(write_byte === 60) + { + // Detect Windows NT and turn on workaround the bug + // 200->100->80->60 + this.mouse_reset_workaround = true; + this.mouse_detect_state = 0; + } + else + { + this.mouse_reset_workaround = false; + this.mouse_detect_state = (write_byte === 200) ? 1 : 0; + } + break; + case 0: + if(write_byte === 200) this.mouse_detect_state = 1; + break; + case 1: + if(write_byte === 100) this.mouse_detect_state = 2; + else if(write_byte === 200) this.mouse_detect_state = 3; + else this.mouse_detect_state = 0; + break; + case 2: + // Host sends sample rate 200->100->80 to activate Intellimouse wheel + if(write_byte === 80) this.mouse_id = 0x03; + this.mouse_detect_state = -1; + break; + case 3: + // Host sends sample rate 200->200->80 to activate Intellimouse 4th, 5th buttons + if(write_byte === 80) this.mouse_id = 0x04; + this.mouse_detect_state = -1; + break; + } + + dbg_log("mouse sample rate: " + h(write_byte) + ", mouse id: " + h(this.mouse_id), LOG_PS2); + + if(!this.sample_rate) + { + dbg_log("invalid sample rate, reset to 100", LOG_PS2); + this.sample_rate = 100; + } + + this.mouse_irq(); + } + else if(this.next_read_resolution) + { + this.next_read_resolution = false; + this.mouse_buffer.clear(); + this.mouse_buffer.push(0xFA); + + if(write_byte > 3) + { + this.resolution = 4; + dbg_log("invalid resolution, resetting to 4", LOG_PS2); + } + else + { + this.resolution = 1 << write_byte; + dbg_log("resolution: " + this.resolution, LOG_PS2); + } + this.mouse_irq(); + } + else if(this.next_read_led) + { + // nope + this.next_read_led = false; + this.kbd_buffer.push(0xFA); + this.kbd_irq(); + } + else if(this.next_handle_scan_code_set) + { + this.next_handle_scan_code_set = false; + + this.kbd_buffer.push(0xFA); + this.kbd_irq(); + + if(write_byte) + { + // set scan code set + } + else + { + this.kbd_buffer.push(2); + } + } + else if(this.next_read_rate) + { + // nope + this.next_read_rate = false; + this.kbd_buffer.push(0xFA); + this.kbd_irq(); + } + else if(this.next_is_mouse_command) + { + this.next_is_mouse_command = false; + dbg_log("Port 60 data register write: " + h(write_byte), LOG_PS2); + + if(!this.have_mouse) + { + return; + } + + // send ack + this.kbd_buffer.clear(); + this.mouse_buffer.clear(); + this.mouse_buffer.push(0xFA); + + switch(write_byte) + { + case 0xE6: + // set scaling to 1:1 + dbg_log("Scaling 1:1", LOG_PS2); + this.scaling2 = false; + break; + case 0xE7: + // set scaling to 2:1 + dbg_log("Scaling 2:1", LOG_PS2); + this.scaling2 = true; + break; + case 0xE8: + // set mouse resolution + this.next_read_resolution = true; + break; + case 0xE9: + // status request - send one packet + this.send_mouse_packet(0, 0); + break; + case 0xEB: + // request single packet + dbg_log("unimplemented request single packet", LOG_PS2); + this.send_mouse_packet(0, 0); + break; + case 0xF2: + // MouseID Byte + dbg_log("required id: " + h(this.mouse_id), LOG_PS2); + this.mouse_buffer.push(this.mouse_id); + + this.mouse_clicks = this.mouse_delta_x = this.mouse_delta_y = 0; + // this.send_mouse_packet(0, 0); + this.raise_irq(); + break; + case 0xF3: + // sample rate + this.next_read_sample = true; + break; + case 0xF4: + // enable streaming + this.enable_mouse_stream = true; + this.use_mouse = true; + this.bus.send("mouse-enable", true); + + this.mouse_clicks = this.mouse_delta_x = this.mouse_delta_y = 0; + break; + case 0xF5: + // disable streaming + this.enable_mouse_stream = false; + break; + case 0xF6: + // set defaults + this.enable_mouse_stream = false; + this.sample_rate = 100; + this.scaling2 = false; + this.resolution = 4; + break; + case 0xFF: + // reset, send completion code + dbg_log("Mouse reset", LOG_PS2); + this.mouse_buffer.push(0xAA); + this.mouse_buffer.push(0); + + this.use_mouse = true; + this.bus.send("mouse-enable", true); + + this.enable_mouse_stream = false; + this.sample_rate = 100; + this.scaling2 = false; + this.resolution = 4; + + if(!this.mouse_reset_workaround) + { + this.mouse_id = 0x00; + } + + this.mouse_clicks = this.mouse_delta_x = this.mouse_delta_y = 0; + break; + + default: + dbg_log("Unimplemented mouse command: " + h(write_byte), LOG_PS2); + } + + this.mouse_irq(); + } + else if(this.read_controller_output_port) + { + this.read_controller_output_port = false; + this.controller_output_port = write_byte; + // If we ever want to implement A20 masking, here is where + // we should turn the masking off if the second bit is on + } + else + { + dbg_log("Port 60 data register write: " + h(write_byte), LOG_PS2); + + // send ack + this.mouse_buffer.clear(); + this.kbd_buffer.clear(); + this.kbd_buffer.push(0xFA); + + switch(write_byte) + { + case 0xED: + this.next_read_led = true; + break; + case 0xF0: + // get/set scan code set + this.next_handle_scan_code_set = true; + break; + case 0xF2: + // identify + this.kbd_buffer.push(0xAB); + this.kbd_buffer.push(83); + break; + case 0xF3: + // Set typematic rate and delay + this.next_read_rate = true; + break; + case 0xF4: + // enable scanning + dbg_log("kbd enable scanning", LOG_PS2); + this.enable_keyboard_stream = true; + break; + case 0xF5: + // disable scanning + dbg_log("kbd disable scanning", LOG_PS2); + this.enable_keyboard_stream = false; + break; + case 0xF6: + // reset defaults + //this.enable_keyboard_stream = false; + break; + case 0xFF: + this.kbd_buffer.clear(); + this.kbd_buffer.push(0xFA); + this.kbd_buffer.push(0xAA); + this.kbd_buffer.push(0); + break; + default: + dbg_log("Unimplemented keyboard command: " + h(write_byte), LOG_PS2); + } + + this.kbd_irq(); + } +}; + +PS2.prototype.port64_write = function(write_byte) +{ + dbg_log("port 64 write: " + h(write_byte), LOG_PS2); + + switch(write_byte) + { + case 0x20: + this.kbd_buffer.clear(); + this.mouse_buffer.clear(); + this.kbd_buffer.push(this.command_register); + this.kbd_irq(); + break; + case 0x60: + this.read_command_register = true; + break; + case 0xD1: + this.read_controller_output_port = true; + break; + case 0xD3: + this.read_output_register = true; + break; + case 0xD4: + this.next_is_mouse_command = true; + break; + case 0xA7: + // Disable second port + dbg_log("Disable second port", LOG_PS2); + this.command_register |= 0x20; + break; + case 0xA8: + // Enable second port + dbg_log("Enable second port", LOG_PS2); + this.command_register &= ~0x20; + break; + case 0xA9: + // test second ps/2 port + this.kbd_buffer.clear(); + this.mouse_buffer.clear(); + this.kbd_buffer.push(0); + this.kbd_irq(); + break; + case 0xAA: + this.kbd_buffer.clear(); + this.mouse_buffer.clear(); + this.kbd_buffer.push(0x55); + this.kbd_irq(); + break; + case 0xAB: + // Test first PS/2 port + this.kbd_buffer.clear(); + this.mouse_buffer.clear(); + this.kbd_buffer.push(0); + this.kbd_irq(); + break; + case 0xAD: + // Disable Keyboard + dbg_log("Disable Keyboard", LOG_PS2); + this.command_register |= 0x10; + break; + case 0xAE: + // Enable Keyboard + dbg_log("Enable Keyboard", LOG_PS2); + this.command_register &= ~0x10; + break; + case 0xFE: + dbg_log("CPU reboot via PS2"); + this.cpu.reboot_internal(); + break; + default: + dbg_log("port 64: Unimplemented command byte: " + h(write_byte), LOG_PS2); + } +}; diff --git a/src/rtc.js b/src/rtc.js new file mode 100644 index 0000000..4468faf --- /dev/null +++ b/src/rtc.js @@ -0,0 +1,359 @@ +"use strict"; + +/** @const */ var CMOS_RTC_SECONDS = 0x00; +/** @const */ var CMOS_RTC_SECONDS_ALARM = 0x01; +/** @const */ var CMOS_RTC_MINUTES = 0x02; +/** @const */ var CMOS_RTC_MINUTES_ALARM = 0x03; +/** @const */ var CMOS_RTC_HOURS = 0x04; +/** @const */ var CMOS_RTC_HOURS_ALARM = 0x05; +/** @const */ var CMOS_RTC_DAY_WEEK = 0x06; +/** @const */ var CMOS_RTC_DAY_MONTH = 0x07; +/** @const */ var CMOS_RTC_MONTH = 0x08; +/** @const */ var CMOS_RTC_YEAR = 0x09; +/** @const */ var CMOS_STATUS_A = 0x0a; +/** @const */ var CMOS_STATUS_B = 0x0b; +/** @const */ var CMOS_STATUS_C = 0x0c; +/** @const */ var CMOS_STATUS_D = 0x0d; +/** @const */ var CMOS_RESET_CODE = 0x0f; + +/** @const */ var CMOS_FLOPPY_DRIVE_TYPE = 0x10; +/** @const */ var CMOS_DISK_DATA = 0x12; +/** @const */ var CMOS_EQUIPMENT_INFO = 0x14; +/** @const */ var CMOS_MEM_BASE_LOW = 0x15; +/** @const */ var CMOS_MEM_BASE_HIGH = 0x16; +/** @const */ var CMOS_MEM_OLD_EXT_LOW = 0x17; +/** @const */ var CMOS_MEM_OLD_EXT_HIGH = 0x18; +/** @const */ var CMOS_DISK_DRIVE1_TYPE = 0x19; +/** @const */ var CMOS_DISK_DRIVE2_TYPE = 0x1a; +/** @const */ var CMOS_DISK_DRIVE1_CYL = 0x1b; +/** @const */ var CMOS_DISK_DRIVE2_CYL = 0x24; +/** @const */ var CMOS_MEM_EXTMEM_LOW = 0x30; +/** @const */ var CMOS_MEM_EXTMEM_HIGH = 0x31; +/** @const */ var CMOS_CENTURY = 0x32; +/** @const */ var CMOS_MEM_EXTMEM2_LOW = 0x34; +/** @const */ var CMOS_MEM_EXTMEM2_HIGH = 0x35; +/** @const */ var CMOS_BIOS_BOOTFLAG1 = 0x38; +/** @const */ var CMOS_BIOS_DISKTRANSFLAG = 0x39; +/** @const */ var CMOS_BIOS_BOOTFLAG2 = 0x3d; +/** @const */ var CMOS_MEM_HIGHMEM_LOW = 0x5b; +/** @const */ var CMOS_MEM_HIGHMEM_MID = 0x5c; +/** @const */ var CMOS_MEM_HIGHMEM_HIGH = 0x5d; +/** @const */ var CMOS_BIOS_SMP_COUNT = 0x5f; + + +/** + * RTC (real time clock) and CMOS + * @constructor + * @param {CPU} cpu + */ +function RTC(cpu) +{ + /** @const @type {CPU} */ + this.cpu = cpu; + + this.cmos_index = 0; + this.cmos_data = new Uint8Array(128); + + // used for cmos entries + this.rtc_time = Date.now(); + this.last_update = this.rtc_time; + + // used for periodic interrupt + this.next_interrupt = 0; + + // next alarm interrupt + this.next_interrupt_alarm = 0; + + this.periodic_interrupt = false; + + // corresponds to default value for cmos_a + this.periodic_interrupt_time = 1000 / 1024; + + this.cmos_a = 0x26; + this.cmos_b = 2; + this.cmos_c = 0; + + this.nmi_disabled = 0; + + cpu.io.register_write(0x70, this, function(out_byte) + { + this.cmos_index = out_byte & 0x7F; + this.nmi_disabled = out_byte >> 7; + }); + + cpu.io.register_write(0x71, this, this.cmos_port_write); + cpu.io.register_read(0x71, this, this.cmos_port_read); +} + +RTC.prototype.get_state = function() +{ + var state = []; + + state[0] = this.cmos_index; + state[1] = this.cmos_data; + state[2] = this.rtc_time; + state[3] = this.last_update; + state[4] = this.next_interrupt; + state[5] = this.next_interrupt_alarm; + state[6] = this.periodic_interrupt; + state[7] = this.periodic_interrupt_time; + state[8] = this.cmos_a; + state[9] = this.cmos_b; + state[10] = this.cmos_c; + state[11] = this.nmi_disabled; + + return state; +}; + +RTC.prototype.set_state = function(state) +{ + this.cmos_index = state[0]; + this.cmos_data = state[1]; + this.rtc_time = state[2]; + this.last_update = state[3]; + this.next_interrupt = state[4]; + this.next_interrupt_alarm = state[5]; + this.periodic_interrupt = state[6]; + this.periodic_interrupt_time = state[7]; + this.cmos_a = state[8]; + this.cmos_b = state[9]; + this.cmos_c = state[10]; + this.nmi_disabled = state[11]; +}; + +RTC.prototype.timer = function(time, legacy_mode) +{ + time = Date.now(); // XXX + this.rtc_time += time - this.last_update; + this.last_update = time; + + if(this.periodic_interrupt && this.next_interrupt < time) + { + this.cpu.device_raise_irq(8); + this.cmos_c |= 1 << 6 | 1 << 7; + + this.next_interrupt += this.periodic_interrupt_time * + Math.ceil((time - this.next_interrupt) / this.periodic_interrupt_time); + } + else if(this.next_interrupt_alarm && this.next_interrupt_alarm < time) + { + this.cpu.device_raise_irq(8); + this.cmos_c |= 1 << 5 | 1 << 7; + + this.next_interrupt_alarm = 0; + } + + let t = 100; + + if(this.periodic_interrupt && this.next_interrupt) + { + t = Math.min(t, Math.max(0, this.next_interrupt - time)); + } + if(this.next_interrupt_alarm) + { + t = Math.min(t, Math.max(0, this.next_interrupt_alarm - time)); + } + + return t; +}; + +RTC.prototype.bcd_pack = function(n) +{ + var i = 0, + result = 0, + digit; + + while(n) + { + digit = n % 10; + + result |= digit << (4 * i); + i++; + n = (n - digit) / 10; + } + + return result; +}; + +RTC.prototype.bcd_unpack = function(n) +{ + const low = n & 0xF; + const high = n >> 4 & 0xF; + + dbg_assert(n < 0x100); + dbg_assert(low < 10); + dbg_assert(high < 10); + + return low + 10 * high; +}; + +RTC.prototype.encode_time = function(t) +{ + if(this.cmos_b & 4) + { + // binary mode + return t; + } + else + { + return this.bcd_pack(t); + } +}; + +RTC.prototype.decode_time = function(t) +{ + if(this.cmos_b & 4) + { + // binary mode + return t; + } + else + { + return this.bcd_unpack(t); + } +}; + +// TODO +// - interrupt on update +// - countdown +// - letting bios/os set values +// (none of these are used by seabios or the OSes we're +// currently testing) +RTC.prototype.cmos_port_read = function() +{ + var index = this.cmos_index; + + //this.cmos_index = 0xD; + + switch(index) + { + case CMOS_RTC_SECONDS: + return this.encode_time(new Date(this.rtc_time).getUTCSeconds()); + case CMOS_RTC_MINUTES: + return this.encode_time(new Date(this.rtc_time).getUTCMinutes()); + case CMOS_RTC_HOURS: + // TODO: 12 hour mode + return this.encode_time(new Date(this.rtc_time).getUTCHours()); + case CMOS_RTC_DAY_MONTH: + return this.encode_time(new Date(this.rtc_time).getUTCDate()); + case CMOS_RTC_MONTH: + return this.encode_time(new Date(this.rtc_time).getUTCMonth() + 1); + case CMOS_RTC_YEAR: + return this.encode_time(new Date(this.rtc_time).getUTCFullYear() % 100); + + case CMOS_STATUS_A: + if(v86.microtick() % 1000 >= 999) + { + // Set update-in-progress for one millisecond every second (we + // may not have precision higher than that in browser + // environments) + return this.cmos_a | 0x80; + } + return this.cmos_a; + case CMOS_STATUS_B: + //dbg_log("cmos read from index " + h(index)); + return this.cmos_b; + + case CMOS_STATUS_C: + // It is important to know that upon a IRQ 8, Status Register C + // will contain a bitmask telling which interrupt happened. + // What is important is that if register C is not read after an + // IRQ 8, then the interrupt will not happen again. + this.cpu.device_lower_irq(8); + + dbg_log("cmos reg C read", LOG_RTC); + // Missing IRQF flag + //return cmos_b & 0x70; + var c = this.cmos_c; + + this.cmos_c &= ~0xF0; + + return c; + + case CMOS_STATUS_D: + return 0; + + case CMOS_CENTURY: + return this.encode_time(new Date(this.rtc_time).getUTCFullYear() / 100 | 0); + + default: + dbg_log("cmos read from index " + h(index), LOG_RTC); + return this.cmos_data[this.cmos_index]; + } +}; + +RTC.prototype.cmos_port_write = function(data_byte) +{ + switch(this.cmos_index) + { + case 0xA: + this.cmos_a = data_byte & 0x7F; + this.periodic_interrupt_time = 1000 / (32768 >> (this.cmos_a & 0xF) - 1); + + dbg_log("Periodic interrupt, a=" + h(this.cmos_a, 2) + " t=" + this.periodic_interrupt_time , LOG_RTC); + break; + case 0xB: + this.cmos_b = data_byte; + if(this.cmos_b & 0x40) + { + this.next_interrupt = Date.now(); + } + + if(this.cmos_b & 0x20) + { + const now = new Date(); + + const seconds = this.decode_time(this.cmos_data[CMOS_RTC_SECONDS_ALARM]); + const minutes = this.decode_time(this.cmos_data[CMOS_RTC_MINUTES_ALARM]); + const hours = this.decode_time(this.cmos_data[CMOS_RTC_HOURS_ALARM]); + + const alarm_date = new Date(Date.UTC( + now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), + hours, minutes, seconds + )); + + const ms_from_now = alarm_date - now; + dbg_log("RTC alarm scheduled for " + alarm_date + + " hh:mm:ss=" + hours + ":" + minutes + ":" + seconds + + " ms_from_now=" + ms_from_now, LOG_RTC); + + this.next_interrupt_alarm = +alarm_date; + } + + if(this.cmos_b & 0x10) dbg_log("Unimplemented: updated interrupt", LOG_RTC); + + dbg_log("cmos b=" + h(this.cmos_b, 2), LOG_RTC); + break; + + case CMOS_RTC_SECONDS_ALARM: + case CMOS_RTC_MINUTES_ALARM: + case CMOS_RTC_HOURS_ALARM: + this.cmos_write(this.cmos_index, data_byte); + break; + + default: + dbg_log("cmos write index " + h(this.cmos_index) + ": " + h(data_byte), LOG_RTC); + } + + this.periodic_interrupt = (this.cmos_b & 0x40) === 0x40 && (this.cmos_a & 0xF) > 0; +}; + +/** + * @param {number} index + */ +RTC.prototype.cmos_read = function(index) +{ + dbg_assert(index < 128); + return this.cmos_data[index]; +}; + +/** + * @param {number} index + * @param {number} value + */ +RTC.prototype.cmos_write = function(index, value) +{ + dbg_log("cmos " + h(index) + " <- " + h(value), LOG_RTC); + dbg_assert(index < 128); + this.cmos_data[index] = value; +}; diff --git a/src/rust/analysis.rs b/src/rust/analysis.rs new file mode 100644 index 0000000..f52a6bc --- /dev/null +++ b/src/rust/analysis.rs @@ -0,0 +1,99 @@ +#![allow(non_snake_case)] + +use cpu_context::CpuContext; +use prefix::{PREFIX_66, PREFIX_67, PREFIX_F2, PREFIX_F3}; +use regs::{CS, DS, ES, FS, GS, SS}; + +#[derive(PartialEq, Eq)] +pub enum AnalysisType { + Normal, + BlockBoundary, + Jump { + offset: i32, + is_32: bool, + condition: Option, + }, + STI, +} + +pub struct Analysis { + pub no_next_instruction: bool, + pub absolute_jump: bool, + pub ty: AnalysisType, +} + +pub fn analyze_step(mut cpu: &mut CpuContext) -> Analysis { + let mut analysis = Analysis { + no_next_instruction: false, + absolute_jump: false, + ty: AnalysisType::Normal, + }; + cpu.prefixes = 0; + let opcode = cpu.read_imm8() as u32 | (cpu.osize_32() as u32) << 8; + ::gen::analyzer::analyzer(opcode, &mut cpu, &mut analysis); + analysis +} + +pub fn analyze_step_handle_prefix(cpu: &mut CpuContext, analysis: &mut Analysis) { + ::gen::analyzer::analyzer( + cpu.read_imm8() as u32 | (cpu.osize_32() as u32) << 8, + cpu, + analysis, + ) +} +pub fn analyze_step_handle_segment_prefix( + segment: u32, + cpu: &mut CpuContext, + analysis: &mut Analysis, +) { + dbg_assert!(segment <= 5); + cpu.prefixes |= segment + 1; + analyze_step_handle_prefix(cpu, analysis) +} + +pub fn instr16_0F_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + ::gen::analyzer0f::analyzer(cpu.read_imm8() as u32, cpu, analysis) +} +pub fn instr32_0F_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + ::gen::analyzer0f::analyzer(cpu.read_imm8() as u32 | 0x100, cpu, analysis) +} +pub fn instr_26_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + analyze_step_handle_segment_prefix(ES, cpu, analysis) +} +pub fn instr_2E_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + analyze_step_handle_segment_prefix(CS, cpu, analysis) +} +pub fn instr_36_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + analyze_step_handle_segment_prefix(SS, cpu, analysis) +} +pub fn instr_3E_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + analyze_step_handle_segment_prefix(DS, cpu, analysis) +} +pub fn instr_64_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + analyze_step_handle_segment_prefix(FS, cpu, analysis) +} +pub fn instr_65_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + analyze_step_handle_segment_prefix(GS, cpu, analysis) +} +pub fn instr_66_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + cpu.prefixes |= PREFIX_66; + analyze_step_handle_prefix(cpu, analysis) +} +pub fn instr_67_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + cpu.prefixes |= PREFIX_67; + analyze_step_handle_prefix(cpu, analysis) +} +pub fn instr_F0_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + // lock: Ignored + analyze_step_handle_prefix(cpu, analysis) +} +pub fn instr_F2_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + cpu.prefixes |= PREFIX_F2; + analyze_step_handle_prefix(cpu, analysis) +} +pub fn instr_F3_analyze(cpu: &mut CpuContext, analysis: &mut Analysis) { + cpu.prefixes |= PREFIX_F3; + analyze_step_handle_prefix(cpu, analysis) +} + +pub fn modrm_analyze(ctx: &mut CpuContext, modrm_byte: u8) { ::modrm::skip(ctx, modrm_byte); } diff --git a/src/rust/codegen.rs b/src/rust/codegen.rs new file mode 100644 index 0000000..2c6a01e --- /dev/null +++ b/src/rust/codegen.rs @@ -0,0 +1,2648 @@ +use cpu::cpu::{ + tlb_data, FLAG_CARRY, FLAG_OVERFLOW, FLAG_SIGN, FLAG_ZERO, OPSIZE_8, OPSIZE_16, OPSIZE_32, + TLB_GLOBAL, TLB_HAS_CODE, TLB_NO_USER, TLB_READONLY, TLB_VALID, +}; +use cpu::global_pointers; +use cpu::memory; +use jit::{Instruction, InstructionOperand, InstructionOperandDest, JitContext}; +use modrm; +use modrm::ModrmByte; +use profiler; +use regs; +use wasmgen::wasm_builder::{WasmBuilder, WasmLocal, WasmLocalI64}; + +pub fn gen_add_cs_offset(ctx: &mut JitContext) { + if !ctx.cpu.has_flat_segmentation() { + ctx.builder + .load_fixed_i32(global_pointers::get_seg_offset(regs::CS)); + ctx.builder.add_i32(); + } +} + +pub fn gen_get_eip(builder: &mut WasmBuilder) { + builder.load_fixed_i32(global_pointers::instruction_pointer as u32); +} + +pub fn gen_set_eip_to_after_current_instruction(ctx: &mut JitContext) { + ctx.builder + .const_i32(global_pointers::instruction_pointer as i32); + gen_get_eip(ctx.builder); + ctx.builder.const_i32(!0xFFF); + ctx.builder.and_i32(); + ctx.builder.const_i32(ctx.cpu.eip as i32 & 0xFFF); + ctx.builder.or_i32(); + ctx.builder.store_aligned_i32(0); +} + +pub fn gen_set_previous_eip_offset_from_eip_with_low_bits( + builder: &mut WasmBuilder, + low_bits: i32, +) { + // previous_ip = instruction_pointer & ~0xFFF | low_bits; + dbg_assert!(low_bits & !0xFFF == 0); + builder.const_i32(global_pointers::previous_ip as i32); + gen_get_eip(builder); + builder.const_i32(!0xFFF); + builder.and_i32(); + builder.const_i32(low_bits); + builder.or_i32(); + builder.store_aligned_i32(0); +} + +pub fn gen_set_eip_low_bits(builder: &mut WasmBuilder, low_bits: i32) { + // instruction_pointer = instruction_pointer & ~0xFFF | low_bits; + dbg_assert!(low_bits & !0xFFF == 0); + builder.const_i32(global_pointers::instruction_pointer as i32); + gen_get_eip(builder); + builder.const_i32(!0xFFF); + builder.and_i32(); + builder.const_i32(low_bits); + builder.or_i32(); + builder.store_aligned_i32(0); +} + +pub fn gen_set_eip_low_bits_and_jump_rel32(builder: &mut WasmBuilder, low_bits: i32, n: i32) { + // instruction_pointer = (instruction_pointer & ~0xFFF | low_bits) + n; + dbg_assert!(low_bits & !0xFFF == 0); + builder.const_i32(global_pointers::instruction_pointer as i32); + gen_get_eip(builder); + builder.const_i32(!0xFFF); + builder.and_i32(); + builder.const_i32(low_bits); + builder.or_i32(); + if n != 0 { + builder.const_i32(n); + builder.add_i32(); + } + builder.store_aligned_i32(0); +} + +pub fn gen_relative_jump(builder: &mut WasmBuilder, n: i32) { + // add n to instruction_pointer + if n != 0 { + builder.const_i32(global_pointers::instruction_pointer as i32); + gen_get_eip(builder); + builder.const_i32(n); + builder.add_i32(); + builder.store_aligned_i32(0); + } +} + +pub fn gen_page_switch_check( + ctx: &mut JitContext, + next_block_addr: u32, + last_instruction_addr: u32, +) { + // After switching a page while in jitted code, check if the page mapping still holds + + gen_get_eip(ctx.builder); + let address_local = ctx.builder.set_new_local(); + gen_get_phys_eip_plus_mem(ctx, &address_local); + ctx.builder.free_local(address_local); + + ctx.builder + .const_i32(next_block_addr as i32 + unsafe { memory::mem8 } as i32); + ctx.builder.ne_i32(); + + if cfg!(debug_assertions) { + ctx.builder.if_void(); + gen_profiler_stat_increment(ctx.builder, profiler::stat::FAILED_PAGE_CHANGE); + gen_debug_track_jit_exit(ctx.builder, last_instruction_addr); + ctx.builder.br(ctx.exit_label); + ctx.builder.block_end(); + } + else { + ctx.builder.br_if(ctx.exit_label); + } +} + +pub fn gen_update_instruction_counter(ctx: &mut JitContext) { + ctx.builder + .const_i32(global_pointers::instruction_counter as i32); + ctx.builder + .load_fixed_i32(global_pointers::instruction_counter as u32); + ctx.builder.get_local(&ctx.instruction_counter); + ctx.builder.add_i32(); + ctx.builder.store_aligned_i32(0); +} + +pub fn gen_get_reg8(ctx: &mut JitContext, r: u32) { + match r { + regs::AL | regs::CL | regs::DL | regs::BL => { + ctx.builder.get_local(&ctx.register_locals[r as usize]); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + }, + regs::AH | regs::CH | regs::DH | regs::BH => { + ctx.builder + .get_local(&ctx.register_locals[(r - 4) as usize]); + ctx.builder.const_i32(8); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + }, + _ => assert!(false), + } +} + +/// Return a new local referencing one of the 8 bit registers or a direct reference to one of the +/// register locals. Higher bits might be garbage (suitable for gen_cmp8 etc.). Must be freed with +/// gen_free_reg8_or_alias. +pub fn gen_get_reg8_or_alias_to_reg32(ctx: &mut JitContext, r: u32) -> WasmLocal { + match r { + regs::AL | regs::CL | regs::DL | regs::BL => ctx.register_locals[r as usize].unsafe_clone(), + regs::AH | regs::CH | regs::DH | regs::BH => { + ctx.builder + .get_local(&ctx.register_locals[(r - 4) as usize]); + ctx.builder.const_i32(8); + ctx.builder.shr_u_i32(); + ctx.builder.set_new_local() + }, + _ => panic!(), + } +} + +pub fn gen_free_reg8_or_alias(ctx: &mut JitContext, r: u32, local: WasmLocal) { + match r { + regs::AL | regs::CL | regs::DL | regs::BL => {}, + regs::AH | regs::CH | regs::DH | regs::BH => ctx.builder.free_local(local), + _ => panic!(), + } +} + +pub fn gen_get_reg16(ctx: &mut JitContext, r: u32) { + ctx.builder.get_local(&ctx.register_locals[r as usize]); + ctx.builder.const_i32(0xFFFF); + ctx.builder.and_i32(); +} + +pub fn gen_get_reg32(ctx: &mut JitContext, r: u32) { + ctx.builder.get_local(&ctx.register_locals[r as usize]); +} + +pub fn gen_set_reg8(ctx: &mut JitContext, r: u32) { + match r { + regs::AL | regs::CL | regs::DL | regs::BL => { + // reg32[r] = stack_value & 0xFF | reg32[r] & ~0xFF + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + + ctx.builder.get_local(&ctx.register_locals[r as usize]); + ctx.builder.const_i32(!0xFF); + ctx.builder.and_i32(); + + ctx.builder.or_i32(); + ctx.builder.set_local(&ctx.register_locals[r as usize]); + }, + regs::AH | regs::CH | regs::DH | regs::BH => { + // reg32[r] = stack_value << 8 & 0xFF00 | reg32[r] & ~0xFF00 + ctx.builder.const_i32(8); + ctx.builder.shl_i32(); + ctx.builder.const_i32(0xFF00); + ctx.builder.and_i32(); + + ctx.builder + .get_local(&ctx.register_locals[(r - 4) as usize]); + ctx.builder.const_i32(!0xFF00); + ctx.builder.and_i32(); + + ctx.builder.or_i32(); + ctx.builder + .set_local(&ctx.register_locals[(r - 4) as usize]); + }, + _ => assert!(false), + } +} + +pub fn gen_set_reg8_unmasked(ctx: &mut JitContext, r: u32) { + if cfg!(debug_assertions) { + let val = ctx.builder.set_new_local(); + ctx.builder.get_local(&val); + ctx.builder.const_i32(!0xFF); + ctx.builder.and_i32(); + ctx.builder.if_void(); + ctx.builder.unreachable(); + ctx.builder.block_end(); + ctx.builder.get_local(&val); + ctx.builder.free_local(val); + } + + match r { + regs::AL | regs::CL | regs::DL | regs::BL => { + // reg32[r] = stack_value | reg32[r] & ~0xFF + ctx.builder.get_local(&ctx.register_locals[r as usize]); + ctx.builder.const_i32(!0xFF); + ctx.builder.and_i32(); + + ctx.builder.or_i32(); + ctx.builder.set_local(&ctx.register_locals[r as usize]); + }, + regs::AH | regs::CH | regs::DH | regs::BH => { + // reg32[r] = stack_value << 8 | reg32[r] & ~0xFF00 + ctx.builder.const_i32(8); + ctx.builder.shl_i32(); + ctx.builder.const_i32(0xFF00); + ctx.builder.and_i32(); + + ctx.builder + .get_local(&ctx.register_locals[(r - 4) as usize]); + ctx.builder.const_i32(!0xFF00); + ctx.builder.and_i32(); + + ctx.builder.or_i32(); + ctx.builder + .set_local(&ctx.register_locals[(r - 4) as usize]); + }, + _ => assert!(false), + } +} + +pub fn gen_set_reg16(ctx: &mut JitContext, r: u32) { + gen_set_reg16_local(ctx.builder, &ctx.register_locals[r as usize]); +} + +pub fn gen_set_reg16_unmasked(ctx: &mut JitContext, r: u32) { + if cfg!(debug_assertions) { + let val = ctx.builder.set_new_local(); + ctx.builder.get_local(&val); + ctx.builder.const_i32(!0xFFFF); + ctx.builder.and_i32(); + ctx.builder.if_void(); + ctx.builder.unreachable(); + ctx.builder.block_end(); + ctx.builder.get_local(&val); + ctx.builder.free_local(val); + } + + ctx.builder.get_local(&ctx.reg(r)); + ctx.builder.const_i32(!0xFFFF); + ctx.builder.and_i32(); + ctx.builder.or_i32(); + ctx.builder.set_local(&ctx.reg(r)); +} + +pub fn gen_set_reg16_local(builder: &mut WasmBuilder, local: &WasmLocal) { + // reg32[r] = v & 0xFFFF | reg32[r] & ~0xFFFF + builder.const_i32(0xFFFF); + builder.and_i32(); + builder.get_local(local); + builder.const_i32(!0xFFFF); + builder.and_i32(); + builder.or_i32(); + builder.set_local(local); +} + +pub fn gen_set_reg32(ctx: &mut JitContext, r: u32) { + ctx.builder.set_local(&ctx.register_locals[r as usize]); +} + +pub fn decr_exc_asize(ctx: &mut JitContext) { + gen_get_reg32(ctx, regs::ECX); + ctx.builder.const_i32(1); + ctx.builder.sub_i32(); + if ctx.cpu.asize_32() { + gen_set_reg32(ctx, regs::ECX); + } + else { + gen_set_reg16(ctx, regs::CX); + } +} + +pub fn gen_read_reg_xmm128_into_scratch(ctx: &mut JitContext, r: u32) { + ctx.builder + .const_i32(global_pointers::sse_scratch_register as i32); + let dest = global_pointers::get_reg_xmm_offset(r); + ctx.builder.const_i32(dest as i32); + ctx.builder.load_aligned_i64(0); + ctx.builder.store_aligned_i64(0); + + ctx.builder + .const_i32(global_pointers::sse_scratch_register as i32 + 8); + let dest = global_pointers::get_reg_xmm_offset(r) + 8; + ctx.builder.const_i32(dest as i32); + ctx.builder.load_aligned_i64(0); + ctx.builder.store_aligned_i64(0); +} + +pub fn gen_get_sreg(ctx: &mut JitContext, r: u32) { + ctx.builder + .load_fixed_u16(global_pointers::get_sreg_offset(r)) +} + +pub fn gen_get_ss_offset(ctx: &mut JitContext) { + ctx.builder + .load_fixed_i32(global_pointers::get_seg_offset(regs::SS)); +} + +pub fn gen_get_flags(builder: &mut WasmBuilder) { + builder.load_fixed_i32(global_pointers::flags as u32); +} +fn gen_get_flags_changed(builder: &mut WasmBuilder) { + builder.load_fixed_i32(global_pointers::flags_changed as u32); +} +fn gen_get_last_result(builder: &mut WasmBuilder, previous_instruction: &Instruction) { + match previous_instruction { + Instruction::Add { + dest: InstructionOperandDest::WasmLocal(l), + opsize: OPSIZE_32, + .. + } + | Instruction::AdcSbb { + dest: InstructionOperandDest::WasmLocal(l), + opsize: OPSIZE_32, + .. + } + | Instruction::Sub { + dest: InstructionOperandDest::WasmLocal(l), + opsize: OPSIZE_32, + .. + } + | Instruction::Bitwise { + dest: InstructionOperandDest::WasmLocal(l), + opsize: OPSIZE_32, + } + | Instruction::NonZeroShift { + dest: InstructionOperandDest::WasmLocal(l), + opsize: OPSIZE_32, + } => builder.get_local(&l), + Instruction::Cmp { + dest: InstructionOperandDest::WasmLocal(l), + source, + opsize: OPSIZE_32, + } => { + if source.is_zero() { + builder.get_local(&l) + } + else { + builder.load_fixed_i32(global_pointers::last_result as u32) + } + }, + _ => builder.load_fixed_i32(global_pointers::last_result as u32), + } +} +fn gen_get_last_op_size(builder: &mut WasmBuilder) { + builder.load_fixed_i32(global_pointers::last_op_size as u32); +} +fn gen_get_last_op1(builder: &mut WasmBuilder, previous_instruction: &Instruction) { + match previous_instruction { + Instruction::Cmp { + dest: InstructionOperandDest::WasmLocal(l), + source: _, + opsize: OPSIZE_32, + } => builder.get_local(&l), + _ => builder.load_fixed_i32(global_pointers::last_op1 as u32), + } +} + +pub fn gen_get_page_fault(builder: &mut WasmBuilder) { + builder.load_fixed_u8(global_pointers::page_fault as u32); +} + +/// sign-extend a byte value on the stack and leave it on the stack +pub fn sign_extend_i8(builder: &mut WasmBuilder) { + builder.const_i32(24); + builder.shl_i32(); + builder.const_i32(24); + builder.shr_s_i32(); +} + +/// sign-extend a two byte value on the stack and leave it on the stack +pub fn sign_extend_i16(builder: &mut WasmBuilder) { + builder.const_i32(16); + builder.shl_i32(); + builder.const_i32(16); + builder.shr_s_i32(); +} + +pub fn gen_fn0_const(builder: &mut WasmBuilder, name: &str) { builder.call_fn0(name) } +pub fn gen_fn1_const(builder: &mut WasmBuilder, name: &str, arg0: u32) { + builder.const_i32(arg0 as i32); + builder.call_fn1(name); +} +pub fn gen_fn2_const(builder: &mut WasmBuilder, name: &str, arg0: u32, arg1: u32) { + builder.const_i32(arg0 as i32); + builder.const_i32(arg1 as i32); + builder.call_fn2(name); +} + +// helper functions for gen/generate_jit.js +pub fn gen_modrm_fn0(builder: &mut WasmBuilder, name: &str) { + // generates: fn( _ ) + builder.call_fn1(name); +} +pub fn gen_modrm_fn1(builder: &mut WasmBuilder, name: &str, arg0: u32) { + // generates: fn( _, arg0 ) + builder.const_i32(arg0 as i32); + builder.call_fn2(name); +} + +pub fn gen_modrm_resolve(ctx: &mut JitContext, modrm_byte: ModrmByte) { + modrm::gen(ctx, modrm_byte) +} +pub fn gen_modrm_resolve_with_local( + ctx: &mut JitContext, + modrm_byte: ModrmByte, + gen: &dyn Fn(&mut JitContext, &WasmLocal), +) { + if let Some(r) = modrm::get_as_reg_index_if_possible(ctx, &modrm_byte) { + gen(ctx, &ctx.reg(r)); + } + else { + gen_modrm_resolve(ctx, modrm_byte); + let address = ctx.builder.set_new_local(); + gen(ctx, &address); + ctx.builder.free_local(address); + } +} + +pub fn gen_set_reg8_r(ctx: &mut JitContext, dest: u32, src: u32) { + // generates: reg8[r_dest] = reg8[r_src] + if src != dest { + gen_get_reg8(ctx, src); + gen_set_reg8_unmasked(ctx, dest); + } +} +pub fn gen_set_reg16_r(ctx: &mut JitContext, dest: u32, src: u32) { + // generates: reg16[r_dest] = reg16[r_src] + if src != dest { + gen_get_reg16(ctx, src); + gen_set_reg16_unmasked(ctx, dest); + } +} +pub fn gen_set_reg32_r(ctx: &mut JitContext, dest: u32, src: u32) { + // generates: reg32[r_dest] = reg32[r_src] + if src != dest { + gen_get_reg32(ctx, src); + gen_set_reg32(ctx, dest); + } +} + +pub fn gen_modrm_resolve_safe_read8(ctx: &mut JitContext, modrm_byte: ModrmByte) { + gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| gen_safe_read8(ctx, addr)); +} +pub fn gen_modrm_resolve_safe_read16(ctx: &mut JitContext, modrm_byte: ModrmByte) { + gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| gen_safe_read16(ctx, addr)); +} +pub fn gen_modrm_resolve_safe_read32(ctx: &mut JitContext, modrm_byte: ModrmByte) { + gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| gen_safe_read32(ctx, addr)); +} +pub fn gen_modrm_resolve_safe_read64(ctx: &mut JitContext, modrm_byte: ModrmByte) { + gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| gen_safe_read64(ctx, addr)); +} +pub fn gen_modrm_resolve_safe_read128( + ctx: &mut JitContext, + modrm_byte: ModrmByte, + where_to_write: u32, +) { + gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + gen_safe_read128(ctx, addr, where_to_write) + }); +} + +pub fn gen_safe_read8(ctx: &mut JitContext, address_local: &WasmLocal) { + gen_safe_read(ctx, BitSize::BYTE, address_local, None); +} +pub fn gen_safe_read16(ctx: &mut JitContext, address_local: &WasmLocal) { + gen_safe_read(ctx, BitSize::WORD, address_local, None); +} +pub fn gen_safe_read32(ctx: &mut JitContext, address_local: &WasmLocal) { + gen_safe_read(ctx, BitSize::DWORD, address_local, None); +} +pub fn gen_safe_read64(ctx: &mut JitContext, address_local: &WasmLocal) { + gen_safe_read(ctx, BitSize::QWORD, &address_local, None); +} +pub fn gen_safe_read128(ctx: &mut JitContext, address_local: &WasmLocal, where_to_write: u32) { + gen_safe_read(ctx, BitSize::DQWORD, &address_local, Some(where_to_write)); +} + +// only used internally for gen_safe_write +enum GenSafeWriteValue<'a> { + I32(&'a WasmLocal), + I64(&'a WasmLocalI64), + TwoI64s(&'a WasmLocalI64, &'a WasmLocalI64), +} + +enum GenSafeReadWriteValue { + I32(WasmLocal), + I64(WasmLocalI64), +} + +#[derive(Copy, Clone, Eq, PartialEq)] +pub enum BitSize { + BYTE, + WORD, + DWORD, + QWORD, + DQWORD, +} +impl BitSize { + pub fn bytes(&self) -> u32 { + match self { + BitSize::BYTE => 1, + BitSize::WORD => 2, + BitSize::DWORD => 4, + BitSize::QWORD => 8, + BitSize::DQWORD => 16, + } + } +} + +pub fn gen_safe_write8(ctx: &mut JitContext, address_local: &WasmLocal, value_local: &WasmLocal) { + gen_safe_write( + ctx, + BitSize::BYTE, + address_local, + GenSafeWriteValue::I32(value_local), + ) +} +pub fn gen_safe_write16(ctx: &mut JitContext, address_local: &WasmLocal, value_local: &WasmLocal) { + gen_safe_write( + ctx, + BitSize::WORD, + address_local, + GenSafeWriteValue::I32(value_local), + ) +} +pub fn gen_safe_write32(ctx: &mut JitContext, address_local: &WasmLocal, value_local: &WasmLocal) { + gen_safe_write( + ctx, + BitSize::DWORD, + address_local, + GenSafeWriteValue::I32(value_local), + ) +} +pub fn gen_safe_write64( + ctx: &mut JitContext, + address_local: &WasmLocal, + value_local: &WasmLocalI64, +) { + gen_safe_write( + ctx, + BitSize::QWORD, + address_local, + GenSafeWriteValue::I64(value_local), + ) +} + +pub fn gen_safe_write128( + ctx: &mut JitContext, + address_local: &WasmLocal, + value_local_low: &WasmLocalI64, + value_local_high: &WasmLocalI64, +) { + gen_safe_write( + ctx, + BitSize::DQWORD, + address_local, + GenSafeWriteValue::TwoI64s(value_local_low, value_local_high), + ) +} + +fn gen_safe_read( + ctx: &mut JitContext, + bits: BitSize, + address_local: &WasmLocal, + where_to_write: Option, +) { + // Execute a virtual memory read. All slow paths (memory-mapped IO, tlb miss, page fault and + // read across page boundary are handled in safe_read_jit_slow + + // entry <- tlb_data[addr >> 12 << 2] + // if entry & MASK == TLB_VALID && (addr & 0xFFF) <= 0x1000 - bytes: goto fast + // entry <- safe_read_jit_slow(addr, instruction_pointer) + // if page_fault: goto exit-with-pagefault + // fast: mem[(entry & ~0xFFF) ^ addr] + + let cont = ctx.builder.block_void(); + ctx.builder.get_local(&address_local); + + ctx.builder.const_i32(12); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(2); + ctx.builder.shl_i32(); + + ctx.builder + .load_aligned_i32(unsafe { &tlb_data[0] as *const i32 as u32 }); + let entry_local = ctx.builder.tee_new_local(); + + ctx.builder.const_i32( + (0xFFF + & !TLB_READONLY + & !TLB_GLOBAL + & !TLB_HAS_CODE + & !(if ctx.cpu.cpl3() { 0 } else { TLB_NO_USER })) as i32, + ); + ctx.builder.and_i32(); + + ctx.builder.const_i32(TLB_VALID as i32); + ctx.builder.eq_i32(); + + if bits != BitSize::BYTE { + ctx.builder.get_local(&address_local); + ctx.builder.const_i32(0xFFF); + ctx.builder.and_i32(); + ctx.builder.const_i32(0x1000 - bits.bytes() as i32); + ctx.builder.le_i32(); + + ctx.builder.and_i32(); + } + + ctx.builder.br_if(cont); + + if cfg!(feature = "profiler") { + ctx.builder.get_local(&address_local); + ctx.builder.get_local(&entry_local); + ctx.builder.call_fn2("report_safe_read_jit_slow"); + } + + ctx.builder.get_local(&address_local); + ctx.builder + .const_i32(ctx.start_of_current_instruction as i32 & 0xFFF); + match bits { + BitSize::BYTE => { + ctx.builder.call_fn2_ret("safe_read8_slow_jit"); + }, + BitSize::WORD => { + ctx.builder.call_fn2_ret("safe_read16_slow_jit"); + }, + BitSize::DWORD => { + ctx.builder.call_fn2_ret("safe_read32s_slow_jit"); + }, + BitSize::QWORD => { + ctx.builder.call_fn2_ret("safe_read64s_slow_jit"); + }, + BitSize::DQWORD => { + ctx.builder.call_fn2_ret("safe_read128s_slow_jit"); + }, + } + ctx.builder.tee_local(&entry_local); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + + if cfg!(feature = "profiler") { + ctx.builder.if_void(); + gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.block_end(); + + ctx.builder.get_local(&entry_local); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + } + + ctx.builder.br_if(ctx.exit_with_fault_label); + + ctx.builder.block_end(); + + gen_profiler_stat_increment(ctx.builder, profiler::stat::SAFE_READ_FAST); // XXX: Both fast and slow + + ctx.builder.get_local(&entry_local); + ctx.builder.const_i32(!0xFFF); + ctx.builder.and_i32(); + ctx.builder.get_local(&address_local); + ctx.builder.xor_i32(); + + // where_to_write is only used by dqword + dbg_assert!((where_to_write != None) == (bits == BitSize::DQWORD)); + + match bits { + BitSize::BYTE => { + ctx.builder.load_u8(0); + }, + BitSize::WORD => { + ctx.builder.load_unaligned_u16(0); + }, + BitSize::DWORD => { + ctx.builder.load_unaligned_i32(0); + }, + BitSize::QWORD => { + ctx.builder.load_unaligned_i64(0); + }, + BitSize::DQWORD => { + let where_to_write = where_to_write.unwrap(); + let virt_address_local = ctx.builder.set_new_local(); + ctx.builder.const_i32(0); + ctx.builder.get_local(&virt_address_local); + ctx.builder.load_unaligned_i64(0); + ctx.builder.store_unaligned_i64(where_to_write); + + ctx.builder.const_i32(0); + ctx.builder.get_local(&virt_address_local); + ctx.builder.load_unaligned_i64(8); + ctx.builder.store_unaligned_i64(where_to_write + 8); + + ctx.builder.free_local(virt_address_local); + }, + } + + ctx.builder.free_local(entry_local); +} + +pub fn gen_get_phys_eip_plus_mem(ctx: &mut JitContext, address_local: &WasmLocal) { + // Similar to gen_safe_read, but return the physical eip + memory::mem rather than reading from memory + // In functions that need to use this value we need to fix it by substracting memory::mem + // this is done in order to remove one instruction from the fast path of memory accesses (no need to add + // memory::mem anymore ). + // We need to account for this in gen_page_switch_check and we compare with next_block_addr + memory::mem8 + // We cannot the same while processing an AbsoluteEip flow control change so there we need to fix the value + // by subscracting memory::mem. Overall, since AbsoluteEip is encountered less often than memory accesses so + // this ends up improving perf. + // Does not (need to) handle mapped memory + // XXX: Currently does not use ctx.start_of_current_instruction, but rather assumes that eip is + // already correct (pointing at the current instruction) + + let cont = ctx.builder.block_void(); + ctx.builder.get_local(&address_local); + + ctx.builder.const_i32(12); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(2); + ctx.builder.shl_i32(); + + ctx.builder + .load_aligned_i32(unsafe { &tlb_data[0] as *const i32 as u32 }); + let entry_local = ctx.builder.tee_new_local(); + + ctx.builder.const_i32( + (0xFFF + & !TLB_READONLY + & !TLB_GLOBAL + & !TLB_HAS_CODE + & !(if ctx.cpu.cpl3() { 0 } else { TLB_NO_USER })) as i32, + ); + ctx.builder.and_i32(); + + ctx.builder.const_i32(TLB_VALID as i32); + ctx.builder.eq_i32(); + + ctx.builder.br_if(cont); + + if cfg!(feature = "profiler") { + ctx.builder.get_local(&address_local); + ctx.builder.get_local(&entry_local); + ctx.builder.call_fn2("report_safe_read_jit_slow"); + } + + ctx.builder.get_local(&address_local); + ctx.builder.call_fn1_ret("get_phys_eip_slow_jit"); + + ctx.builder.tee_local(&entry_local); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + + if cfg!(feature = "profiler") { + ctx.builder.if_void(); + gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); // XXX + ctx.builder.block_end(); + + ctx.builder.get_local(&entry_local); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + } + + ctx.builder.br_if(ctx.exit_with_fault_label); + + ctx.builder.block_end(); + + gen_profiler_stat_increment(ctx.builder, profiler::stat::SAFE_READ_FAST); // XXX: Both fast and slow + + ctx.builder.get_local(&entry_local); + ctx.builder.const_i32(!0xFFF); + ctx.builder.and_i32(); + ctx.builder.get_local(&address_local); + ctx.builder.xor_i32(); + + ctx.builder.free_local(entry_local); +} + +fn gen_safe_write( + ctx: &mut JitContext, + bits: BitSize, + address_local: &WasmLocal, + value_local: GenSafeWriteValue, +) { + // Execute a virtual memory write. All slow paths (memory-mapped IO, tlb miss, page fault, + // write across page boundary and page containing jitted code are handled in safe_write_jit_slow + + // entry <- tlb_data[addr >> 12 << 2] + // if entry & MASK == TLB_VALID && (addr & 0xFFF) <= 0x1000 - bytes: goto fast + // entry <- safe_write_jit_slow(addr, value, instruction_pointer) + // if page_fault: goto exit-with-pagefault + // fast: mem[(entry & ~0xFFF) ^ addr] <- value + + let cont = ctx.builder.block_void(); + ctx.builder.get_local(&address_local); + + ctx.builder.const_i32(12); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(2); + ctx.builder.shl_i32(); + + ctx.builder + .load_aligned_i32(unsafe { &tlb_data[0] as *const i32 as u32 }); + let entry_local = ctx.builder.tee_new_local(); + + ctx.builder + .const_i32((0xFFF & !TLB_GLOBAL & !(if ctx.cpu.cpl3() { 0 } else { TLB_NO_USER })) as i32); + ctx.builder.and_i32(); + + ctx.builder.const_i32(TLB_VALID as i32); + ctx.builder.eq_i32(); + + if bits != BitSize::BYTE { + ctx.builder.get_local(&address_local); + ctx.builder.const_i32(0xFFF); + ctx.builder.and_i32(); + ctx.builder.const_i32(0x1000 - bits.bytes() as i32); + ctx.builder.le_i32(); + + ctx.builder.and_i32(); + } + + ctx.builder.br_if(cont); + + if cfg!(feature = "profiler") { + ctx.builder.get_local(&address_local); + ctx.builder.get_local(&entry_local); + ctx.builder.call_fn2("report_safe_write_jit_slow"); + } + + ctx.builder.get_local(&address_local); + match value_local { + GenSafeWriteValue::I32(local) => ctx.builder.get_local(local), + GenSafeWriteValue::I64(local) => ctx.builder.get_local_i64(local), + GenSafeWriteValue::TwoI64s(local1, local2) => { + ctx.builder.get_local_i64(local1); + ctx.builder.get_local_i64(local2) + }, + } + ctx.builder + .const_i32(ctx.start_of_current_instruction as i32 & 0xFFF); + match bits { + BitSize::BYTE => { + ctx.builder.call_fn3_ret("safe_write8_slow_jit"); + }, + BitSize::WORD => { + ctx.builder.call_fn3_ret("safe_write16_slow_jit"); + }, + BitSize::DWORD => { + ctx.builder.call_fn3_ret("safe_write32_slow_jit"); + }, + BitSize::QWORD => { + ctx.builder + .call_fn3_i32_i64_i32_ret("safe_write64_slow_jit"); + }, + BitSize::DQWORD => { + ctx.builder + .call_fn4_i32_i64_i64_i32_ret("safe_write128_slow_jit"); + }, + } + ctx.builder.tee_local(&entry_local); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + + if cfg!(feature = "profiler") { + ctx.builder.if_void(); + gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.block_end(); + + ctx.builder.get_local(&entry_local); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + } + + ctx.builder.br_if(ctx.exit_with_fault_label); + + ctx.builder.block_end(); + + gen_profiler_stat_increment(ctx.builder, profiler::stat::SAFE_WRITE_FAST); // XXX: Both fast and slow + + ctx.builder.get_local(&entry_local); + ctx.builder.const_i32(!0xFFF); + ctx.builder.and_i32(); + ctx.builder.get_local(&address_local); + ctx.builder.xor_i32(); + + match value_local { + GenSafeWriteValue::I32(local) => ctx.builder.get_local(local), + GenSafeWriteValue::I64(local) => ctx.builder.get_local_i64(local), + GenSafeWriteValue::TwoI64s(local1, local2) => { + assert!(bits == BitSize::DQWORD); + + let virt_address_local = ctx.builder.tee_new_local(); + ctx.builder.get_local_i64(local1); + ctx.builder.store_unaligned_i64(0); + + ctx.builder.get_local(&virt_address_local); + ctx.builder.get_local_i64(local2); + ctx.builder.store_unaligned_i64(8); + ctx.builder.free_local(virt_address_local); + }, + } + match bits { + BitSize::BYTE => { + ctx.builder.store_u8(0); + }, + BitSize::WORD => { + ctx.builder.store_unaligned_u16(0); + }, + BitSize::DWORD => { + ctx.builder.store_unaligned_i32(0); + }, + BitSize::QWORD => { + ctx.builder.store_unaligned_i64(0); + }, + BitSize::DQWORD => {}, // handled above + } + + ctx.builder.free_local(entry_local); +} + +pub fn gen_safe_read_write( + ctx: &mut JitContext, + bits: BitSize, + address_local: &WasmLocal, + f: &dyn Fn(&mut JitContext), +) { + // Execute a virtual memory read+write. All slow paths (memory-mapped IO, tlb miss, page fault, + // write across page boundary and page containing jitted code are handled in + // safe_read_write_jit_slow + + // entry <- tlb_data[addr >> 12 << 2] + // can_use_fast_path <- entry & MASK == TLB_VALID && (addr & 0xFFF) <= 0x1000 - bytes + // if can_use_fast_path: goto fast + // entry <- safe_read_write_jit_slow(addr, instruction_pointer) + // if page_fault: goto exit-with-pagefault + // fast: value <- f(mem[(entry & ~0xFFF) ^ addr]) + // if !can_use_fast_path { safe_write_jit_slow(addr, value, instruction_pointer) } + // mem[(entry & ~0xFFF) ^ addr] <- value + + let cont = ctx.builder.block_void(); + ctx.builder.get_local(address_local); + + ctx.builder.const_i32(12); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(2); + ctx.builder.shl_i32(); + + ctx.builder + .load_aligned_i32(unsafe { &tlb_data[0] as *const i32 as u32 }); + let entry_local = ctx.builder.tee_new_local(); + + ctx.builder + .const_i32((0xFFF & !TLB_GLOBAL & !(if ctx.cpu.cpl3() { 0 } else { TLB_NO_USER })) as i32); + ctx.builder.and_i32(); + + ctx.builder.const_i32(TLB_VALID as i32); + ctx.builder.eq_i32(); + + if bits != BitSize::BYTE { + ctx.builder.get_local(&address_local); + ctx.builder.const_i32(0xFFF); + ctx.builder.and_i32(); + ctx.builder.const_i32(0x1000 - bits.bytes() as i32); + ctx.builder.le_i32(); + ctx.builder.and_i32(); + } + + let can_use_fast_path_local = ctx.builder.tee_new_local(); + + ctx.builder.br_if(cont); + + if cfg!(feature = "profiler") { + ctx.builder.get_local(&address_local); + ctx.builder.get_local(&entry_local); + ctx.builder.call_fn2("report_safe_read_write_jit_slow"); + } + + ctx.builder.get_local(&address_local); + ctx.builder + .const_i32(ctx.start_of_current_instruction as i32 & 0xFFF); + + match bits { + BitSize::BYTE => { + ctx.builder.call_fn2_ret("safe_read_write8_slow_jit"); + }, + BitSize::WORD => { + ctx.builder.call_fn2_ret("safe_read_write16_slow_jit"); + }, + BitSize::DWORD => { + ctx.builder.call_fn2_ret("safe_read_write32s_slow_jit"); + }, + BitSize::QWORD => { + ctx.builder.call_fn2_ret("safe_read_write64_slow_jit"); + }, + BitSize::DQWORD => { + dbg_assert!(false); + }, + } + ctx.builder.tee_local(&entry_local); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + + if cfg!(feature = "profiler") { + ctx.builder.if_void(); + gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.block_end(); + + ctx.builder.get_local(&entry_local); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + } + + ctx.builder.br_if(ctx.exit_with_fault_label); + + ctx.builder.block_end(); + + gen_profiler_stat_increment(ctx.builder, profiler::stat::SAFE_READ_WRITE_FAST); // XXX: Also slow + + ctx.builder.get_local(&entry_local); + ctx.builder.const_i32(!0xFFF); + ctx.builder.and_i32(); + ctx.builder.get_local(&address_local); + ctx.builder.xor_i32(); + + ctx.builder.free_local(entry_local); + let phys_addr_local = ctx.builder.tee_new_local(); + + match bits { + BitSize::BYTE => { + ctx.builder.load_u8(0); + }, + BitSize::WORD => { + ctx.builder.load_unaligned_u16(0); + }, + BitSize::DWORD => { + ctx.builder.load_unaligned_i32(0); + }, + BitSize::QWORD => { + ctx.builder.load_unaligned_i64(0); + }, + BitSize::DQWORD => assert!(false), // not used + } + + // value is now on stack + + f(ctx); + + // TODO: Could get rid of this local by returning one from f + let value_local = if bits == BitSize::QWORD { + GenSafeReadWriteValue::I64(ctx.builder.set_new_local_i64()) + } + else { + GenSafeReadWriteValue::I32(ctx.builder.set_new_local()) + }; + + ctx.builder.get_local(&can_use_fast_path_local); + + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + { + ctx.builder.get_local(&address_local); + + match &value_local { + GenSafeReadWriteValue::I32(l) => ctx.builder.get_local(l), + GenSafeReadWriteValue::I64(l) => ctx.builder.get_local_i64(l), + } + + ctx.builder + .const_i32(ctx.start_of_current_instruction as i32); + + match bits { + BitSize::BYTE => { + ctx.builder.call_fn3_ret("safe_write8_slow_jit"); + }, + BitSize::WORD => { + ctx.builder.call_fn3_ret("safe_write16_slow_jit"); + }, + BitSize::DWORD => { + ctx.builder.call_fn3_ret("safe_write32_slow_jit"); + }, + BitSize::QWORD => { + ctx.builder + .call_fn3_i32_i64_i32_ret("safe_write64_slow_jit"); + }, + BitSize::DQWORD => { + dbg_assert!(false); + }, + } + + if cfg!(debug_assertions) { + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + + ctx.builder.if_void(); + { + // handled above + ctx.builder.const_i32(match bits { + BitSize::BYTE => 8, + BitSize::WORD => 16, + BitSize::DWORD => 32, + BitSize::QWORD => 64, + _ => { + dbg_assert!(false); + 0 + }, + }); + ctx.builder.get_local(&address_local); + ctx.builder.call_fn2("bug_gen_safe_read_write_page_fault"); + } + ctx.builder.block_end(); + } + else { + ctx.builder.drop_(); + } + } + ctx.builder.block_end(); + + ctx.builder.get_local(&phys_addr_local); + match &value_local { + GenSafeReadWriteValue::I32(l) => ctx.builder.get_local(l), + GenSafeReadWriteValue::I64(l) => ctx.builder.get_local_i64(l), + } + + match bits { + BitSize::BYTE => { + ctx.builder.store_u8(0); + }, + BitSize::WORD => { + ctx.builder.store_unaligned_u16(0); + }, + BitSize::DWORD => { + ctx.builder.store_unaligned_i32(0); + }, + BitSize::QWORD => { + ctx.builder.store_unaligned_i64(0); + }, + BitSize::DQWORD => { + dbg_assert!(false); + }, + } + + match value_local { + GenSafeReadWriteValue::I32(l) => ctx.builder.free_local(l), + GenSafeReadWriteValue::I64(l) => ctx.builder.free_local_i64(l), + } + ctx.builder.free_local(can_use_fast_path_local); + ctx.builder.free_local(phys_addr_local); +} + +#[cfg(debug_assertions)] +#[no_mangle] +pub fn bug_gen_safe_read_write_page_fault(bits: i32, addr: u32) { + dbg_log!("bug: gen_safe_read_write_page_fault {} {:x}", bits, addr); + dbg_assert!(false); +} + +pub fn gen_jmp_rel16(builder: &mut WasmBuilder, rel16: u16) { + let cs_offset_addr = global_pointers::get_seg_offset(regs::CS); + builder.load_fixed_i32(cs_offset_addr); + let local = builder.set_new_local(); + + // generate: + // *instruction_pointer = cs_offset + ((*instruction_pointer - cs_offset + rel16) & 0xFFFF); + { + builder.const_i32(global_pointers::instruction_pointer as i32); + + gen_get_eip(builder); + builder.get_local(&local); + builder.sub_i32(); + + builder.const_i32(rel16 as i32); + builder.add_i32(); + + builder.const_i32(0xFFFF); + builder.and_i32(); + + builder.get_local(&local); + builder.add_i32(); + + builder.store_aligned_i32(0); + } + builder.free_local(local); +} + +pub fn gen_pop16_ss16(ctx: &mut JitContext) { + // sp = segment_offsets[SS] + reg16[SP] (or just reg16[SP] if has_flat_segmentation) + gen_get_reg16(ctx, regs::SP); + + if !ctx.cpu.has_flat_segmentation() { + gen_get_ss_offset(ctx); + ctx.builder.add_i32(); + } + + // result = safe_read16(sp) + let address_local = ctx.builder.set_new_local(); + gen_safe_read16(ctx, &address_local); + ctx.builder.free_local(address_local); + + // reg16[SP] += 2; + gen_get_reg16(ctx, regs::SP); + ctx.builder.const_i32(2); + ctx.builder.add_i32(); + gen_set_reg16(ctx, regs::SP); + + // return value is already on stack +} + +pub fn gen_pop16_ss32(ctx: &mut JitContext) { + // esp = segment_offsets[SS] + reg32[ESP] (or just reg32[ESP] if has_flat_segmentation) + gen_get_reg32(ctx, regs::ESP); + + if !ctx.cpu.has_flat_segmentation() { + gen_get_ss_offset(ctx); + ctx.builder.add_i32(); + } + + // result = safe_read16(esp) + let address_local = ctx.builder.set_new_local(); + gen_safe_read16(ctx, &address_local); + ctx.builder.free_local(address_local); + + // reg32[ESP] += 2; + gen_get_reg32(ctx, regs::ESP); + ctx.builder.const_i32(2); + ctx.builder.add_i32(); + gen_set_reg32(ctx, regs::ESP); + + // return value is already on stack +} + +pub fn gen_pop16(ctx: &mut JitContext) { + if ctx.cpu.ssize_32() { + gen_pop16_ss32(ctx); + } + else { + gen_pop16_ss16(ctx); + } +} + +pub fn gen_pop32s_ss16(ctx: &mut JitContext) { + // sp = reg16[SP] + gen_get_reg16(ctx, regs::SP); + + // result = safe_read32s(segment_offsets[SS] + sp) (or just sp if has_flat_segmentation) + if !ctx.cpu.has_flat_segmentation() { + gen_get_ss_offset(ctx); + ctx.builder.add_i32(); + } + + let address_local = ctx.builder.set_new_local(); + gen_safe_read32(ctx, &address_local); + ctx.builder.free_local(address_local); + + // reg16[SP] = sp + 4; + gen_get_reg16(ctx, regs::SP); + ctx.builder.const_i32(4); + ctx.builder.add_i32(); + gen_set_reg16(ctx, regs::SP); + + // return value is already on stack +} + +pub fn gen_pop32s_ss32(ctx: &mut JitContext) { + if !ctx.cpu.has_flat_segmentation() { + gen_get_reg32(ctx, regs::ESP); + gen_get_ss_offset(ctx); + ctx.builder.add_i32(); + let address_local = ctx.builder.set_new_local(); + gen_safe_read32(ctx, &address_local); + ctx.builder.free_local(address_local); + } + else { + let reg = ctx.register_locals[regs::ESP as usize].unsafe_clone(); + gen_safe_read32(ctx, ®); + } + + gen_get_reg32(ctx, regs::ESP); + ctx.builder.const_i32(4); + ctx.builder.add_i32(); + gen_set_reg32(ctx, regs::ESP); + + // return value is already on stack +} + +pub fn gen_pop32s(ctx: &mut JitContext) { + if ctx.cpu.ssize_32() { + gen_pop32s_ss32(ctx); + } + else { + gen_pop32s_ss16(ctx); + } +} + +pub fn gen_adjust_stack_reg(ctx: &mut JitContext, offset: u32) { + if ctx.cpu.ssize_32() { + gen_get_reg32(ctx, regs::ESP); + ctx.builder.const_i32(offset as i32); + ctx.builder.add_i32(); + gen_set_reg32(ctx, regs::ESP); + } + else { + gen_get_reg16(ctx, regs::SP); + ctx.builder.const_i32(offset as i32); + ctx.builder.add_i32(); + gen_set_reg16(ctx, regs::SP); + } +} + +pub fn gen_leave(ctx: &mut JitContext, os32: bool) { + // [e]bp = safe_read{16,32}([e]bp) + + if ctx.cpu.ssize_32() { + gen_get_reg32(ctx, regs::EBP); + } + else { + gen_get_reg16(ctx, regs::BP); + } + + let old_vbp = ctx.builder.tee_new_local(); + + if !ctx.cpu.has_flat_segmentation() { + gen_get_ss_offset(ctx); + ctx.builder.add_i32(); + } + if os32 { + let address_local = ctx.builder.set_new_local(); + gen_safe_read32(ctx, &address_local); + ctx.builder.free_local(address_local); + gen_set_reg32(ctx, regs::EBP); + } + else { + let address_local = ctx.builder.set_new_local(); + gen_safe_read16(ctx, &address_local); + ctx.builder.free_local(address_local); + gen_set_reg16(ctx, regs::BP); + } + + // [e]sp = [e]bp + (os32 ? 4 : 2) + + if ctx.cpu.ssize_32() { + ctx.builder.get_local(&old_vbp); + ctx.builder.const_i32(if os32 { 4 } else { 2 }); + ctx.builder.add_i32(); + gen_set_reg32(ctx, regs::ESP); + } + else { + ctx.builder.get_local(&old_vbp); + ctx.builder.const_i32(if os32 { 4 } else { 2 }); + ctx.builder.add_i32(); + gen_set_reg16(ctx, regs::SP); + } + + ctx.builder.free_local(old_vbp); +} + +pub fn gen_task_switch_test(ctx: &mut JitContext) { + // generate if(cr[0] & (CR0_EM | CR0_TS)) { task_switch_test_jit(); goto exit_with_fault; } + let cr0_offset = global_pointers::get_creg_offset(0); + + dbg_assert!(regs::CR0_EM | regs::CR0_TS <= 0xFF); + ctx.builder.load_fixed_u8(cr0_offset); + ctx.builder.const_i32((regs::CR0_EM | regs::CR0_TS) as i32); + ctx.builder.and_i32(); + + ctx.builder.if_void(); + { + gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + gen_fn1_const( + ctx.builder, + "task_switch_test_jit", + ctx.start_of_current_instruction, + ); + ctx.builder.br(ctx.exit_with_fault_label); + } + ctx.builder.block_end(); +} + +pub fn gen_task_switch_test_mmx(ctx: &mut JitContext) { + // generate if(cr[0] & (CR0_EM | CR0_TS)) { task_switch_test_mmx_jit(); goto exit_with_fault; } + let cr0_offset = global_pointers::get_creg_offset(0); + + dbg_assert!(regs::CR0_EM | regs::CR0_TS <= 0xFF); + ctx.builder.load_fixed_u8(cr0_offset); + ctx.builder.const_i32((regs::CR0_EM | regs::CR0_TS) as i32); + ctx.builder.and_i32(); + + ctx.builder.if_void(); + { + gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + gen_fn1_const( + ctx.builder, + "task_switch_test_mmx_jit", + ctx.start_of_current_instruction, + ); + ctx.builder.br(ctx.exit_with_fault_label); + } + ctx.builder.block_end(); +} + +pub fn gen_push16(ctx: &mut JitContext, value_local: &WasmLocal) { + if ctx.cpu.ssize_32() { + gen_get_reg32(ctx, regs::ESP); + } + else { + gen_get_reg16(ctx, regs::SP); + }; + + ctx.builder.const_i32(2); + ctx.builder.sub_i32(); + + let reg_updated_local = if !ctx.cpu.ssize_32() || !ctx.cpu.has_flat_segmentation() { + let reg_updated_local = ctx.builder.tee_new_local(); + if !ctx.cpu.ssize_32() { + ctx.builder.const_i32(0xFFFF); + ctx.builder.and_i32(); + } + + if !ctx.cpu.has_flat_segmentation() { + gen_get_ss_offset(ctx); + ctx.builder.add_i32(); + } + + let sp_local = ctx.builder.set_new_local(); + gen_safe_write16(ctx, &sp_local, &value_local); + ctx.builder.free_local(sp_local); + + ctx.builder.get_local(®_updated_local); + reg_updated_local + } + else { + // short path: The address written to is equal to ESP/SP minus two + let reg_updated_local = ctx.builder.tee_new_local(); + gen_safe_write16(ctx, ®_updated_local, &value_local); + reg_updated_local + }; + + if ctx.cpu.ssize_32() { + gen_set_reg32(ctx, regs::ESP); + } + else { + gen_set_reg16(ctx, regs::SP); + }; + ctx.builder.free_local(reg_updated_local); +} + +pub fn gen_push32(ctx: &mut JitContext, value_local: &WasmLocal) { + if ctx.cpu.ssize_32() { + gen_get_reg32(ctx, regs::ESP); + } + else { + gen_get_reg16(ctx, regs::SP); + }; + + ctx.builder.const_i32(4); + ctx.builder.sub_i32(); + + let new_sp_local = if !ctx.cpu.ssize_32() || !ctx.cpu.has_flat_segmentation() { + let new_sp_local = ctx.builder.tee_new_local(); + if !ctx.cpu.ssize_32() { + ctx.builder.const_i32(0xFFFF); + ctx.builder.and_i32(); + } + + if !ctx.cpu.has_flat_segmentation() { + gen_get_ss_offset(ctx); + ctx.builder.add_i32(); + } + + let sp_local = ctx.builder.set_new_local(); + + gen_safe_write32(ctx, &sp_local, &value_local); + ctx.builder.free_local(sp_local); + + ctx.builder.get_local(&new_sp_local); + new_sp_local + } + else { + // short path: The address written to is equal to ESP/SP minus four + let new_sp_local = ctx.builder.tee_new_local(); + gen_safe_write32(ctx, &new_sp_local, &value_local); + new_sp_local + }; + + if ctx.cpu.ssize_32() { + gen_set_reg32(ctx, regs::ESP); + } + else { + gen_set_reg16(ctx, regs::SP); + }; + ctx.builder.free_local(new_sp_local); +} + +pub fn gen_push32_sreg(ctx: &mut JitContext, reg: u32) { + gen_get_sreg(ctx, reg); + let value_local = ctx.builder.set_new_local(); + + if ctx.cpu.ssize_32() { + gen_get_reg32(ctx, regs::ESP); + } + else { + gen_get_reg16(ctx, regs::SP); + }; + + ctx.builder.const_i32(4); + ctx.builder.sub_i32(); + + let new_sp_local = if !ctx.cpu.ssize_32() || !ctx.cpu.has_flat_segmentation() { + let new_sp_local = ctx.builder.tee_new_local(); + if !ctx.cpu.ssize_32() { + ctx.builder.const_i32(0xFFFF); + ctx.builder.and_i32(); + } + + if !ctx.cpu.has_flat_segmentation() { + gen_get_ss_offset(ctx); + ctx.builder.add_i32(); + } + + let sp_local = ctx.builder.set_new_local(); + + gen_safe_write16(ctx, &sp_local, &value_local); + ctx.builder.free_local(sp_local); + + ctx.builder.get_local(&new_sp_local); + new_sp_local + } + else { + // short path: The address written to is equal to ESP/SP minus four + let new_sp_local = ctx.builder.tee_new_local(); + gen_safe_write16(ctx, &new_sp_local, &value_local); + new_sp_local + }; + + if ctx.cpu.ssize_32() { + gen_set_reg32(ctx, regs::ESP); + } + else { + gen_set_reg16(ctx, regs::SP); + }; + ctx.builder.free_local(new_sp_local); + ctx.builder.free_local(value_local); +} + +pub fn gen_get_real_eip(ctx: &mut JitContext) { + gen_get_eip(ctx.builder); + ctx.builder.const_i32(!0xFFF); + ctx.builder.and_i32(); + ctx.builder.const_i32(ctx.cpu.eip as i32 & 0xFFF); + ctx.builder.or_i32(); + if !ctx.cpu.has_flat_segmentation() { + ctx.builder + .load_fixed_i32(global_pointers::get_seg_offset(regs::CS)); + ctx.builder.sub_i32(); + } +} + +pub fn gen_set_last_op1(builder: &mut WasmBuilder, source: &WasmLocal) { + builder.const_i32(global_pointers::last_op1 as i32); + builder.get_local(&source); + builder.store_aligned_i32(0); +} + +pub fn gen_set_last_result(builder: &mut WasmBuilder, source: &WasmLocal) { + builder.const_i32(global_pointers::last_result as i32); + builder.get_local(&source); + builder.store_aligned_i32(0); +} + +pub fn gen_clear_flags_changed_bits(builder: &mut WasmBuilder, bits_to_clear: i32) { + builder.const_i32(global_pointers::flags_changed as i32); + gen_get_flags_changed(builder); + builder.const_i32(!bits_to_clear); + builder.and_i32(); + builder.store_aligned_i32(0); +} + +pub fn gen_set_last_op_size_and_flags_changed( + builder: &mut WasmBuilder, + last_op_size: i32, + flags_changed: i32, +) { + dbg_assert!(last_op_size == OPSIZE_8 || last_op_size == OPSIZE_16 || last_op_size == OPSIZE_32); + dbg_assert!(global_pointers::last_op_size as i32 % 8 == 0); + dbg_assert!(global_pointers::last_op_size as i32 + 4 == global_pointers::flags_changed as i32); + builder.const_i32(global_pointers::last_op_size as i32); + builder.const_i64(last_op_size as u32 as i64 | (flags_changed as u32 as i64) << 32); + builder.store_aligned_i64(0); +} + +pub fn gen_set_flags_bits(builder: &mut WasmBuilder, bits_to_set: i32) { + builder.const_i32(global_pointers::flags as i32); + gen_get_flags(builder); + builder.const_i32(bits_to_set); + builder.or_i32(); + builder.store_aligned_i32(0); +} + +pub fn gen_clear_flags_bits(builder: &mut WasmBuilder, bits_to_clear: i32) { + builder.const_i32(global_pointers::flags as i32); + gen_get_flags(builder); + builder.const_i32(!bits_to_clear); + builder.and_i32(); + builder.store_aligned_i32(0); +} + +#[derive(PartialEq)] +pub enum ConditionNegate { + True, + False, +} + +pub fn gen_getzf(ctx: &mut JitContext, negate: ConditionNegate) { + match &ctx.previous_instruction { + Instruction::Cmp { + dest: InstructionOperandDest::WasmLocal(dest), + source: InstructionOperand::WasmLocal(source), + opsize: OPSIZE_32, + } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + ctx.builder.get_local(dest); + ctx.builder.get_local(source); + if negate == ConditionNegate::False { + ctx.builder.eq_i32(); + } + else { + ctx.builder.ne_i32(); + } + }, + Instruction::Cmp { + dest: InstructionOperandDest::WasmLocal(dest), + source: InstructionOperand::Immediate(i), + opsize: OPSIZE_32, + } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + ctx.builder.get_local(dest); + if *i != 0 { + ctx.builder.const_i32(*i); + if negate == ConditionNegate::False { + ctx.builder.eq_i32(); + } + else { + ctx.builder.ne_i32(); + } + } + else { + if negate == ConditionNegate::False { + ctx.builder.eqz_i32(); + } + } + }, + Instruction::Cmp { .. } + | Instruction::Sub { .. } + | Instruction::Add { .. } + | Instruction::AdcSbb { .. } + | Instruction::NonZeroShift { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + if negate == ConditionNegate::False { + ctx.builder.eqz_i32(); + } + }, + Instruction::Bitwise { opsize, .. } => { + let &opsize = opsize; + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + // Note: Necessary because test{8,16} don't mask their neither last_result nor any of their operands + // TODO: Use local instead of last_result for 8-bit/16-bit + if opsize == OPSIZE_32 { + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + } + else if opsize == OPSIZE_16 { + ctx.builder + .load_fixed_u16(global_pointers::last_result as u32); + } + else if opsize == OPSIZE_8 { + ctx.builder + .load_fixed_u8(global_pointers::last_result as u32); + } + if negate == ConditionNegate::False { + ctx.builder.eqz_i32(); + } + }, + &Instruction::Other => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED); + gen_get_flags_changed(ctx.builder); + ctx.builder.const_i32(FLAG_ZERO); + ctx.builder.and_i32(); + ctx.builder.if_i32(); + + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + let last_result = ctx.builder.tee_new_local(); + ctx.builder.const_i32(-1); + ctx.builder.xor_i32(); + ctx.builder.get_local(&last_result); + ctx.builder.free_local(last_result); + ctx.builder.const_i32(1); + ctx.builder.sub_i32(); + ctx.builder.and_i32(); + gen_get_last_op_size(ctx.builder); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + + ctx.builder.else_(); + gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_ZERO); + ctx.builder.and_i32(); + ctx.builder.block_end(); + + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + } +} + +pub fn gen_getcf(ctx: &mut JitContext, negate: ConditionNegate) { + match &ctx.previous_instruction { + Instruction::Cmp { source, opsize, .. } + | Instruction::Sub { + source, + opsize, + is_dec: false, + .. + } => { + // Note: x < y and x < x - y can be used interchangeably (see getcf) + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + match (opsize, source) { + (&OPSIZE_32, InstructionOperand::WasmLocal(l)) => ctx.builder.get_local(l), + (_, &InstructionOperand::Immediate(i)) => ctx.builder.const_i32(i), + _ => gen_get_last_result(ctx.builder, &ctx.previous_instruction), + } + if negate == ConditionNegate::True { + ctx.builder.geu_i32(); + } + else { + ctx.builder.ltu_i32(); + } + }, + Instruction::Add { + source, + opsize, + is_inc: false, + .. + } => { + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + match (opsize, source) { + (&OPSIZE_32, InstructionOperand::WasmLocal(l)) => ctx.builder.get_local(l), + (_, &InstructionOperand::Immediate(i)) => ctx.builder.const_i32(i), + _ => gen_get_last_op1(ctx.builder, &ctx.previous_instruction), + } + if negate == ConditionNegate::True { + ctx.builder.geu_i32(); + } + else { + ctx.builder.ltu_i32(); + } + }, + Instruction::Add { is_inc: true, .. } | Instruction::Sub { is_dec: true, .. } => { + gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_CARRY); + ctx.builder.and_i32(); + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + Instruction::Bitwise { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + ctx.builder + .const_i32(if negate == ConditionNegate::True { 1 } else { 0 }); + }, + Instruction::NonZeroShift { .. } | Instruction::AdcSbb { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_CARRY); + ctx.builder.and_i32(); + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + &Instruction::Other => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED); + + gen_get_flags_changed(ctx.builder); + let flags_changed = ctx.builder.tee_new_local(); + ctx.builder.const_i32(FLAG_CARRY); + ctx.builder.and_i32(); + ctx.builder.if_i32(); + + ctx.builder.get_local(&flags_changed); + ctx.builder.const_i32(31); + ctx.builder.shr_s_i32(); + ctx.builder.free_local(flags_changed); + let sub_mask = ctx.builder.set_new_local(); + + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.get_local(&sub_mask); + ctx.builder.xor_i32(); + + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + ctx.builder.get_local(&sub_mask); + ctx.builder.xor_i32(); + + ctx.builder.ltu_i32(); + + ctx.builder.else_(); + gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_CARRY); + ctx.builder.and_i32(); + ctx.builder.block_end(); + + ctx.builder.free_local(sub_mask); + + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + } +} + +pub fn gen_getsf(ctx: &mut JitContext, negate: ConditionNegate) { + match &ctx.previous_instruction { + Instruction::Cmp { opsize, .. } + | Instruction::Sub { opsize, .. } + | Instruction::Add { opsize, .. } + | Instruction::AdcSbb { opsize, .. } + | Instruction::Bitwise { opsize, .. } + | Instruction::NonZeroShift { opsize, .. } => { + let &opsize = opsize; + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + if opsize == OPSIZE_32 { + ctx.builder.const_i32(0); + if negate == ConditionNegate::True { + ctx.builder.ge_i32(); + } + else { + ctx.builder.lt_i32(); + } + } + else { + // TODO: use register (see get_last_result) + ctx.builder + .const_i32(if opsize == OPSIZE_16 { 0x8000 } else { 0x80 }); + ctx.builder.and_i32(); + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + } + }, + &Instruction::Other => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED); + gen_get_flags_changed(ctx.builder); + ctx.builder.const_i32(FLAG_SIGN); + ctx.builder.and_i32(); + ctx.builder.if_i32(); + { + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + gen_get_last_op_size(ctx.builder); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + } + ctx.builder.else_(); + { + gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_SIGN); + ctx.builder.and_i32(); + } + ctx.builder.block_end(); + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + } +} + +pub fn gen_getof(ctx: &mut JitContext) { + match &ctx.previous_instruction { + Instruction::Cmp { opsize, .. } | Instruction::Sub { opsize, .. } => { + // TODO: a better formula might be possible + let &opsize = opsize; + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.xor_i32(); + + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.sub_i32(); + ctx.builder.xor_i32(); + ctx.builder.and_i32(); + + ctx.builder.const_i32(if opsize == OPSIZE_32 { + 0x8000_0000u32 as i32 + } + else if opsize == OPSIZE_16 { + 0x8000 + } + else { + 0x80 + }); + ctx.builder.and_i32(); + }, + Instruction::Add { opsize, .. } => { + // TODO: a better formula might be possible + let &opsize = opsize; + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.xor_i32(); + + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + ctx.builder.sub_i32(); + ctx.builder.xor_i32(); + ctx.builder.and_i32(); + + ctx.builder.const_i32(if opsize == OPSIZE_32 { + 0x8000_0000u32 as i32 + } + else if opsize == OPSIZE_16 { + 0x8000 + } + else { + 0x80 + }); + ctx.builder.and_i32(); + }, + Instruction::Bitwise { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + ctx.builder.const_i32(0); + }, + Instruction::NonZeroShift { .. } | Instruction::AdcSbb { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_OVERFLOW); + ctx.builder.and_i32(); + }, + &Instruction::Other => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED); + gen_get_flags_changed(ctx.builder); + let flags_changed = ctx.builder.tee_new_local(); + ctx.builder.const_i32(FLAG_OVERFLOW); + ctx.builder.and_i32(); + ctx.builder.if_i32(); + { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + let last_op1 = ctx.builder.tee_new_local(); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + let last_result = ctx.builder.tee_new_local(); + ctx.builder.xor_i32(); + + ctx.builder.get_local(&last_result); + ctx.builder.get_local(&last_op1); + ctx.builder.sub_i32(); + gen_get_flags_changed(ctx.builder); + ctx.builder.const_i32(31); + ctx.builder.shr_u_i32(); + ctx.builder.sub_i32(); + + ctx.builder.get_local(&last_result); + ctx.builder.xor_i32(); + + ctx.builder.and_i32(); + + gen_get_last_op_size(ctx.builder); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(1); + ctx.builder.and_i32(); + + ctx.builder.free_local(last_op1); + ctx.builder.free_local(last_result); + } + ctx.builder.else_(); + { + gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_OVERFLOW); + ctx.builder.and_i32(); + } + ctx.builder.block_end(); + ctx.builder.free_local(flags_changed); + }, + } +} + +pub fn gen_test_be(ctx: &mut JitContext, negate: ConditionNegate) { + match &ctx.previous_instruction { + Instruction::Cmp { + dest, + source, + opsize, + } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + match dest { + InstructionOperandDest::WasmLocal(l) => { + ctx.builder.get_local(l); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 0xFF } else { 0xFFFF }); + ctx.builder.and_i32(); + } + }, + InstructionOperandDest::Other => { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + }, + } + match source { + InstructionOperand::WasmLocal(l) => { + ctx.builder.get_local(l); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 0xFF } else { 0xFFFF }); + ctx.builder.and_i32(); + } + }, + InstructionOperand::Other => { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.sub_i32(); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 0xFF } else { 0xFFFF }); + ctx.builder.and_i32(); + } + }, + &InstructionOperand::Immediate(i) => { + dbg_assert!(*opsize != OPSIZE_8 || i >= 0 && i < 0x100); + dbg_assert!(*opsize != OPSIZE_16 || i >= 0 && i < 0x10000); + ctx.builder.const_i32(i); + }, + } + + if negate == ConditionNegate::True { + ctx.builder.gtu_i32(); + } + else { + ctx.builder.leu_i32(); + } + }, + Instruction::Sub { + opsize, + source, + is_dec: false, + .. + } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + match (opsize, source) { + (&OPSIZE_32, InstructionOperand::WasmLocal(l)) => ctx.builder.get_local(l), + (_, &InstructionOperand::Immediate(i)) => ctx.builder.const_i32(i), + _ => { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.sub_i32(); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 0xFF } else { 0xFFFF }); + ctx.builder.and_i32(); + } + }, + } + + if negate == ConditionNegate::True { + ctx.builder.gtu_i32(); + } + else { + ctx.builder.leu_i32(); + } + }, + &Instruction::Bitwise { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_getzf(ctx, negate); + }, + &Instruction::Add { .. } | &Instruction::Sub { is_dec: true, .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + // not the best code generation, but reasonable for this fairly uncommon case + gen_getcf(ctx, ConditionNegate::False); + gen_getzf(ctx, ConditionNegate::False); + ctx.builder.or_i32(); + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + Instruction::Other | Instruction::NonZeroShift { .. } | Instruction::AdcSbb { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED); + gen_getcf(ctx, ConditionNegate::False); + gen_getzf(ctx, ConditionNegate::False); + ctx.builder.or_i32(); + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + } +} + +pub fn gen_test_l(ctx: &mut JitContext, negate: ConditionNegate) { + match &ctx.previous_instruction { + Instruction::Cmp { + dest, + source, + opsize, + } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + match dest { + InstructionOperandDest::WasmLocal(l) => { + ctx.builder.get_local(l); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + InstructionOperandDest::Other => { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + } + match source { + InstructionOperand::WasmLocal(l) => { + ctx.builder.get_local(l); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + InstructionOperand::Other => { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.sub_i32(); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + &InstructionOperand::Immediate(i) => { + ctx.builder.const_i32(i); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + } + if negate == ConditionNegate::True { + ctx.builder.ge_i32(); + } + else { + ctx.builder.lt_i32(); + } + }, + Instruction::Sub { opsize, source, .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + match (opsize, source) { + (&OPSIZE_32, InstructionOperand::WasmLocal(l)) => ctx.builder.get_local(l), + (_, &InstructionOperand::Immediate(i)) => ctx.builder.const_i32( + i << if *opsize == OPSIZE_32 { + 0 + } + else if *opsize == OPSIZE_16 { + 16 + } + else { + 24 + }, + ), + _ => { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.sub_i32(); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + } + if negate == ConditionNegate::True { + ctx.builder.ge_i32(); + } + else { + ctx.builder.lt_i32(); + } + }, + &Instruction::Bitwise { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_getsf(ctx, negate); + }, + &Instruction::Other + | Instruction::Add { .. } + | Instruction::NonZeroShift { .. } + | Instruction::AdcSbb { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED); + if let Instruction::Add { .. } = ctx.previous_instruction { + gen_profiler_stat_increment( + ctx.builder, + profiler::stat::CONDITION_UNOPTIMISED_UNHANDLED_L, + ); + } + gen_getsf(ctx, ConditionNegate::False); + ctx.builder.eqz_i32(); + gen_getof(ctx); + ctx.builder.eqz_i32(); + ctx.builder.xor_i32(); + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + } +} + +pub fn gen_test_le(ctx: &mut JitContext, negate: ConditionNegate) { + match &ctx.previous_instruction { + Instruction::Cmp { + dest, + source, + opsize, + } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + match dest { + InstructionOperandDest::WasmLocal(l) => { + ctx.builder.get_local(l); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + InstructionOperandDest::Other => { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + } + match source { + InstructionOperand::WasmLocal(l) => { + ctx.builder.get_local(l); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + InstructionOperand::Other => { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.sub_i32(); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + &InstructionOperand::Immediate(i) => { + ctx.builder.const_i32(i); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + } + if negate == ConditionNegate::True { + ctx.builder.gt_i32(); + } + else { + ctx.builder.le_i32(); + } + }, + Instruction::Sub { opsize, source, .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + match (opsize, source) { + (&OPSIZE_32, InstructionOperand::WasmLocal(l)) => ctx.builder.get_local(l), + (_, &InstructionOperand::Immediate(i)) => ctx.builder.const_i32( + i << if *opsize == OPSIZE_32 { + 0 + } + else if *opsize == OPSIZE_16 { + 16 + } + else { + 24 + }, + ), + _ => { + gen_get_last_op1(ctx.builder, &ctx.previous_instruction); + gen_get_last_result(ctx.builder, &ctx.previous_instruction); + ctx.builder.sub_i32(); + if *opsize == OPSIZE_8 || *opsize == OPSIZE_16 { + ctx.builder + .const_i32(if *opsize == OPSIZE_8 { 24 } else { 16 }); + ctx.builder.shl_i32(); + } + }, + } + if negate == ConditionNegate::True { + ctx.builder.gt_i32(); + } + else { + ctx.builder.le_i32(); + } + }, + &Instruction::Bitwise { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_OPTIMISED); + // TODO: Could probably be improved (<= 0) + gen_test_l(ctx, ConditionNegate::False); + gen_getzf(ctx, ConditionNegate::False); + ctx.builder.or_i32(); + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + Instruction::Other + | Instruction::Add { .. } + | Instruction::NonZeroShift { .. } + | Instruction::AdcSbb { .. } => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED); + if let Instruction::Add { .. } = ctx.previous_instruction { + gen_profiler_stat_increment( + ctx.builder, + profiler::stat::CONDITION_UNOPTIMISED_UNHANDLED_LE, + ); + } + gen_test_l(ctx, ConditionNegate::False); + gen_getzf(ctx, ConditionNegate::False); + ctx.builder.or_i32(); + if negate == ConditionNegate::True { + ctx.builder.eqz_i32(); + } + }, + } +} + +pub fn gen_test_loopnz(ctx: &mut JitContext, is_asize_32: bool) { + gen_test_loop(ctx, is_asize_32); + ctx.builder.eqz_i32(); + gen_getzf(ctx, ConditionNegate::False); + ctx.builder.or_i32(); + ctx.builder.eqz_i32(); +} +pub fn gen_test_loopz(ctx: &mut JitContext, is_asize_32: bool) { + gen_test_loop(ctx, is_asize_32); + ctx.builder.eqz_i32(); + gen_getzf(ctx, ConditionNegate::False); + ctx.builder.eqz_i32(); + ctx.builder.or_i32(); + ctx.builder.eqz_i32(); +} +pub fn gen_test_loop(ctx: &mut JitContext, is_asize_32: bool) { + if is_asize_32 { + gen_get_reg32(ctx, regs::ECX); + } + else { + gen_get_reg16(ctx, regs::CX); + } +} +pub fn gen_test_jcxz(ctx: &mut JitContext, is_asize_32: bool) { + if is_asize_32 { + gen_get_reg32(ctx, regs::ECX); + } + else { + gen_get_reg16(ctx, regs::CX); + } + ctx.builder.eqz_i32(); +} + +pub fn gen_fpu_get_sti(ctx: &mut JitContext, i: u32) { + ctx.builder + .const_i32(global_pointers::sse_scratch_register as i32); + ctx.builder.const_i32(i as i32); + ctx.builder.call_fn2("fpu_get_sti"); + ctx.builder + .load_fixed_i64(global_pointers::sse_scratch_register as u32); + ctx.builder + .load_fixed_u16(global_pointers::sse_scratch_register as u32 + 8); +} + +pub fn gen_fpu_load_m32(ctx: &mut JitContext, modrm_byte: ModrmByte) { + ctx.builder + .const_i32(global_pointers::sse_scratch_register as i32); + gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.call_fn2("f32_to_f80"); + ctx.builder + .load_fixed_i64(global_pointers::sse_scratch_register as u32); + ctx.builder + .load_fixed_u16(global_pointers::sse_scratch_register as u32 + 8); +} + +pub fn gen_fpu_load_m64(ctx: &mut JitContext, modrm_byte: ModrmByte) { + ctx.builder + .const_i32(global_pointers::sse_scratch_register as i32); + gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.call_fn2_i32_i64("f64_to_f80"); + ctx.builder + .load_fixed_i64(global_pointers::sse_scratch_register as u32); + ctx.builder + .load_fixed_u16(global_pointers::sse_scratch_register as u32 + 8); +} + +pub fn gen_fpu_load_i16(ctx: &mut JitContext, modrm_byte: ModrmByte) { + ctx.builder + .const_i32(global_pointers::sse_scratch_register as i32); + gen_modrm_resolve_safe_read16(ctx, modrm_byte); + sign_extend_i16(ctx.builder); + ctx.builder.call_fn2("i32_to_f80"); + ctx.builder + .load_fixed_i64(global_pointers::sse_scratch_register as u32); + ctx.builder + .load_fixed_u16(global_pointers::sse_scratch_register as u32 + 8); +} +pub fn gen_fpu_load_i32(ctx: &mut JitContext, modrm_byte: ModrmByte) { + ctx.builder + .const_i32(global_pointers::sse_scratch_register as i32); + gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.call_fn2("i32_to_f80"); + ctx.builder + .load_fixed_i64(global_pointers::sse_scratch_register as u32); + ctx.builder + .load_fixed_u16(global_pointers::sse_scratch_register as u32 + 8); +} +pub fn gen_fpu_load_i64(ctx: &mut JitContext, modrm_byte: ModrmByte) { + ctx.builder + .const_i32(global_pointers::sse_scratch_register as i32); + gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.call_fn2_i32_i64("i64_to_f80"); + ctx.builder + .load_fixed_i64(global_pointers::sse_scratch_register as u32); + ctx.builder + .load_fixed_u16(global_pointers::sse_scratch_register as u32 + 8); +} + +pub fn gen_trigger_de(ctx: &mut JitContext) { + gen_fn1_const( + ctx.builder, + "trigger_de_jit", + ctx.start_of_current_instruction, + ); + gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.br(ctx.exit_with_fault_label); +} + +pub fn gen_trigger_ud(ctx: &mut JitContext) { + gen_fn1_const( + ctx.builder, + "trigger_ud_jit", + ctx.start_of_current_instruction, + ); + gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.br(ctx.exit_with_fault_label); +} + +pub fn gen_trigger_gp(ctx: &mut JitContext, error_code: u32) { + gen_fn2_const( + ctx.builder, + "trigger_gp_jit", + error_code, + ctx.start_of_current_instruction, + ); + gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.br(ctx.exit_with_fault_label); +} + +pub fn gen_condition_fn_negated(ctx: &mut JitContext, condition: u8) { + gen_condition_fn(ctx, condition ^ 1) +} + +pub fn gen_condition_fn(ctx: &mut JitContext, condition: u8) { + if condition & 0xF0 == 0x00 || condition & 0xF0 == 0x70 || condition & 0xF0 == 0x80 { + match condition & 0xF { + 0x0 => { + gen_getof(ctx); + }, + 0x1 => { + gen_getof(ctx); + ctx.builder.eqz_i32(); + }, + 0x2 => { + gen_getcf(ctx, ConditionNegate::False); + }, + 0x3 => { + gen_getcf(ctx, ConditionNegate::True); + }, + 0x4 => { + gen_getzf(ctx, ConditionNegate::False); + }, + 0x5 => { + gen_getzf(ctx, ConditionNegate::True); + }, + 0x6 => { + gen_test_be(ctx, ConditionNegate::False); + }, + 0x7 => { + gen_test_be(ctx, ConditionNegate::True); + }, + 0x8 => { + gen_getsf(ctx, ConditionNegate::False); + }, + 0x9 => { + gen_getsf(ctx, ConditionNegate::True); + }, + 0xA => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED); + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED_PF); + ctx.builder.call_fn0_ret("test_p"); + }, + 0xB => { + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED); + gen_profiler_stat_increment(ctx.builder, profiler::stat::CONDITION_UNOPTIMISED_PF); + ctx.builder.call_fn0_ret("test_np"); + }, + 0xC => { + gen_test_l(ctx, ConditionNegate::False); + }, + 0xD => { + gen_test_l(ctx, ConditionNegate::True); + }, + 0xE => { + gen_test_le(ctx, ConditionNegate::False); + }, + 0xF => { + gen_test_le(ctx, ConditionNegate::True); + }, + _ => { + dbg_assert!(false); + }, + } + } + else { + // loop, loopnz, loopz, jcxz + dbg_assert!(condition & !0x3 == 0xE0); + if condition == 0xE0 { + gen_test_loopnz(ctx, ctx.cpu.asize_32()); + } + else if condition == 0xE1 { + gen_test_loopz(ctx, ctx.cpu.asize_32()); + } + else if condition == 0xE2 { + gen_test_loop(ctx, ctx.cpu.asize_32()); + } + else if condition == 0xE3 { + gen_test_jcxz(ctx, ctx.cpu.asize_32()); + } + } +} + +pub fn gen_move_registers_from_locals_to_memory(ctx: &mut JitContext) { + if cfg!(feature = "profiler") { + let instruction = memory::read32s(ctx.start_of_current_instruction) as u32; + ::opstats::gen_opstat_unguarded_register(ctx.builder, instruction); + } + + for i in 0..8 { + ctx.builder + .const_i32(global_pointers::get_reg32_offset(i as u32) as i32); + ctx.builder.get_local(&ctx.register_locals[i]); + ctx.builder.store_aligned_i32(0); + } +} +pub fn gen_move_registers_from_memory_to_locals(ctx: &mut JitContext) { + if cfg!(feature = "profiler") { + let instruction = memory::read32s(ctx.start_of_current_instruction) as u32; + ::opstats::gen_opstat_unguarded_register(ctx.builder, instruction); + } + + for i in 0..8 { + ctx.builder + .const_i32(global_pointers::get_reg32_offset(i as u32) as i32); + ctx.builder.load_aligned_i32(0); + ctx.builder.set_local(&ctx.register_locals[i]); + } +} + +pub fn gen_profiler_stat_increment(builder: &mut WasmBuilder, stat: profiler::stat) { + if !cfg!(feature = "profiler") { + return; + } + let addr = unsafe { profiler::stat_array.as_mut_ptr().offset(stat as isize) } as u32; + builder.increment_fixed_i64(addr, 1) +} + +pub fn gen_debug_track_jit_exit(builder: &mut WasmBuilder, address: u32) { + if cfg!(feature = "profiler") { + gen_fn1_const(builder, "track_jit_exit", address); + } +} diff --git a/src/rust/config.rs b/src/rust/config.rs new file mode 100644 index 0000000..0a8ab4a --- /dev/null +++ b/src/rust/config.rs @@ -0,0 +1,4 @@ +pub const LOG_PAGE_FAULTS: bool = false; +pub const FORCE_DISABLE_JIT: bool = false; + +pub const VMWARE_HYPERVISOR_PORT: bool = true; diff --git a/src/rust/control_flow.rs b/src/rust/control_flow.rs new file mode 100644 index 0000000..ae43116 --- /dev/null +++ b/src/rust/control_flow.rs @@ -0,0 +1,420 @@ +use std::collections::{HashMap, HashSet}; +use std::iter; + +use jit::{BasicBlock, BasicBlockType, MAX_EXTRA_BASIC_BLOCKS}; +use profiler; + +const ENTRY_NODE_ID: u32 = 0xffff_ffff; + +type Graph = HashMap>; + +/// Reverse the direction of all edges in the graph +fn rev_graph_edges(nodes: &Graph) -> Graph { + let mut rev_nodes = Graph::new(); + for (from, tos) in nodes { + for to in tos { + rev_nodes + .entry(*to) + .or_insert_with(|| HashSet::new()) + .insert(*from); + } + } + rev_nodes +} + +pub fn make_graph(basic_blocks: &Vec) -> Graph { + let mut nodes = Graph::new(); + let mut entry_edges = HashSet::new(); + + for b in basic_blocks.iter() { + let mut edges = HashSet::new(); + + match &b.ty { + &BasicBlockType::ConditionalJump { + next_block_addr, + next_block_branch_taken_addr, + .. + } => { + if let Some(next_block_addr) = next_block_addr { + edges.insert(next_block_addr); + } + if let Some(next_block_branch_taken_addr) = next_block_branch_taken_addr { + edges.insert(next_block_branch_taken_addr); + } + }, + &BasicBlockType::Normal { + next_block_addr: Some(next_block_addr), + .. + } => { + edges.insert(next_block_addr); + }, + &BasicBlockType::Normal { + next_block_addr: None, + .. + } => {}, + BasicBlockType::Exit => {}, + BasicBlockType::AbsoluteEip => { + // Not necessary: We generate a loop around the outer brtable unconditionally + //edges.insert(ENTRY_NODE_ID); + }, + } + + nodes.insert(b.addr, edges); + + if b.is_entry_block { + entry_edges.insert(b.addr); + } + } + + // Entry node that represents the initial basic block of the generated function (must be + // able to reach all entry nodes) + nodes.insert(ENTRY_NODE_ID, entry_edges); + return nodes; +} + +pub enum WasmStructure { + BasicBlock(u32), + Dispatcher(Vec), + Loop(Vec), + Block(Vec), +} +impl WasmStructure { + pub fn print(&self, depth: usize) { + match self { + Self::BasicBlock(addr) => { + dbg_log!("{} 0x{:x}", " ".repeat(depth), addr); + }, + Self::Dispatcher(entries) => { + dbg_log!("{} Dispatcher entries:", " ".repeat(depth)); + for e in entries { + dbg_log!("{} {:x}", " ".repeat(depth), e); + } + }, + Self::Loop(elements) => { + dbg_log!("{} loop_void({})", " ".repeat(depth), elements.len()); + for e in elements { + e.print(depth + 1) + } + dbg_log!("{} loop_end({})", " ".repeat(depth), elements.len()); + }, + Self::Block(elements) => { + dbg_log!("{} block_void({})", " ".repeat(depth), elements.len()); + for e in elements { + e.print(depth + 1) + } + dbg_log!("{} block_end({})", " ".repeat(depth), elements.len()); + }, + } + } + + fn branches(&self, edges: &Graph) -> HashSet { + fn handle(block: &WasmStructure, edges: &Graph, result: &mut HashSet) { + match block { + WasmStructure::BasicBlock(addr) => result.extend(edges.get(&addr).unwrap()), + WasmStructure::Dispatcher(entries) => result.extend(entries), + WasmStructure::Loop(children) | WasmStructure::Block(children) => { + for c in children.iter() { + handle(c, edges, result); + } + }, + } + } + + let mut result = HashSet::new(); + handle(self, edges, &mut result); + result + } + + pub fn head(&self) -> Box + '_> { + match self { + Self::BasicBlock(addr) => Box::new(iter::once(*addr)), + Self::Dispatcher(entries) => Box::new(entries.iter().copied()), + Self::Loop(children) => children.first().unwrap().head(), + Self::Block(elements) => elements.first().unwrap().head(), + } + } +} + +/// Check: +/// - Dispatcher appears at the beginning of a loop +/// - No two nested blocks at the end +/// - No two nested loops at the beginning +/// - No empty blocks or loops +/// - The entry node block is not present +pub fn assert_invariants(blocks: &Vec) { + fn check(node: &WasmStructure, in_tail_block: bool, in_head_loop: bool, is_first: bool) { + match node { + WasmStructure::Block(children) => { + dbg_assert!(!in_tail_block); + dbg_assert!(!children.is_empty()); + for (i, c) in children.iter().enumerate() { + let is_first = i == 0; + let is_last = i == children.len() - 1; + check(c, is_last, in_head_loop && is_first, is_first); + } + }, + WasmStructure::Loop(children) => { + dbg_assert!(!in_head_loop); + dbg_assert!(!children.is_empty()); + for (i, c) in children.iter().enumerate() { + let is_first = i == 0; + let is_last = i == children.len() - 1; + check(c, in_tail_block && is_last, is_first, is_first); + } + }, + &WasmStructure::BasicBlock(addr) => { + dbg_assert!(addr != ENTRY_NODE_ID); + }, + WasmStructure::Dispatcher(_) => { + dbg_assert!(is_first); + //dbg_assert!(in_head_loop); // fails for module dispatcher + }, + } + } + + for (i, b) in blocks.iter().enumerate() { + check(b, false, false, i == 0); + } +} + +/// Strongly connected components via Kosaraju's algorithm +fn scc(edges: &Graph, rev_edges: &Graph) -> Vec> { + fn visit( + node: u32, + edges: &Graph, + rev_edges: &Graph, + visited: &mut HashSet, + l: &mut Vec, + ) { + if visited.contains(&node) { + return; + } + visited.insert(node); + for &next in edges.get(&node).unwrap() { + visit(next, edges, rev_edges, visited, l); + } + l.push(node); + } + + let mut l = Vec::new(); + let mut visited = HashSet::new(); + for &node in edges.keys() { + visit(node, edges, rev_edges, &mut visited, &mut l); + } + + fn assign( + node: u32, + edges: &Graph, + rev_edges: &Graph, + assigned: &mut HashSet, + group: &mut Vec, + ) { + if assigned.contains(&node) { + return; + } + assigned.insert(node); + group.push(node); + if let Some(nexts) = rev_edges.get(&node) { + for &next in nexts { + assign(next, edges, rev_edges, assigned, group); + } + } + } + let mut assigned = HashSet::new(); + let mut assignment = Vec::new(); + for &node in l.iter().rev() { + let mut group = Vec::new(); + assign(node, edges, rev_edges, &mut assigned, &mut group); + if !group.is_empty() { + assignment.push(group); + } + } + + assignment +} + +pub fn loopify(nodes: &Graph) -> Vec { + let rev_nodes = rev_graph_edges(nodes); + let groups = scc(nodes, &rev_nodes); + + return groups + .iter() + .flat_map(|group| { + dbg_assert!(!group.is_empty()); + if group.len() == 1 { + let addr = group[0]; + if addr == ENTRY_NODE_ID { + let entries = nodes.get(&ENTRY_NODE_ID).unwrap().iter().copied().collect(); + return vec![WasmStructure::Dispatcher(entries)].into_iter(); + } + let block = WasmStructure::BasicBlock(addr); + // self-loops + if nodes.get(&group[0]).unwrap().contains(&group[0]) { + return vec![WasmStructure::Loop(vec![block])].into_iter(); + } + else { + return vec![block].into_iter(); + } + } + + let entries_to_group: Vec = group + .iter() + .filter(|addr| { + // reachable from outside of the group + rev_nodes.get(addr).map_or(false, |x| { + x.iter().any(|incoming| !group.contains(incoming)) + }) + }) + .copied() + .collect(); + + if entries_to_group.len() != 1 { + //dbg_log!( + // "Compiling multi-entry loop with {} entries and {} basic blocks", + // entries_to_group.len(), + // group.len() + //); + } + + let max_extra_basic_blocks = unsafe { MAX_EXTRA_BASIC_BLOCKS } as usize; + + if entries_to_group.len() * group.len() > max_extra_basic_blocks { + let mut subgroup_edges: Graph = Graph::new(); + for elem in group { + subgroup_edges.insert( + *elem, + nodes + .get(&elem) + .unwrap() + .iter() + .filter(|dest| { + // XXX: This might remove forward edges to other loop entries + // Probably not an issue since it can go through the + // dispatcher + group.contains(dest) && !entries_to_group.contains(dest) + }) + .copied() + .collect(), + ); + } + + let mut loop_nodes = loopify(&subgroup_edges); + + if entries_to_group.len() > 1 { + loop_nodes.insert(0, WasmStructure::Dispatcher(entries_to_group)); + } + + return vec![WasmStructure::Loop(loop_nodes)].into_iter(); + } + else { + profiler::stat_increment_by( + profiler::stat::COMPILE_DUPLICATED_BASIC_BLOCK, + ((entries_to_group.len() - 1) * group.len()) as u64, + ); + + let nodes: Vec = entries_to_group + .iter() + .map(|&entry| { + let mut subgroup_edges: Graph = Graph::new(); + for &elem in group { + subgroup_edges.insert( + elem, + nodes + .get(&elem) + .unwrap() + .iter() + .copied() + .filter(|dest| group.contains(dest) && *dest != entry) + .collect(), + ); + } + let loop_nodes = loopify(&subgroup_edges); + WasmStructure::Loop(loop_nodes) + }) + .collect(); + + nodes.into_iter() + } + }) + .collect(); +} + +pub fn blockify(blocks: &mut Vec, edges: &Graph) { + let mut cached_branches: Vec> = Vec::new(); + for i in 0..blocks.len() { + cached_branches.push(blocks[i].branches(edges)); + } + + let mut i = 0; + while i < blocks.len() { + match &mut blocks[i] { + WasmStructure::BasicBlock(_) | WasmStructure::Dispatcher(_) => {}, + WasmStructure::Loop ( + blocks + ) + // TODO: Might be faster to do this *after* inserting blocks in this block + | WasmStructure::Block(blocks) => blockify(blocks, edges), + } + + let source = { + let mut source = None; + for j in 0..i { + if blocks[i].head().any(|bb| cached_branches[j].contains(&bb)) { + source = Some(j); + break; + } + } + match source { + Some(s) => s, + None => { + i += 1; + continue; + }, + } + }; + + // This is optional: Avoid putting a single basic block into a block + if source == i - 1 { + match &blocks[source] { + &WasmStructure::BasicBlock(_) => { + i += 1; + continue; + }, + _ => {}, + } + } + + let replacement = WasmStructure::Block(Vec::new()); + let children: Vec = + blocks.splice(source..i, iter::once(replacement)).collect(); + match &mut blocks[source] { + WasmStructure::Block(c) => c.extend(children), + _ => { + dbg_assert!(false); + }, + } + match &blocks[source + 1] { + WasmStructure::BasicBlock(_) => + //dbg_assert!(*b == bbs.next().unwrap()) + {} + WasmStructure::Dispatcher(_) => {}, + WasmStructure::Loop(_blocks) | WasmStructure::Block(_blocks) => {}, //dbg_assert!(blocks[0].head() == bb), + } + + { + let replacement = HashSet::new(); + let children: Vec> = cached_branches + .splice(source..i, iter::once(replacement)) + .collect(); + dbg_assert!(cached_branches[source].len() == 0); + let mut iter = children.into_iter(); + cached_branches[source] = iter.next().unwrap(); + for c in iter { + cached_branches[source].extend(c); + } + } + + // skip the inserted block and this block + i = source + 2; + } +} diff --git a/src/rust/cpu/arith.rs b/src/rust/cpu/arith.rs new file mode 100644 index 0000000..3604723 --- /dev/null +++ b/src/rust/cpu/arith.rs @@ -0,0 +1,1202 @@ +use cpu::cpu::*; +use cpu::global_pointers::*; +use cpu::memory::{read8, write8}; +use cpu::misc_instr::{getaf, getcf, getzf}; + +fn int_log2(x: i32) -> i32 { 31 - x.leading_zeros() as i32 } + +unsafe fn add(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 { + let res = dest_operand + source_operand; + *last_op1 = dest_operand; + *last_result = res & (2 << op_size) - 1; + *last_op_size = op_size; + *flags_changed = FLAGS_ALL; + return res; +} +unsafe fn adc(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 { + let cf = getcf() as i32; + let res = dest_operand + source_operand + cf; + *last_op1 = dest_operand; + *last_result = res; + *last_op_size = op_size; + *flags_changed = FLAGS_ALL & !FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW; + *flags = *flags & !FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW + | (dest_operand ^ ((dest_operand ^ source_operand) & (source_operand ^ res))) >> op_size + & FLAG_CARRY + | (dest_operand ^ source_operand ^ res) & FLAG_ADJUST + | ((source_operand ^ res) & (dest_operand ^ res)) >> op_size << 11 & FLAG_OVERFLOW; + return res; +} +unsafe fn sub(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 { + let res = dest_operand - source_operand; + *last_op1 = dest_operand; + *last_result = res & (2 << op_size) - 1; + *last_op_size = op_size; + *flags_changed = FLAGS_ALL | FLAG_SUB; + return res; +} +unsafe fn sbb(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 { + let cf = getcf() as i32; + let res = dest_operand - source_operand - cf; + *last_op1 = dest_operand; + *last_result = res; + *last_op_size = op_size; + *flags_changed = FLAGS_ALL & !FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW | FLAG_SUB; + *flags = *flags & !FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW + | (res ^ ((res ^ source_operand) & (source_operand ^ dest_operand))) >> op_size + & FLAG_CARRY + | (dest_operand ^ source_operand ^ res) & FLAG_ADJUST + | ((source_operand ^ dest_operand) & (res ^ dest_operand)) >> op_size << 11 & FLAG_OVERFLOW; + return res; +} +pub unsafe fn add8(x: i32, y: i32) -> i32 { + dbg_assert!(x >= 0 && x < 0x10000); + dbg_assert!(y >= 0 && y < 0x10000); + return add(x, y, OPSIZE_8); +} +#[no_mangle] +pub unsafe fn add16(x: i32, y: i32) -> i32 { + dbg_assert!(x >= 0 && x < 0x10000); + dbg_assert!(y >= 0 && y < 0x10000); + return add(x, y, OPSIZE_16); +} +pub unsafe fn add32(x: i32, y: i32) -> i32 { return add(x, y, OPSIZE_32); } +pub unsafe fn sub8(x: i32, y: i32) -> i32 { return sub(x, y, OPSIZE_8); } +#[no_mangle] +pub unsafe fn sub16(x: i32, y: i32) -> i32 { return sub(x, y, OPSIZE_16); } +pub unsafe fn sub32(x: i32, y: i32) -> i32 { return sub(x, y, OPSIZE_32); } +#[no_mangle] +pub unsafe fn adc8(x: i32, y: i32) -> i32 { return adc(x, y, OPSIZE_8); } +#[no_mangle] +pub unsafe fn adc16(x: i32, y: i32) -> i32 { return adc(x, y, OPSIZE_16); } +pub unsafe fn adc32(x: i32, y: i32) -> i32 { return adc(x, y, OPSIZE_32); } +#[no_mangle] +pub unsafe fn sbb8(x: i32, y: i32) -> i32 { return sbb(x, y, OPSIZE_8); } +#[no_mangle] +pub unsafe fn sbb16(x: i32, y: i32) -> i32 { return sbb(x, y, OPSIZE_16); } +pub unsafe fn sbb32(x: i32, y: i32) -> i32 { return sbb(x, y, OPSIZE_32); } +pub unsafe fn cmp8(x: i32, y: i32) { + dbg_assert!(x >= 0 && x < 0x100); + dbg_assert!(y >= 0 && y < 0x100); + sub(x, y, OPSIZE_8); +} +pub unsafe fn cmp16(x: i32, y: i32) { + dbg_assert!(x >= 0 && x < 0x10000); + dbg_assert!(y >= 0 && y < 0x10000); + sub(x, y, OPSIZE_16); +} +pub unsafe fn cmp32(x: i32, y: i32) { sub(x, y, OPSIZE_32); } +unsafe fn inc(dest_operand: i32, op_size: i32) -> i32 { + *flags = *flags & !1 | getcf() as i32; + let res = dest_operand + 1; + *last_op1 = dest_operand; + *last_result = res & (2 << op_size) - 1; + *last_op_size = op_size; + *flags_changed = FLAGS_ALL & !1; + return res; +} +unsafe fn dec(dest_operand: i32, op_size: i32) -> i32 { + *flags = *flags & !1 | getcf() as i32; + let res = dest_operand - 1; + *last_op1 = dest_operand; + *last_result = res & (2 << op_size) - 1; + *last_op_size = op_size; + *flags_changed = FLAGS_ALL & !1 | FLAG_SUB; + return res; +} +#[no_mangle] +pub unsafe fn inc8(x: i32) -> i32 { return inc(x, OPSIZE_8); } +pub unsafe fn inc16(x: i32) -> i32 { return inc(x, OPSIZE_16); } +pub unsafe fn inc32(x: i32) -> i32 { return inc(x, OPSIZE_32); } +#[no_mangle] +pub unsafe fn dec8(x: i32) -> i32 { return dec(x, OPSIZE_8); } +pub unsafe fn dec16(x: i32) -> i32 { return dec(x, OPSIZE_16); } +pub unsafe fn dec32(x: i32) -> i32 { return dec(x, OPSIZE_32); } + +unsafe fn neg(dest_operand: i32, op_size: i32) -> i32 { sub(0, dest_operand, op_size) } +#[no_mangle] +pub unsafe fn not8(x: i32) -> i32 { return !x; } +#[no_mangle] +pub unsafe fn neg8(x: i32) -> i32 { return neg(x, OPSIZE_8); } +#[no_mangle] +pub unsafe fn neg16(x: i32) -> i32 { return neg(x, OPSIZE_16); } +pub unsafe fn neg32(x: i32) -> i32 { return neg(x, OPSIZE_32); } + +#[no_mangle] +pub unsafe fn mul8(source_operand: i32) { + let result = source_operand * read_reg8(AL); + write_reg16(AX, result); + *last_result = result & 255; + *last_op_size = OPSIZE_8; + if result < 256 { + *flags &= !1 & !FLAG_OVERFLOW + } + else { + *flags |= 1 | FLAG_OVERFLOW + } + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; +} +#[no_mangle] +pub unsafe fn imul8(source_operand: i32) { + let result = source_operand * (read_reg8(AL) << 24 >> 24); + write_reg16(AX, result); + *last_result = result & 255; + *last_op_size = OPSIZE_8; + if result > 127 || result < -128 { + *flags |= 1 | FLAG_OVERFLOW + } + else { + *flags &= !1 & !FLAG_OVERFLOW + } + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; +} +#[no_mangle] +pub unsafe fn mul16(source_operand: u32) { + let result = source_operand * read_reg16(AX) as u32; + let high_result = result >> 16; + write_reg16(AX, result as i32); + write_reg16(DX, high_result as i32); + *last_result = (result & 0xFFFF) as i32; + *last_op_size = OPSIZE_16; + if high_result == 0 { + *flags &= !1 & !FLAG_OVERFLOW + } + else { + *flags |= 1 | FLAG_OVERFLOW + } + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; +} +#[no_mangle] +pub unsafe fn imul16(source_operand: i32) { + let result = source_operand * (read_reg16(AX) << 16 >> 16); + write_reg16(AX, result); + write_reg16(DX, result >> 16); + *last_result = result & 0xFFFF; + *last_op_size = OPSIZE_16; + if result > 32767 || result < -32768 { + *flags |= 1 | FLAG_OVERFLOW + } + else { + *flags &= !1 & !FLAG_OVERFLOW + } + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; +} +#[no_mangle] +pub unsafe fn imul_reg16(mut operand1: i32, mut operand2: i32) -> i32 { + operand1 = operand1 << 16 >> 16; + operand2 = operand2 << 16 >> 16; + let result = operand1 * operand2; + *last_result = result & 0xFFFF; + *last_op_size = OPSIZE_16; + if result > 32767 || result < -32768 { + *flags |= 1 | FLAG_OVERFLOW + } + else { + *flags &= !1 & !FLAG_OVERFLOW + } + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + return result; +} +#[no_mangle] +pub unsafe fn mul32(source_operand: i32) { + let dest_operand = read_reg32(EAX); + let result = (dest_operand as u32 as u64) * (source_operand as u32 as u64); + let result_low = result as i32; + let result_high = (result >> 32) as i32; + write_reg32(EAX, result_low); + write_reg32(EDX, result_high); + *last_result = result_low; + *last_op_size = OPSIZE_32; + if result_high == 0 { + *flags &= !1 & !FLAG_OVERFLOW + } + else { + *flags |= 1 | FLAG_OVERFLOW + } + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; +} +pub unsafe fn imul32(source_operand: i32) { + let dest_operand = read_reg32(EAX); + let result = dest_operand as i64 * source_operand as i64; + let result_low = result as i32; + let result_high = (result >> 32) as i32; + write_reg32(EAX, result_low); + write_reg32(EDX, result_high); + *last_result = result_low; + *last_op_size = OPSIZE_32; + if result_high == result_low >> 31 { + *flags &= !1 & !FLAG_OVERFLOW + } + else { + *flags |= 1 | FLAG_OVERFLOW + } + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; +} +pub unsafe fn imul_reg32(operand1: i32, operand2: i32) -> i32 { + let result = operand1 as i64 * operand2 as i64; + let result_low = result as i32; + let result_high = (result >> 32) as i32; + *last_result = result_low; + *last_op_size = OPSIZE_32; + if result_high == result_low >> 31 { + *flags &= !1 & !FLAG_OVERFLOW + } + else { + *flags |= 1 | FLAG_OVERFLOW + } + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + return result_low; +} + +#[no_mangle] +pub unsafe fn xadd8(source_operand: i32, reg: i32) -> i32 { + let tmp = read_reg8(reg); + write_reg8(reg, source_operand); + return add(source_operand, tmp, OPSIZE_8); +} +#[no_mangle] +pub unsafe fn xadd16(source_operand: i32, reg: i32) -> i32 { + let tmp = read_reg16(reg); + write_reg16(reg, source_operand); + return add(source_operand, tmp, OPSIZE_16); +} +pub unsafe fn xadd32(source_operand: i32, reg: i32) -> i32 { + let tmp = read_reg32(reg); + write_reg32(reg, source_operand); + return add(source_operand, tmp, OPSIZE_32); +} + +#[no_mangle] +pub unsafe fn cmpxchg8(data: i32, r: i32) -> i32 { + cmp8(read_reg8(AL), data); + if getzf() { + read_reg8(r) + } + else { + write_reg8(AL, data); + data + } +} +#[no_mangle] +pub unsafe fn cmpxchg16(data: i32, r: i32) -> i32 { + cmp16(read_reg16(AX), data); + if getzf() { + read_reg16(r) + } + else { + write_reg16(AX, data); + data + } +} +pub unsafe fn cmpxchg32(data: i32, r: i32) -> i32 { + cmp32(read_reg32(EAX), data); + if getzf() { + read_reg32(r) + } + else { + write_reg32(EAX, data); + data + } +} + +#[no_mangle] +pub unsafe fn bcd_daa() { + let old_al = read_reg8(AL); + let old_cf = getcf(); + let old_af = getaf(); + *flags &= !1 & !FLAG_ADJUST; + if old_al & 15 > 9 || old_af { + write_reg8(AL, read_reg8(AL) + 6); + *flags |= FLAG_ADJUST + } + if old_al > 153 || old_cf { + write_reg8(AL, read_reg8(AL) + 96); + *flags |= 1 + } + *last_result = read_reg8(AL); + *last_op_size = OPSIZE_8; + *flags_changed = FLAGS_ALL & !1 & !FLAG_ADJUST & !FLAG_OVERFLOW; +} +#[no_mangle] +pub unsafe fn bcd_das() { + let old_al = read_reg8(AL); + let old_cf = getcf(); + *flags &= !1; + if old_al & 15 > 9 || getaf() { + write_reg8(AL, read_reg8(AL) - 6); + *flags |= FLAG_ADJUST; + *flags = *flags & !1 | old_cf as i32 | (old_al < 6) as i32 + } + else { + *flags &= !FLAG_ADJUST + } + if old_al > 153 || old_cf { + write_reg8(AL, read_reg8(AL) - 96); + *flags |= 1 + } + *last_result = read_reg8(AL); + *last_op_size = OPSIZE_8; + *flags_changed = FLAGS_ALL & !1 & !FLAG_ADJUST & !FLAG_OVERFLOW; +} +#[no_mangle] +pub unsafe fn bcd_aad(imm8: i32) { + let result = read_reg8(AL) + read_reg8(AH) * imm8; + *last_result = result & 255; + write_reg16(AX, *last_result); + *last_op_size = OPSIZE_8; + *flags_changed = FLAGS_ALL & !1 & !FLAG_ADJUST & !FLAG_OVERFLOW; + *flags &= !1 & !FLAG_ADJUST & !FLAG_OVERFLOW; + if result > 0xFFFF { + *flags |= 1 + }; +} +#[no_mangle] +pub unsafe fn bcd_aam(imm8: i32) { + // ascii adjust after multiplication + if imm8 == 0 { + trigger_de(); + } + else { + let temp = read_reg8(AL); + write_reg8(AH, temp as i32 / imm8); + write_reg8(AL, temp as i32 % imm8); + *last_result = read_reg8(AL); + *last_op_size = OPSIZE_8; + *flags_changed = FLAGS_ALL & !1 & !FLAG_ADJUST & !FLAG_OVERFLOW; + *flags &= !1 & !FLAG_ADJUST & !FLAG_OVERFLOW + }; +} +#[no_mangle] +pub unsafe fn bcd_aaa() { + if read_reg8(AL) & 15 > 9 || getaf() { + write_reg16(AX, read_reg16(AX) + 6); + write_reg8(AH, read_reg8(AH) + 1); + *flags |= FLAG_ADJUST | 1 + } + else { + *flags &= !FLAG_ADJUST & !1 + } + write_reg8(AL, read_reg8(AL) & 15); + *flags_changed &= !FLAG_ADJUST & !1; +} +#[no_mangle] +pub unsafe fn bcd_aas() { + if read_reg8(AL) & 15 > 9 || getaf() { + write_reg16(AX, read_reg16(AX) - 6); + write_reg8(AH, read_reg8(AH) - 1); + *flags |= FLAG_ADJUST | 1 + } + else { + *flags &= !FLAG_ADJUST & !1 + } + write_reg8(AL, read_reg8(AL) & 15); + *flags_changed &= !FLAG_ADJUST & !1; +} +unsafe fn and(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 { + let result = dest_operand & source_operand; + *last_result = result; + *last_op_size = op_size; + *flags &= !1 & !FLAG_OVERFLOW & !FLAG_ADJUST; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW & !FLAG_ADJUST; + return result; +} +unsafe fn or(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 { + let result = dest_operand | source_operand; + *last_result = result; + *last_op_size = op_size; + *flags &= !1 & !FLAG_OVERFLOW & !FLAG_ADJUST; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW & !FLAG_ADJUST; + return result; +} +unsafe fn xor(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 { + let result = dest_operand ^ source_operand; + *last_result = result; + *last_op_size = op_size; + *flags &= !1 & !FLAG_OVERFLOW & !FLAG_ADJUST; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW & !FLAG_ADJUST; + return result; +} +pub unsafe fn and8(x: i32, y: i32) -> i32 { return and(x, y, OPSIZE_8); } +#[no_mangle] +pub unsafe fn and16(x: i32, y: i32) -> i32 { return and(x, y, OPSIZE_16); } +pub unsafe fn and32(x: i32, y: i32) -> i32 { return and(x, y, OPSIZE_32); } +pub unsafe fn test8(x: i32, y: i32) { and(x, y, OPSIZE_8); } +pub unsafe fn test16(x: i32, y: i32) { and(x, y, OPSIZE_16); } +pub unsafe fn test32(x: i32, y: i32) { and(x, y, OPSIZE_32); } +pub unsafe fn or8(x: i32, y: i32) -> i32 { return or(x, y, OPSIZE_8); } +#[no_mangle] +pub unsafe fn or16(x: i32, y: i32) -> i32 { return or(x, y, OPSIZE_16); } +pub unsafe fn or32(x: i32, y: i32) -> i32 { return or(x, y, OPSIZE_32); } +pub unsafe fn xor8(x: i32, y: i32) -> i32 { return xor(x, y, OPSIZE_8); } +#[no_mangle] +pub unsafe fn xor16(x: i32, y: i32) -> i32 { return xor(x, y, OPSIZE_16); } +pub unsafe fn xor32(x: i32, y: i32) -> i32 { return xor(x, y, OPSIZE_32); } + +#[no_mangle] +pub unsafe fn rol8(dest_operand: i32, mut count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if 0 == count { + return dest_operand; + } + else { + count &= 7; + let result = dest_operand << count | dest_operand >> 8 - count; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result & 1 + | (result << 11 ^ result << 4) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn rol16(dest_operand: i32, mut count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if 0 == count { + return dest_operand; + } + else { + count &= 15; + let result = dest_operand << count | dest_operand >> 16 - count; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result & 1 + | (result << 11 ^ result >> 4) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn rol32(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if 0 == count { + return dest_operand; + } + else { + let result = ((dest_operand << count) as u32 | dest_operand as u32 >> 32 - count) as i32; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result & 1 + | (result << 11 ^ result >> 20) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn rcl8(dest_operand: i32, mut count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + count %= 9; + if 0 == count { + return dest_operand; + } + else { + let result = + dest_operand << count | (getcf() as i32) << count - 1 | dest_operand >> 9 - count; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result >> 8 & 1 + | (result << 3 ^ result << 4) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn rcl16(dest_operand: i32, mut count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + count %= 17; + if 0 == count { + return dest_operand; + } + else { + let result = + dest_operand << count | (getcf() as i32) << count - 1 | dest_operand >> 17 - count; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result >> 16 & 1 + | (result >> 5 ^ result >> 4) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn rcl32(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if 0 == count { + return dest_operand; + } + else { + let mut result: i32 = dest_operand << count | (getcf() as i32) << count - 1; + if count > 1 { + result = (result as u32 | dest_operand as u32 >> 33 - count) as i32 + } + *flags_changed &= !1 & !FLAG_OVERFLOW; + let b = (dest_operand as u32 >> 32 - count & 1) as i32; + *flags = (*flags & !1 & !FLAG_OVERFLOW | b) | (b << 11 ^ result >> 20) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn ror8(dest_operand: i32, mut count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if 0 == count { + return dest_operand; + } + else { + count &= 7; + let result = dest_operand >> count | dest_operand << 8 - count; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result >> 7 & 1 + | (result << 4 ^ result << 5) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn ror16(dest_operand: i32, mut count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if 0 == count { + return dest_operand; + } + else { + count &= 15; + let result = dest_operand >> count | dest_operand << 16 - count; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result >> 15 & 1 + | (result >> 4 ^ result >> 3) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn ror32(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if 0 == count { + return dest_operand; + } + else { + let result = (dest_operand as u32 >> count | (dest_operand << 32 - count) as u32) as i32; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result >> 31 & 1 + | (result >> 20 ^ result >> 19) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn rcr8(dest_operand: i32, mut count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + count %= 9; + if 0 == count { + return dest_operand; + } + else { + let result = + dest_operand >> count | (getcf() as i32) << 8 - count | dest_operand << 9 - count; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result >> 8 & 1 + | (result << 4 ^ result << 5) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn rcr16(dest_operand: i32, mut count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + count %= 17; + if 0 == count { + return dest_operand; + } + else { + let result = + dest_operand >> count | (getcf() as i32) << 16 - count | dest_operand << 17 - count; + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result >> 16 & 1 + | (result >> 4 ^ result >> 3) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn rcr32(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if 0 == count { + return dest_operand; + } + else { + let mut result: i32 = + (dest_operand as u32 >> count | ((getcf() as i32) << 32 - count) as u32) as i32; + if count > 1 { + result |= dest_operand << 33 - count + } + *flags_changed &= !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | dest_operand >> count - 1 & 1 + | (result >> 20 ^ result >> 19) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn div8(source_operand: u32) { + if source_operand == 0 { + trigger_de(); + return; + } + let target_operand = read_reg16(AX) as u32; + let result = target_operand / source_operand; + if result >= 0x100 { + trigger_de(); + return; + } + write_reg8(AL, result as i32); + write_reg8(AH, (target_operand % source_operand) as i32); +} + +#[no_mangle] +pub unsafe fn idiv8(source_operand: i32) { + if source_operand == 0 { + trigger_de(); + return; + } + let target_operand = read_reg16(AX) << 16 >> 16; + let result = target_operand / source_operand; + if result >= 0x80 || result < -0x80 { + trigger_de(); + return; + } + write_reg8(AL, result); + write_reg8(AH, target_operand % source_operand); +} + +#[no_mangle] +pub unsafe fn div16_without_fault(source_operand: u32) -> bool { + let target_operand = (read_reg16(AX) | read_reg16(DX) << 16) as u32; + let result = match target_operand.checked_div(source_operand) { + None => return false, + Some(r) => r, + }; + if result >= 0x10000 { + return false; + } + write_reg16(AX, result as i32); + write_reg16(DX, (target_operand % source_operand) as i32); + return true; +} +pub unsafe fn div16(source_operand: u32) { + if !div16_without_fault(source_operand) { + trigger_de() + } +} +#[no_mangle] +pub unsafe fn idiv16_without_fault(source_operand: i32) -> bool { + let target_operand = read_reg16(AX) | read_reg16(DX) << 16; + let result = match target_operand.checked_div(source_operand) { + None => return false, + Some(r) => r, + }; + if result >= 0x8000 || result < -0x8000 { + return false; + } + write_reg16(AX, result); + write_reg16(DX, (target_operand % source_operand) as i32); + return true; +} +pub unsafe fn idiv16(source_operand: i32) { + if !idiv16_without_fault(source_operand) { + trigger_de() + } +} + +#[no_mangle] +pub unsafe fn div32_without_fault(source_operand: u32) -> bool { + let source_operand = source_operand as u64; + let target_low = read_reg32(EAX) as u32; + let target_high = read_reg32(EDX) as u32; + let target_operand = (target_high as u64) << 32 | target_low as u64; + let result = match target_operand.checked_div(source_operand) { + None => return false, + Some(r) => r, + }; + if result > 0xFFFFFFFF { + return false; + } + let modulo = target_operand % source_operand; + write_reg32(EAX, result as i32); + write_reg32(EDX, modulo as i32); + return true; +} +pub unsafe fn div32(source_operand: u32) { + if !div32_without_fault(source_operand) { + trigger_de() + } +} +#[no_mangle] +pub unsafe fn idiv32_without_fault(source_operand: i32) -> bool { + let source_operand = source_operand as i64; + let target_low = read_reg32(EAX) as u32; + let target_high = read_reg32(EDX) as u32; + let target_operand = (target_high as i64) << 32 | target_low as i64; + let result = match target_operand.checked_div(source_operand) { + None => return false, + Some(r) => r, + }; + if result < -0x80000000 || result > 0x7FFFFFFF { + return false; + } + let modulo = target_operand % source_operand; + write_reg32(EAX, result as i32); + write_reg32(EDX, modulo as i32); + return true; +} +pub unsafe fn idiv32(source_operand: i32) { + if !idiv32_without_fault(source_operand) { + trigger_de() + } +} + +#[no_mangle] +pub unsafe fn shl8(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result = dest_operand << count; + *last_result = result; + *last_op_size = OPSIZE_8; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result >> 8 & 1 + | (result << 3 ^ result << 4) & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn shl16(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result = dest_operand << count; + *last_result = result; + *last_op_size = OPSIZE_16; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | result >> 16 & 1 + | (result >> 5 ^ result >> 4) & FLAG_OVERFLOW; + return result; + }; +} +pub unsafe fn shl32(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result = dest_operand << count; + *last_result = result; + *last_op_size = OPSIZE_32; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + let b = dest_operand >> 32 - count & 1; + *flags = *flags & !1 & !FLAG_OVERFLOW | b | (b ^ result >> 31) << 11 & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn shr8(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result = dest_operand >> count; + *last_result = result; + *last_op_size = OPSIZE_8; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | dest_operand >> count - 1 & 1 + | (dest_operand >> 7 & 1) << 11 & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn shr16(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result = dest_operand >> count; + *last_result = result; + *last_op_size = OPSIZE_16; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = *flags & !1 & !FLAG_OVERFLOW + | dest_operand >> count - 1 & 1 + | dest_operand >> 4 & FLAG_OVERFLOW; + return result; + }; +} +pub unsafe fn shr32(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result = (dest_operand as u32 >> count) as i32; + *last_result = result; + *last_op_size = OPSIZE_32; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = (*flags & !1 & !FLAG_OVERFLOW) + | (dest_operand as u32 >> count - 1 & 1) as i32 + | (dest_operand >> 20 & FLAG_OVERFLOW); + return result; + }; +} +#[no_mangle] +pub unsafe fn sar8(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result; + if count < 8 { + result = dest_operand << 24 >> count + 24; + // of is zero + *flags = *flags & !1 & !FLAG_OVERFLOW | dest_operand >> count - 1 & 1 + } + else { + result = dest_operand << 24 >> 31; + *flags = *flags & !1 & !FLAG_OVERFLOW | result & 1 + } + *last_result = result; + *last_op_size = OPSIZE_8; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn sar16(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result; + if count < 16 { + result = dest_operand << 16 >> count + 16; + *flags = *flags & !1 & !FLAG_OVERFLOW | dest_operand >> count - 1 & 1 + } + else { + result = dest_operand << 16 >> 31; + *flags = *flags & !1 & !FLAG_OVERFLOW | result & 1 + } + *last_result = result; + *last_op_size = OPSIZE_16; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + return result; + }; +} +pub unsafe fn sar32(dest_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result = dest_operand >> count; + *last_result = result; + *last_op_size = OPSIZE_32; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = (*flags & !1 & !FLAG_OVERFLOW) | (dest_operand as u32 >> count - 1 & 1) as i32; + return result; + }; +} + +#[no_mangle] +pub unsafe fn shrd16(dest_operand: i32, source_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result; + if count <= 16 { + result = dest_operand >> count | source_operand << 16 - count; + *flags = *flags & !1 | dest_operand >> count - 1 & 1 + } + else { + result = dest_operand << 32 - count | source_operand >> count - 16; + *flags = *flags & !1 | source_operand >> count - 17 & 1 + } + *last_result = result; + *last_op_size = OPSIZE_16; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = *flags & !FLAG_OVERFLOW | (result ^ dest_operand) >> 4 & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn shrd32(dest_operand: i32, source_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result = (dest_operand as u32 >> count | (source_operand << 32 - count) as u32) as i32; + *last_result = result; + *last_op_size = OPSIZE_32; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = ((*flags & !1 & !FLAG_OVERFLOW) | (dest_operand as u32 >> count - 1 & 1) as i32) + | (result ^ dest_operand) >> 20 & FLAG_OVERFLOW; + return result; + }; +} +#[no_mangle] +pub unsafe fn shld16(dest_operand: i32, source_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result; + if count <= 16 { + result = ((dest_operand << count) as u32 | source_operand as u32 >> 16 - count) as i32; + *flags = (*flags & !1) | (dest_operand as u32 >> 16 - count & 1) as i32; + } + else { + result = dest_operand >> 32 - count | source_operand << count - 16; + *flags = (*flags & !1) | (source_operand as u32 >> 32 - count & 1) as i32; + } + *last_result = result; + *last_op_size = OPSIZE_16; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = *flags & !FLAG_OVERFLOW | (*flags & 1 ^ result >> 15 & 1) << 11; + return result; + }; +} +#[no_mangle] +pub unsafe fn shld32(dest_operand: i32, source_operand: i32, count: i32) -> i32 { + dbg_assert!(count >= 0 && count < 32); + if count == 0 { + return dest_operand; + } + else { + let result = ((dest_operand << count) as u32 | source_operand as u32 >> 32 - count) as i32; + *last_result = result; + *last_op_size = OPSIZE_32; + *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW; + *flags = (*flags & !1) | (dest_operand as u32 >> 32 - count & 1) as i32; + if count == 1 { + *flags = *flags & !FLAG_OVERFLOW | (*flags & 1 ^ result >> 31 & 1) << 11 + } + else { + *flags &= !FLAG_OVERFLOW + } + return result; + }; +} + +pub unsafe fn bt_reg(bit_base: i32, bit_offset: i32) { + *flags = *flags & !1 | bit_base >> bit_offset & 1; + *flags_changed &= !1; +} +pub unsafe fn btc_reg(bit_base: i32, bit_offset: i32) -> i32 { + *flags = *flags & !1 | bit_base >> bit_offset & 1; + *flags_changed &= !1; + return bit_base ^ 1 << bit_offset; +} +pub unsafe fn bts_reg(bit_base: i32, bit_offset: i32) -> i32 { + *flags = *flags & !1 | bit_base >> bit_offset & 1; + *flags_changed &= !1; + return bit_base | 1 << bit_offset; +} +pub unsafe fn btr_reg(bit_base: i32, bit_offset: i32) -> i32 { + *flags = *flags & !1 | bit_base >> bit_offset & 1; + *flags_changed &= !1; + return bit_base & !(1 << bit_offset); +} + +pub unsafe fn bt_mem(virt_addr: i32, mut bit_offset: i32) { + let bit_base = return_on_pagefault!(safe_read8(virt_addr + (bit_offset >> 3))); + bit_offset &= 7; + *flags = *flags & !1 | bit_base >> bit_offset & 1; + *flags_changed &= !1; +} +pub unsafe fn btc_mem(virt_addr: i32, mut bit_offset: i32) { + let phys_addr = return_on_pagefault!(translate_address_write(virt_addr + (bit_offset >> 3))); + let bit_base = read8(phys_addr); + bit_offset &= 7; + *flags = *flags & !1 | bit_base >> bit_offset & 1; + *flags_changed &= !1; + write8(phys_addr, bit_base ^ 1 << bit_offset); +} +pub unsafe fn btr_mem(virt_addr: i32, mut bit_offset: i32) { + let phys_addr = return_on_pagefault!(translate_address_write(virt_addr + (bit_offset >> 3))); + let bit_base = read8(phys_addr); + bit_offset &= 7; + *flags = *flags & !1 | bit_base >> bit_offset & 1; + *flags_changed &= !1; + write8(phys_addr, bit_base & !(1 << bit_offset)); +} +pub unsafe fn bts_mem(virt_addr: i32, mut bit_offset: i32) { + let phys_addr = return_on_pagefault!(translate_address_write(virt_addr + (bit_offset >> 3))); + let bit_base = read8(phys_addr); + bit_offset &= 7; + *flags = *flags & !1 | bit_base >> bit_offset & 1; + *flags_changed &= !1; + write8(phys_addr, bit_base | 1 << bit_offset); +} + +#[no_mangle] +pub unsafe fn bsf16(old: i32, bit_base: i32) -> i32 { + *flags_changed = FLAGS_ALL & !FLAG_ZERO & !FLAG_CARRY; + *flags &= !FLAG_CARRY; + *last_op_size = OPSIZE_16; + if bit_base == 0 { + *flags |= FLAG_ZERO; + *last_result = bit_base; + // not defined in the docs, but value doesn't change on my intel machine + return old; + } + else { + *flags &= !FLAG_ZERO; + *last_result = int_log2(-bit_base & bit_base); + return *last_result; + }; +} +#[no_mangle] +pub unsafe fn bsf32(old: i32, bit_base: i32) -> i32 { + *flags_changed = FLAGS_ALL & !FLAG_ZERO & !FLAG_CARRY; + *flags &= !FLAG_CARRY; + *last_op_size = OPSIZE_32; + if bit_base == 0 { + *flags |= FLAG_ZERO; + *last_result = bit_base; + return old; + } + else { + *flags &= !FLAG_ZERO; + *last_result = int_log2(-bit_base & bit_base); + return *last_result; + }; +} +#[no_mangle] +pub unsafe fn bsr16(old: i32, bit_base: i32) -> i32 { + *flags_changed = FLAGS_ALL & !FLAG_ZERO & !FLAG_CARRY; + *flags &= !FLAG_CARRY; + *last_op_size = OPSIZE_16; + if bit_base == 0 { + *flags |= FLAG_ZERO; + *last_result = bit_base; + return old; + } + else { + *flags &= !FLAG_ZERO; + *last_result = int_log2(bit_base); + return *last_result; + }; +} +#[no_mangle] +pub unsafe fn bsr32(old: i32, bit_base: i32) -> i32 { + *flags_changed = FLAGS_ALL & !FLAG_ZERO & !FLAG_CARRY; + *flags &= !FLAG_CARRY; + *last_op_size = OPSIZE_32; + if bit_base == 0 { + *flags |= FLAG_ZERO; + *last_result = bit_base; + return old; + } + else { + *flags &= !FLAG_ZERO; + *last_result = int_log2(bit_base); + return *last_result; + }; +} +#[no_mangle] +pub unsafe fn popcnt(v: i32) -> i32 { + *flags_changed = 0; + *flags &= !FLAGS_ALL; + if 0 != v { + return v.count_ones() as i32; + } + else { + *flags |= FLAG_ZERO; + return 0; + }; +} + +pub unsafe fn saturate_sw_to_ub(v: u16) -> u8 { + let mut ret = v; + if ret >= 32768 { + ret = 0 + } + else if ret > 255 { + ret = 255 + } + return ret as u8; +} +pub unsafe fn saturate_sw_to_sb(v: i32) -> u8 { + dbg_assert!(v as u32 & 0xFFFF_0000 == 0); + let mut ret: i32 = v; + if ret > 65408 { + ret = ret & 255 + } + else if ret > 32767 { + ret = 128 + } + else if ret > 127 { + ret = 127 + } + dbg_assert!(ret as u32 & 0xFFFF_FF00 == 0); + return ret as u8; +} +pub unsafe fn saturate_sd_to_sw(v: u32) -> u16 { + let mut ret: u32 = v; + if ret > 4294934528 { + ret = ret & 0xFFFF + } + else if ret > 0x7FFFFFFF { + ret = 32768 + } + else if ret > 32767 { + ret = 32767 + } + dbg_assert!(ret & 0xFFFF_0000 == 0); + return ret as u16; +} +pub unsafe fn saturate_sd_to_sb(v: u32) -> i8 { + let mut ret: u32 = v; + if ret > 0xFFFFFF80 { + ret = ret & 255 + } + else if ret > 0x7FFFFFFF { + ret = 128 + } + else if ret > 127 { + ret = 127 + } + dbg_assert!(ret & 0xFFFF_FF00 == 0); + return ret as i8; +} +pub unsafe fn saturate_sd_to_ub(v: i32) -> i32 { + let mut ret: i32 = v; + if ret < 0 { + ret = 0 + } + dbg_assert!(ret as u32 & 0xFFFF_FF00 == 0); + return ret; +} +pub unsafe fn saturate_ud_to_ub(v: u32) -> u8 { + let mut ret: u32 = v; + if ret > 255 { + ret = 255 + } + dbg_assert!(ret & 0xFFFF_FF00 == 0); + return ret as u8; +} +pub unsafe fn saturate_uw(v: u32) -> u16 { + let mut ret: u32 = v; + if ret > 0x7FFFFFFF { + ret = 0 + } + else if ret > 0xFFFF { + ret = 0xFFFF + } + dbg_assert!(ret & 0xFFFF_0000 == 0); + return ret as u16; +} diff --git a/src/rust/cpu/call_indirect.rs b/src/rust/cpu/call_indirect.rs new file mode 100644 index 0000000..d38a6c0 --- /dev/null +++ b/src/rust/cpu/call_indirect.rs @@ -0,0 +1,2 @@ +#[no_mangle] +pub fn call_indirect1(f: fn(u16), x: u16) { f(x); } diff --git a/src/rust/cpu/cpu.rs b/src/rust/cpu/cpu.rs new file mode 100644 index 0000000..b12f144 --- /dev/null +++ b/src/rust/cpu/cpu.rs @@ -0,0 +1,4330 @@ +#![allow(non_upper_case_globals)] + +extern "C" { + fn cpu_exception_hook(interrupt: i32) -> bool; + fn microtick() -> f64; + fn call_indirect1(f: i32, x: u16); + fn pic_acknowledge(); + + pub fn io_port_read8(port: i32) -> i32; + pub fn io_port_read16(port: i32) -> i32; + pub fn io_port_read32(port: i32) -> i32; + + pub fn io_port_write8(port: i32, value: i32); + pub fn io_port_write16(port: i32, value: i32); + pub fn io_port_write32(port: i32, value: i32); +} + +use cpu::fpu::fpu_set_tag_word; +use cpu::global_pointers::*; +use cpu::memory; +use cpu::memory::mem8; +use cpu::memory::{in_mapped_range, read8, read16, read32s, read64s, read128, write8}; +use cpu::misc_instr::{ + adjust_stack_reg, get_stack_pointer, getaf, getcf, getof, getpf, getsf, getzf, pop16, pop32s, + push16, push32, +}; +use cpu::modrm::{resolve_modrm16, resolve_modrm32}; +use jit; +use jit::is_near_end_of_page; +use page::Page; +use paging::OrPageFault; +use profiler; +use profiler::stat::*; +use state_flags::CachedStateFlags; +use std::collections::HashSet; +use std::ptr::NonNull; +pub use util::dbg_trace; + +/// The offset for our generated functions in the wasm table. Every index less than this is +/// reserved for rustc's indirect functions +pub const WASM_TABLE_OFFSET: u32 = 1024; + +#[derive(Copy, Clone)] +#[repr(C)] +pub union reg128 { + pub i8: [i8; 16], + pub i16: [i16; 8], + pub i32: [i32; 4], + pub i64: [i64; 2], + pub u8: [u8; 16], + pub u16: [u16; 8], + pub u32: [u32; 4], + pub u64: [u64; 2], + pub f32: [f32; 4], + pub f64: [f64; 2], +} + +pub const CHECK_MISSED_ENTRY_POINTS: bool = false; + +pub const INTERPRETER_ITERATION_LIMIT: u32 = 100_001; + +pub const FLAG_SUB: i32 = -0x8000_0000; +pub const FLAG_CARRY: i32 = 1; +pub const FLAG_PARITY: i32 = 4; +pub const FLAG_ADJUST: i32 = 16; +pub const FLAG_ZERO: i32 = 64; +pub const FLAG_SIGN: i32 = 128; +pub const FLAG_TRAP: i32 = 256; +pub const FLAG_INTERRUPT: i32 = 512; +pub const FLAG_DIRECTION: i32 = 1024; +pub const FLAG_OVERFLOW: i32 = 2048; +pub const FLAG_IOPL: i32 = 1 << 12 | 1 << 13; +pub const FLAG_NT: i32 = 1 << 14; +pub const FLAG_RF: i32 = 1 << 16; +pub const FLAG_VM: i32 = 1 << 17; +pub const FLAG_AC: i32 = 1 << 18; +pub const FLAG_VIF: i32 = 1 << 19; +pub const FLAG_VIP: i32 = 1 << 20; +pub const FLAG_ID: i32 = 1 << 21; +pub const FLAGS_DEFAULT: i32 = 1 << 1; +pub const FLAGS_MASK: i32 = FLAG_CARRY + | FLAG_PARITY + | FLAG_ADJUST + | FLAG_ZERO + | FLAG_SIGN + | FLAG_TRAP + | FLAG_INTERRUPT + | FLAG_DIRECTION + | FLAG_OVERFLOW + | FLAG_IOPL + | FLAG_NT + | FLAG_RF + | FLAG_VM + | FLAG_AC + | FLAG_VIF + | FLAG_VIP + | FLAG_ID; +pub const FLAGS_ALL: i32 = + FLAG_CARRY | FLAG_PARITY | FLAG_ADJUST | FLAG_ZERO | FLAG_SIGN | FLAG_OVERFLOW; +pub const OPSIZE_8: i32 = 7; +pub const OPSIZE_16: i32 = 15; +pub const OPSIZE_32: i32 = 31; + +pub const EAX: i32 = 0; +pub const ECX: i32 = 1; +pub const EDX: i32 = 2; +pub const EBX: i32 = 3; +pub const ESP: i32 = 4; +pub const EBP: i32 = 5; +pub const ESI: i32 = 6; +pub const EDI: i32 = 7; + +pub const AX: i32 = 0; +pub const CX: i32 = 1; +pub const DX: i32 = 2; +pub const BX: i32 = 3; +pub const SP: i32 = 4; +pub const BP: i32 = 5; +pub const SI: i32 = 6; +pub const DI: i32 = 7; + +pub const AL: i32 = 0; +pub const CL: i32 = 1; +pub const DL: i32 = 2; +pub const BL: i32 = 3; +pub const AH: i32 = 4; +pub const CH: i32 = 5; +pub const DH: i32 = 6; +pub const BH: i32 = 7; + +pub const ES: i32 = 0; +pub const CS: i32 = 1; +pub const SS: i32 = 2; +pub const DS: i32 = 3; +pub const FS: i32 = 4; +pub const GS: i32 = 5; +pub const TR: i32 = 6; + +pub const LDTR: i32 = 7; +pub const PAGE_TABLE_PRESENT_MASK: i32 = 1 << 0; +pub const PAGE_TABLE_RW_MASK: i32 = 1 << 1; +pub const PAGE_TABLE_USER_MASK: i32 = 1 << 2; +pub const PAGE_TABLE_ACCESSED_MASK: i32 = 1 << 5; +pub const PAGE_TABLE_DIRTY_MASK: i32 = 1 << 6; +pub const PAGE_TABLE_PSE_MASK: i32 = 1 << 7; +pub const PAGE_TABLE_GLOBAL_MASK: i32 = 1 << 8; +pub const MMAP_BLOCK_BITS: i32 = 17; +pub const MMAP_BLOCK_SIZE: i32 = 1 << MMAP_BLOCK_BITS; +pub const CR0_PE: i32 = 1; +pub const CR0_MP: i32 = 1 << 1; +pub const CR0_EM: i32 = 1 << 2; +pub const CR0_TS: i32 = 1 << 3; +pub const CR0_ET: i32 = 1 << 4; +pub const CR0_WP: i32 = 1 << 16; +pub const CR0_AM: i32 = 1 << 18; +pub const CR0_NW: i32 = 1 << 29; +pub const CR0_CD: i32 = 1 << 30; +pub const CR0_PG: i32 = 1 << 31; +pub const CR4_VME: i32 = 1; +pub const CR4_PVI: i32 = 1 << 1; +pub const CR4_TSD: i32 = 1 << 2; +pub const CR4_PSE: i32 = 1 << 4; +pub const CR4_DE: i32 = 1 << 3; +pub const CR4_PAE: i32 = 1 << 5; +pub const CR4_PGE: i32 = 1 << 7; +pub const CR4_OSFXSR: i32 = 1 << 9; +pub const CR4_OSXMMEXCPT: i32 = 1 << 10; +pub const CR4_SMEP: i32 = 1 << 20; + +pub const TSR_BACKLINK: i32 = 0x00; +pub const TSR_CR3: i32 = 0x1C; +pub const TSR_EIP: i32 = 0x20; +pub const TSR_EFLAGS: i32 = 0x24; + +pub const TSR_EAX: i32 = 0x28; +pub const TSR_ECX: i32 = 0x2c; +pub const TSR_EDX: i32 = 0x30; +pub const TSR_EBX: i32 = 0x34; +pub const TSR_ESP: i32 = 0x38; +pub const TSR_EBP: i32 = 0x3c; +pub const TSR_ESI: i32 = 0x40; +pub const TSR_EDI: i32 = 0x44; + +pub const TSR_ES: i32 = 0x48; +pub const TSR_CS: i32 = 0x4c; +pub const TSR_SS: i32 = 0x50; +pub const TSR_DS: i32 = 0x54; +pub const TSR_FS: i32 = 0x58; +pub const TSR_GS: i32 = 0x5c; +pub const TSR_LDT: i32 = 0x60; + +pub const IA32_TIME_STAMP_COUNTER: i32 = 0x10; +pub const IA32_PLATFORM_ID: i32 = 0x17; +pub const IA32_APIC_BASE: i32 = 0x1B; +pub const MSR_TEST_CTRL: i32 = 0x33; +pub const MSR_SMI_COUNT: i32 = 0x34; +pub const IA32_FEAT_CTL: i32 = 0x3A; +pub const IA32_SPEC_CTRL: i32 = 0x48; +pub const IA32_BIOS_SIGN_ID: i32 = 0x8B; +pub const MSR_PLATFORM_INFO: i32 = 0xCE; +pub const MSR_TSX_FORCE_ABORT: i32 = 0x10F; +pub const IA32_TSX_CTRL: i32 = 0x122; +pub const IA32_MCU_OPT_CTRL: i32 = 0x123; +pub const MISC_FEATURE_ENABLES: i32 = 0x140; +pub const IA32_SYSENTER_CS: i32 = 0x174; +pub const IA32_SYSENTER_ESP: i32 = 0x175; +pub const IA32_SYSENTER_EIP: i32 = 0x176; +pub const IA32_MCG_CAP: i32 = 0x179; +pub const IA32_MISC_ENABLE: i32 = 0x1A0; +pub const IA32_PAT: i32 = 0x277; +pub const IA32_RTIT_CTL: i32 = 0x570; +pub const MSR_PKG_C2_RESIDENCY: i32 = 0x60D; +pub const IA32_KERNEL_GS_BASE: i32 = 0xC0000101u32 as i32; +pub const MSR_AMD64_LS_CFG: i32 = 0xC0011020u32 as i32; + +pub const IA32_APIC_BASE_BSP: i32 = 1 << 8; +pub const IA32_APIC_BASE_EXTD: i32 = 1 << 10; +pub const IA32_APIC_BASE_EN: i32 = 1 << 11; + +pub const APIC_ADDRESS: i32 = 0xFEE00000u32 as i32; +pub const SEG_PREFIX_NONE: i32 = -1; +pub const SEG_PREFIX_ZERO: i32 = 7; +pub const PREFIX_MASK_REP: i32 = 24; +pub const PREFIX_REPZ: i32 = 8; +pub const PREFIX_REPNZ: i32 = 16; +pub const PREFIX_MASK_SEGMENT: i32 = 7; +pub const PREFIX_MASK_OPSIZE: i32 = 32; +pub const PREFIX_MASK_ADDRSIZE: i32 = 64; +pub const PREFIX_F2: i32 = PREFIX_REPNZ; +pub const PREFIX_F3: i32 = PREFIX_REPZ; +pub const PREFIX_66: i32 = PREFIX_MASK_OPSIZE; + +pub const MXCSR_MASK: i32 = 0xffff; +pub const MXCSR_FZ: i32 = 1 << 15; +pub const MXCSR_DAZ: i32 = 1 << 6; +pub const MXCSR_RC_SHIFT: i32 = 13; + +pub const VALID_TLB_ENTRY_MAX: i32 = 10000; +pub const TLB_VALID: i32 = 1 << 0; +pub const TLB_READONLY: i32 = 1 << 1; +pub const TLB_NO_USER: i32 = 1 << 2; +pub const TLB_IN_MAPPED_RANGE: i32 = 1 << 3; +pub const TLB_GLOBAL: i32 = 1 << 4; +pub const TLB_HAS_CODE: i32 = 1 << 5; +pub const IVT_SIZE: u32 = 0x400; +pub const CPU_EXCEPTION_DE: i32 = 0; +pub const CPU_EXCEPTION_DB: i32 = 1; +pub const CPU_EXCEPTION_NMI: i32 = 2; +pub const CPU_EXCEPTION_BP: i32 = 3; +pub const CPU_EXCEPTION_OF: i32 = 4; +pub const CPU_EXCEPTION_BR: i32 = 5; +pub const CPU_EXCEPTION_UD: i32 = 6; +pub const CPU_EXCEPTION_NM: i32 = 7; +pub const CPU_EXCEPTION_DF: i32 = 8; +pub const CPU_EXCEPTION_TS: i32 = 10; +pub const CPU_EXCEPTION_NP: i32 = 11; +pub const CPU_EXCEPTION_SS: i32 = 12; +pub const CPU_EXCEPTION_GP: i32 = 13; +pub const CPU_EXCEPTION_PF: i32 = 14; +pub const CPU_EXCEPTION_MF: i32 = 16; +pub const CPU_EXCEPTION_AC: i32 = 17; +pub const CPU_EXCEPTION_MC: i32 = 18; +pub const CPU_EXCEPTION_XM: i32 = 19; +pub const CPU_EXCEPTION_VE: i32 = 20; + +pub const CHECK_TLB_INVARIANTS: bool = false; + +pub const DEBUG: bool = cfg!(debug_assertions); + +pub const LOOP_COUNTER: i32 = 100_003; +pub const TSC_RATE: f64 = 1_000_000.0; + +pub static mut cpuid_level: u32 = 0x16; + +pub static mut jit_block_boundary: bool = false; + +pub static mut rdtsc_imprecision_offset: u64 = 0; +pub static mut rdtsc_last_value: u64 = 0; +pub static mut tsc_offset: u64 = 0; + +pub struct Code { + pub wasm_table_index: jit::WasmTableIndex, + pub state_flags: CachedStateFlags, + pub state_table: [u16; 0x1000], +} + +pub static mut tlb_data: [i32; 0x100000] = [0; 0x100000]; +pub static mut tlb_code: [Option>; 0x100000] = [None; 0x100000]; + +pub static mut valid_tlb_entries: [i32; 10000] = [0; 10000]; +pub static mut valid_tlb_entries_count: i32 = 0; + +pub static mut in_jit: bool = false; + +pub static mut jit_fault: Option<(i32, Option)> = None; + +pub enum LastJump { + Interrupt { + phys_addr: u32, + int: u8, + software: bool, + error: Option, + }, + Compiled { + phys_addr: u32, + }, + Interpreted { + phys_addr: u32, + }, + None, +} +impl LastJump { + pub fn phys_address(&self) -> Option { + match self { + LastJump::Interrupt { phys_addr, .. } => Some(*phys_addr), + LastJump::Compiled { phys_addr } => Some(*phys_addr), + LastJump::Interpreted { phys_addr } => Some(*phys_addr), + LastJump::None => None, + } + } + pub fn name(&self) -> &'static str { + match self { + LastJump::Interrupt { .. } => "interrupt", + LastJump::Compiled { .. } => "compiled", + LastJump::Interpreted { .. } => "interpreted", + LastJump::None => "none", + } + } +} +pub static mut debug_last_jump: LastJump = LastJump::None; + +#[derive(Copy, Clone)] +pub struct SegmentSelector { + raw: u16, +} + +impl SegmentSelector { + pub fn of_u16(raw: u16) -> SegmentSelector { SegmentSelector { raw } } + pub fn rpl(&self) -> u8 { (self.raw & 3) as u8 } + pub fn is_gdt(&self) -> bool { (self.raw & 4) == 0 } + pub fn descriptor_offset(&self) -> u16 { (self.raw & !7) as u16 } + + pub fn is_null(&self) -> bool { self.is_gdt() && self.descriptor_offset() == 0 } +} + +// Used to indicate early that the selector cannot be used to fetch a descriptor +#[derive(PartialEq)] +pub enum SelectorNullOrInvalid { + IsNull, + OutsideOfTableLimit, +} + +pub struct SegmentDescriptor { + pub raw: u64, +} + +impl SegmentDescriptor { + pub fn of_u64(raw: u64) -> SegmentDescriptor { SegmentDescriptor { raw } } + pub fn base(&self) -> i32 { + ((self.raw >> 16) & 0xffff | (self.raw & 0xff_00000000) >> 16 | (self.raw >> 56 << 24)) + as i32 + } + pub fn limit(&self) -> u32 { (self.raw & 0xffff | ((self.raw >> 48) & 0xf) << 16) as u32 } + pub fn access_byte(&self) -> u8 { ((self.raw >> 40) & 0xff) as u8 } + pub fn flags(&self) -> u8 { ((self.raw >> 48 >> 4) & 0xf) as u8 } + + pub fn is_system(&self) -> bool { self.access_byte() & 0x10 == 0 } + pub fn system_type(&self) -> u8 { self.access_byte() & 0xF } + + pub fn is_rw(&self) -> bool { self.access_byte() & 2 == 2 } + pub fn is_dc(&self) -> bool { self.access_byte() & 4 == 4 } + pub fn is_executable(&self) -> bool { self.access_byte() & 8 == 8 } + pub fn is_present(&self) -> bool { self.access_byte() & 0x80 == 0x80 } + pub fn is_writable(&self) -> bool { self.is_rw() && !self.is_executable() } + pub fn is_readable(&self) -> bool { self.is_rw() || !self.is_executable() } + pub fn is_conforming_executable(&self) -> bool { self.is_dc() && self.is_executable() } + pub fn dpl(&self) -> u8 { (self.access_byte() >> 5) & 3 } + pub fn is_32(&self) -> bool { self.flags() & 4 == 4 } + pub fn effective_limit(&self) -> u32 { + if self.flags() & 8 == 8 { self.limit() << 12 | 0xFFF } else { self.limit() } + } + pub fn set_busy(&self) -> SegmentDescriptor { + SegmentDescriptor { + raw: self.raw | 2 << 40, + } + } +} + +pub struct InterruptDescriptor { + raw: u64, +} + +impl InterruptDescriptor { + pub fn of_u64(raw: u64) -> InterruptDescriptor { InterruptDescriptor { raw } } + pub fn offset(&self) -> i32 { (self.raw & 0xffff | self.raw >> 32 & 0xffff0000) as i32 } + pub fn selector(&self) -> u16 { (self.raw >> 16 & 0xffff) as u16 } + pub fn access_byte(&self) -> u8 { (self.raw >> 40 & 0xff) as u8 } + pub fn dpl(&self) -> u8 { (self.access_byte() >> 5 & 3) as u8 } + pub fn gate_type(&self) -> u8 { self.access_byte() & 7 } + pub fn is_32(&self) -> bool { self.access_byte() & 8 == 8 } + pub fn is_present(&self) -> bool { self.access_byte() & 0x80 == 0x80 } + pub fn reserved_zeros_are_valid(&self) -> bool { self.access_byte() & 16 == 0 } + + const TASK_GATE: u8 = 0b101; + const INTERRUPT_GATE: u8 = 0b110; + const TRAP_GATE: u8 = 0b111; +} + +pub unsafe fn switch_cs_real_mode(selector: i32) { + dbg_assert!(!*protected_mode || vm86_mode()); + + *sreg.offset(CS as isize) = selector as u16; + *segment_is_null.offset(CS as isize) = false; + *segment_offsets.offset(CS as isize) = selector << 4; + update_cs_size(false); +} + +unsafe fn get_tss_ss_esp(dpl: u8) -> OrPageFault<(i32, i32)> { + Ok(if *tss_size_32 { + let tss_stack_offset = ((dpl << 3) + 4) as u32; + if tss_stack_offset + 7 > *segment_limits.offset(TR as isize) { + panic!("#TS handler"); + } + let addr = translate_address_system_read( + *segment_offsets.offset(TR as isize) + tss_stack_offset as i32, + )?; + dbg_assert!(addr & 0xFFF <= 0x1000 - 6); + (read16(addr + 4), read32s(addr)) + } + else { + let tss_stack_offset = ((dpl << 2) + 2) as u32; + if tss_stack_offset + 3 > *segment_limits.offset(TR as isize) { + panic!("#TS handler"); + } + let addr = translate_address_system_read( + *segment_offsets.offset(TR as isize) + tss_stack_offset as i32, + )?; + dbg_assert!(addr & 0xFFF <= 0x1000 - 4); + (read16(addr + 2), read16(addr)) + }) +} + +pub unsafe fn iret16() { iret(true); } +pub unsafe fn iret32() { iret(false); } + +pub unsafe fn iret(is_16: bool) { + if vm86_mode() && getiopl() < 3 { + // vm86 mode, iopl != 3 + dbg_log!("#gp iret vm86 mode, iopl != 3"); + trigger_gp(0); + return; + } + + let (new_eip, new_cs, mut new_flags) = if is_16 { + ( + return_on_pagefault!(safe_read16(get_stack_pointer(0))), + return_on_pagefault!(safe_read16(get_stack_pointer(2))), + return_on_pagefault!(safe_read16(get_stack_pointer(4))), + ) + } + else { + ( + return_on_pagefault!(safe_read32s(get_stack_pointer(0))), + return_on_pagefault!(safe_read16(get_stack_pointer(4))), + return_on_pagefault!(safe_read32s(get_stack_pointer(8))), + ) + }; + + if !*protected_mode || (vm86_mode() && getiopl() == 3) { + if new_eip as u32 & 0xFFFF0000 != 0 { + panic!("#GP handler"); + } + + switch_cs_real_mode(new_cs); + *instruction_pointer = get_seg_cs() + new_eip; + + if is_16 { + update_eflags(new_flags | *flags & !0xFFFF); + adjust_stack_reg(3 * 2); + } + else { + if !*protected_mode { + update_eflags((new_flags & 0x257FD5) | (*flags & 0x1A0000)); + } + else { + update_eflags(new_flags); + } + adjust_stack_reg(3 * 4); + } + + update_state_flags(); + handle_irqs(); + return; + } + + dbg_assert!(!vm86_mode()); + + if *flags & FLAG_NT != 0 { + if DEBUG { + panic!("NT"); + } + trigger_gp(0); + return; + } + + if new_flags & FLAG_VM != 0 { + if *cpl == 0 { + // return to virtual 8086 mode + + // vm86 cannot be set in 16 bit flag + dbg_assert!(!is_16); + + let temp_esp = return_on_pagefault!(safe_read32s(get_stack_pointer(12))); + let temp_ss = return_on_pagefault!(safe_read16(get_stack_pointer(16))); + + let new_es = return_on_pagefault!(safe_read16(get_stack_pointer(20))); + let new_ds = return_on_pagefault!(safe_read16(get_stack_pointer(24))); + let new_fs = return_on_pagefault!(safe_read16(get_stack_pointer(28))); + let new_gs = return_on_pagefault!(safe_read16(get_stack_pointer(32))); + + // no exceptions below + + update_eflags(new_flags); + *flags |= FLAG_VM; + + switch_cs_real_mode(new_cs); + *instruction_pointer = get_seg_cs() + (new_eip & 0xFFFF); + + if !switch_seg(ES, new_es) + || !switch_seg(DS, new_ds) + || !switch_seg(FS, new_fs) + || !switch_seg(GS, new_gs) + { + // XXX: Should be checked before side effects + dbg_assert!(false); + } + + adjust_stack_reg(9 * 4); // 9 dwords: eip, cs, flags, esp, ss, es, ds, fs, gs + + write_reg32(ESP, temp_esp); + if !switch_seg(SS, temp_ss) { + // XXX + dbg_assert!(false); + } + + *cpl = 3; + cpl_changed(); + + update_cs_size(false); + update_state_flags(); + + // iret end + return; + } + else { + dbg_log!("vm86 flag ignored because cpl != 0"); + new_flags &= !FLAG_VM; + } + } + + // protected mode return + + let cs_selector = SegmentSelector::of_u16(new_cs as u16); + let cs_descriptor = match return_on_pagefault!(lookup_segment_selector(cs_selector)) { + Ok((desc, _)) => desc, + Err(selector_unusable) => match selector_unusable { + SelectorNullOrInvalid::IsNull => { + panic!("Unimplemented: CS selector is null"); + }, + SelectorNullOrInvalid::OutsideOfTableLimit => { + panic!("Unimplemented: CS selector is invalid"); + }, + }, + }; + + if new_eip as u32 > cs_descriptor.effective_limit() { + dbg_log!( + "#gp iret: new_eip > cs_descriptor.effective_limit, new_eip={:x} cs_descriptor.effective_limit={:x}", + new_eip as u32, + cs_descriptor.effective_limit() + ); + trigger_gp(new_cs & !3); + return; + } + + if !cs_descriptor.is_present() { + panic!("not present"); + } + if !cs_descriptor.is_executable() { + panic!("not exec"); + } + if cs_selector.rpl() < *cpl { + panic!("rpl < cpl"); + } + if cs_descriptor.is_dc() && cs_descriptor.dpl() > cs_selector.rpl() { + panic!("conforming and dpl > rpl"); + } + + if !cs_descriptor.is_dc() && cs_selector.rpl() != cs_descriptor.dpl() { + dbg_log!( + "#gp iret: non-conforming cs and rpl != dpl, dpl={} rpl={}", + cs_descriptor.dpl(), + cs_selector.rpl() + ); + trigger_gp(new_cs & !3); + return; + } + + if cs_selector.rpl() > *cpl { + // outer privilege return + let (temp_esp, temp_ss) = if is_16 { + ( + return_on_pagefault!(safe_read16(get_stack_pointer(6))), + return_on_pagefault!(safe_read16(get_stack_pointer(8))), + ) + } + else { + ( + return_on_pagefault!(safe_read32s(get_stack_pointer(12))), + return_on_pagefault!(safe_read16(get_stack_pointer(16))), + ) + }; + + let ss_selector = SegmentSelector::of_u16(temp_ss as u16); + let ss_descriptor = match return_on_pagefault!(lookup_segment_selector(ss_selector)) { + Ok((desc, _)) => desc, + Err(selector_unusable) => match selector_unusable { + SelectorNullOrInvalid::IsNull => { + dbg_log!("#GP for loading 0 in SS sel={:x}", temp_ss); + dbg_trace(); + trigger_gp(0); + return; + }, + SelectorNullOrInvalid::OutsideOfTableLimit => { + dbg_log!("#GP for loading invalid in SS sel={:x}", temp_ss); + trigger_gp(temp_ss & !3); + return; + }, + }, + }; + let new_cpl = cs_selector.rpl(); + + if ss_descriptor.is_system() + || ss_selector.rpl() != new_cpl + || !ss_descriptor.is_writable() + || ss_descriptor.dpl() != new_cpl + { + dbg_log!("#GP for loading invalid in SS sel={:x}", temp_ss); + dbg_trace(); + trigger_gp(temp_ss & !3); + return; + } + + if !ss_descriptor.is_present() { + dbg_log!("#SS for loading non-present in SS sel={:x}", temp_ss); + dbg_trace(); + trigger_ss(temp_ss & !3); + return; + } + + // no exceptions below + + if is_16 { + update_eflags(new_flags | *flags & !0xFFFF); + } + else { + update_eflags(new_flags); + } + + *cpl = cs_selector.rpl(); + cpl_changed(); + + if !switch_seg(SS, temp_ss) { + // XXX + dbg_assert!(false); + } + + set_stack_reg(temp_esp); + + if *cpl == 0 && !is_16 { + *flags = *flags & !FLAG_VIF & !FLAG_VIP | (new_flags & (FLAG_VIF | FLAG_VIP)); + } + + // XXX: Set segment to 0 if it's not usable in the new cpl + // XXX: Use cached segment information + // ... + } + else if cs_selector.rpl() == *cpl { + // same privilege return + // no exceptions below + if is_16 { + adjust_stack_reg(3 * 2); + update_eflags(new_flags | *flags & !0xFFFF); + } + else { + adjust_stack_reg(3 * 4); + update_eflags(new_flags); + } + + // update vip and vif, which are not changed by update_eflags + if *cpl == 0 && !is_16 { + *flags = *flags & !FLAG_VIF & !FLAG_VIP | (new_flags & (FLAG_VIF | FLAG_VIP)); + } + } + else { + dbg_assert!(false); + } + + *sreg.offset(CS as isize) = new_cs as u16; + dbg_assert!((new_cs & 3) == *cpl as i32); + + update_cs_size(cs_descriptor.is_32()); + + *segment_limits.offset(CS as isize) = cs_descriptor.effective_limit(); + *segment_offsets.offset(CS as isize) = cs_descriptor.base(); + + *instruction_pointer = new_eip + get_seg_cs(); + + update_state_flags(); + + // iret end + + handle_irqs(); +} + +pub unsafe fn call_interrupt_vector( + interrupt_nr: i32, + is_software_int: bool, + error_code: Option, +) { + // we have to leave hlt_loop at some point, this is a + // good place to do it + *in_hlt = false; + + if *protected_mode { + if vm86_mode() && *cr.offset(4) & CR4_VME != 0 { + panic!("Unimplemented: VME"); + } + + if vm86_mode() && is_software_int && getiopl() < 3 { + dbg_log!("call_interrupt_vector #GP. vm86 && software int && iopl < 3"); + dbg_trace(); + trigger_gp(0); + return; + } + + if interrupt_nr << 3 | 7 > *idtr_size { + dbg_log!("interrupt_nr={:x} idtr_size={:x}", interrupt_nr, *idtr_size); + dbg_trace(); + panic!("Unimplemented: #GP handler"); + } + + let descriptor_address = return_on_pagefault!(translate_address_system_read( + *idtr_offset + (interrupt_nr << 3) + )); + + let descriptor = InterruptDescriptor::of_u64(read64s(descriptor_address) as u64); + + let mut offset = descriptor.offset(); + let selector = descriptor.selector() as i32; + let dpl = descriptor.dpl(); + let gate_type = descriptor.gate_type(); + + if is_software_int && dpl < *cpl { + dbg_log!("#gp software interrupt ({:x}) and dpl < cpl", interrupt_nr); + dbg_trace(); + trigger_gp(interrupt_nr << 3 | 2); + return; + } + + if gate_type != InterruptDescriptor::TRAP_GATE + && gate_type != InterruptDescriptor::INTERRUPT_GATE + && gate_type != InterruptDescriptor::TASK_GATE + { + // invalid gate_type + dbg_log!( + "gate type invalid. gate_type=0b{:b} raw={:b}", + gate_type, + descriptor.raw + ); + dbg_trace(); + panic!("Unimplemented: #GP handler"); + } + + if !descriptor.reserved_zeros_are_valid() { + dbg_log!( + "reserved 0s violated. gate_type=0b{:b} raw={:b}", + gate_type, + descriptor.raw + ); + dbg_trace(); + panic!("Unimplemented: #GP handler"); + } + + if !descriptor.is_present() { + // present bit not set + dbg_log!("#np int descriptor not present, int={}", interrupt_nr); + trigger_np(interrupt_nr << 3 | 2); + return; + } + + if gate_type == InterruptDescriptor::TASK_GATE { + // task gate + dbg_log!( + "interrupt to task gate: int={:x} sel={:x} dpl={}", + interrupt_nr, + selector, + dpl + ); + dbg_trace(); + dbg_assert!(descriptor.is_32(), "TODO: Check this (likely #GP)"); + dbg_assert!(offset == 0, "TODO: Check this (likely #GP)"); + do_task_switch(selector, error_code); + return; + } + + let cs_segment_descriptor = match return_on_pagefault!(lookup_segment_selector( + SegmentSelector::of_u16(selector as u16) + )) { + Ok((desc, _)) => desc, + Err(selector_unusable) => match selector_unusable { + SelectorNullOrInvalid::IsNull => { + dbg_log!("is null"); + panic!("Unimplemented: #GP handler"); + }, + SelectorNullOrInvalid::OutsideOfTableLimit => { + dbg_log!("is invalid"); + panic!("Unimplemented: #GP handler (error code)"); + }, + }, + }; + + dbg_assert!(offset as u32 <= cs_segment_descriptor.effective_limit()); + + if !cs_segment_descriptor.is_executable() || cs_segment_descriptor.dpl() > *cpl { + dbg_log!("not exec"); + panic!("Unimplemented: #GP handler"); + } + if !cs_segment_descriptor.is_present() { + // kvm-unit-test + dbg_log!("not present"); + trigger_np(interrupt_nr << 3 | 2); + return; + } + + let old_flags = get_eflags(); + + if !cs_segment_descriptor.is_dc() && cs_segment_descriptor.dpl() < *cpl { + // inter privilege level interrupt + // interrupt from vm86 mode + + if old_flags & FLAG_VM != 0 && cs_segment_descriptor.dpl() != 0 { + panic!("Unimplemented: #GP handler for non-0 cs segment dpl when in vm86 mode"); + } + + let (new_ss, new_esp) = + return_on_pagefault!(get_tss_ss_esp(cs_segment_descriptor.dpl())); + + let ss_segment_selector = SegmentSelector::of_u16(new_ss as u16); + let ss_segment_descriptor = + match return_on_pagefault!(lookup_segment_selector(ss_segment_selector)) { + Ok((desc, _)) => desc, + Err(_) => { + panic!("Unimplemented: #TS handler"); + }, + }; + + dbg_assert!(!ss_segment_descriptor.is_dc(), "TODO: Handle direction bit"); + dbg_assert!(new_esp as u32 <= ss_segment_descriptor.effective_limit()); + dbg_assert!(!ss_segment_descriptor.is_system() && ss_segment_descriptor.is_writable()); + + if ss_segment_selector.rpl() != cs_segment_descriptor.dpl() { + panic!("Unimplemented: #TS handler"); + } + if ss_segment_descriptor.dpl() != cs_segment_descriptor.dpl() + || !ss_segment_descriptor.is_rw() + { + panic!("Unimplemented: #TS handler"); + } + if !ss_segment_descriptor.is_present() { + panic!("Unimplemented: #TS handler"); + } + + let old_esp = read_reg32(ESP); + let old_ss = *sreg.offset(SS as isize) as i32; + + let error_code_space = if error_code.is_some() { 1 } else { 0 }; + let vm86_space = if (old_flags & FLAG_VM) == FLAG_VM { 4 } else { 0 }; + let bytes_per_arg = if descriptor.is_32() { 4 } else { 2 }; + + let stack_space = bytes_per_arg * (5 + error_code_space + vm86_space); + let new_stack_pointer = ss_segment_descriptor.base() + + if ss_segment_descriptor.is_32() { + new_esp - stack_space + } + else { + new_esp - stack_space & 0xFFFF + }; + + return_on_pagefault!(translate_address_system_write(new_stack_pointer)); + return_on_pagefault!(translate_address_system_write( + ss_segment_descriptor.base() + new_esp - 1 + )); + + // no exceptions below + *cpl = cs_segment_descriptor.dpl(); + cpl_changed(); + + update_cs_size(cs_segment_descriptor.is_32()); + + *flags &= !FLAG_VM & !FLAG_RF; + + if !switch_seg(SS, new_ss) { + // XXX + dbg_assert!(false); + } + set_stack_reg(new_esp); + + // XXX: #SS if stack would cross stack limit + + if old_flags & FLAG_VM != 0 { + if !descriptor.is_32() { + dbg_assert!(false); + } + else { + push32(*sreg.offset(GS as isize) as i32).unwrap(); + push32(*sreg.offset(FS as isize) as i32).unwrap(); + push32(*sreg.offset(DS as isize) as i32).unwrap(); + push32(*sreg.offset(ES as isize) as i32).unwrap(); + } + } + + if descriptor.is_32() { + push32(old_ss).unwrap(); + push32(old_esp).unwrap(); + } + else { + push16(old_ss).unwrap(); + push16(old_esp).unwrap(); + } + } + else if cs_segment_descriptor.is_dc() || cs_segment_descriptor.dpl() == *cpl { + // intra privilege level interrupt + + //dbg_log!("Intra privilege interrupt gate=" + h(selector, 4) + ":" + h(offset >>> 0, 8) + + // " gate_type=" + gate_type + " 16bit=" + descriptor.is_32() + + // " cpl=" + *cpl + " dpl=" + segment_descriptor.dpl() + " conforming=" + +segment_descriptor.is_dc(), ); + //debug.dump_regs_short(); + + if *flags & FLAG_VM != 0 { + dbg_assert!(false, "check error code"); + trigger_gp(selector & !3); + return; + } + + let bytes_per_arg = if descriptor.is_32() { 4 } else { 2 }; + let error_code_space = if error_code.is_some() { 1 } else { 0 }; + + let stack_space = bytes_per_arg * (3 + error_code_space); + + // XXX: with current cpl or with cpl 0? + return_on_pagefault!(writable_or_pagefault( + get_stack_pointer(-stack_space), + stack_space + )); + + // no exceptions below + } + else { + panic!("Unimplemented: #GP handler"); + } + + // XXX: #SS if stack would cross stack limit + if descriptor.is_32() { + push32(old_flags).unwrap(); + push32(*sreg.offset(CS as isize) as i32).unwrap(); + push32(get_real_eip()).unwrap(); + + if let Some(ec) = error_code { + push32(ec).unwrap(); + } + } + else { + push16(old_flags).unwrap(); + push16(*sreg.offset(CS as isize) as i32).unwrap(); + push16(get_real_eip()).unwrap(); + + if let Some(ec) = error_code { + push16(ec).unwrap(); + } + + offset &= 0xFFFF; + } + + if old_flags & FLAG_VM != 0 { + if !switch_seg(GS, 0) || !switch_seg(FS, 0) || !switch_seg(DS, 0) || !switch_seg(ES, 0) + { + // can't fail + dbg_assert!(false); + } + } + + *sreg.offset(CS as isize) = (selector as u16) & !3 | *cpl as u16; + dbg_assert!((*sreg.offset(CS as isize) & 3) == *cpl as u16); + + update_cs_size(cs_segment_descriptor.is_32()); + + *segment_limits.offset(CS as isize) = cs_segment_descriptor.effective_limit(); + *segment_offsets.offset(CS as isize) = cs_segment_descriptor.base(); + + *instruction_pointer = get_seg_cs() + offset; + + *flags &= !FLAG_NT & !FLAG_VM & !FLAG_RF & !FLAG_TRAP; + + if gate_type == InterruptDescriptor::INTERRUPT_GATE { + // clear int flag for interrupt gates + *flags &= !FLAG_INTERRUPT; + } + else { + if *flags & FLAG_INTERRUPT != 0 && old_flags & FLAG_INTERRUPT == 0 { + handle_irqs(); + } + } + + update_state_flags(); + } + else { + // call 4 byte cs:ip interrupt vector from ivt at cpu.memory 0 + + let index = (interrupt_nr << 2) as u32; + let new_ip = read16(index); + let new_cs = read16(index + 2); + + dbg_assert!( + index | 3 <= IVT_SIZE, + "Unimplemented: #GP for interrupt number out of IVT bounds" + ); + + // XXX: #SS if stack would cross stack limit + + // push flags, cs:ip + push16(get_eflags()).unwrap(); + push16(*sreg.offset(CS as isize) as i32).unwrap(); + push16(get_real_eip()).unwrap(); + + *flags &= !FLAG_INTERRUPT & !FLAG_AC & !FLAG_TRAP; + + switch_cs_real_mode(new_cs); + *instruction_pointer = get_seg_cs() + new_ip; + update_state_flags(); + } +} + +pub unsafe fn far_jump(eip: i32, selector: i32, is_call: bool, is_osize_32: bool) { + dbg_assert!(selector < 0x10000 && selector >= 0); + + //dbg_log("far " + ["jump", "call"][+is_call] + " eip=" + h(eip >>> 0, 8) + " cs=" + h(selector, 4), LOG_CPU); + //CPU_LOG_VERBOSE && this.debug.dump_state("far " + ["jump", "call"][+is_call]); + + if !*protected_mode || vm86_mode() { + if is_call { + if is_osize_32 { + return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-8), 8)); + + push32(*sreg.offset(CS as isize) as i32).unwrap(); + push32(get_real_eip()).unwrap(); + } + else { + return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-4), 4)); + + push16(*sreg.offset(CS as isize) as i32).unwrap(); + push16(get_real_eip()).unwrap(); + } + } + switch_cs_real_mode(selector); + *instruction_pointer = get_seg_cs() + eip; + update_state_flags(); + return; + } + + let cs_selector = SegmentSelector::of_u16(selector as u16); + let info = match return_on_pagefault!(lookup_segment_selector(cs_selector)) { + Ok((desc, _)) => desc, + Err(selector_unusable) => match selector_unusable { + SelectorNullOrInvalid::IsNull => { + dbg_log!("#gp null cs"); + trigger_gp(0); + return; + }, + SelectorNullOrInvalid::OutsideOfTableLimit => { + dbg_log!("#gp invalid cs: {:x}", selector); + trigger_gp(selector & !3); + return; + }, + }, + }; + + if info.is_system() { + dbg_assert!(is_call, "TODO: Jump"); + + dbg_log!("system type cs: {:x}", selector); + + if info.system_type() == 0xC || info.system_type() == 4 { + // call gate + let is_16 = info.system_type() == 4; + + if info.dpl() < *cpl || info.dpl() < cs_selector.rpl() { + dbg_log!("#gp cs gate dpl < cpl or dpl < rpl: {:x}", selector); + trigger_gp(selector & !3); + return; + } + + if !info.is_present() { + dbg_log!("#NP for loading not-present in gate cs sel={:x}", selector); + trigger_np(selector & !3); + return; + } + + let cs_selector = (info.raw >> 16) as i32; + + let cs_info = match return_on_pagefault!(lookup_segment_selector( + SegmentSelector::of_u16(cs_selector as u16) + )) { + Ok((desc, _)) => desc, + Err(selector_unusable) => match selector_unusable { + SelectorNullOrInvalid::IsNull => { + dbg_log!("#gp null cs"); + trigger_gp(0); + return; + }, + SelectorNullOrInvalid::OutsideOfTableLimit => { + dbg_log!("#gp invalid cs: {:x}", selector); + trigger_gp(selector & !3); + return; + }, + }, + }; + + if !cs_info.is_executable() { + dbg_log!("#gp non-executable cs: {:x}", cs_selector); + trigger_gp(cs_selector & !3); + return; + } + + if cs_info.dpl() > *cpl { + dbg_log!("#gp dpl > cpl: {:x}", cs_selector); + trigger_gp(cs_selector & !3); + return; + } + + if !cs_info.is_present() { + dbg_log!("#NP for loading not-present in cs sel={:x}", cs_selector); + trigger_np(cs_selector & !3); + return; + } + + if !cs_info.is_dc() && cs_info.dpl() < *cpl { + dbg_log!( + "more privilege call gate is_16={} from={} to={}", + is_16, + *cpl, + cs_info.dpl() + ); + let (new_ss, new_esp) = return_on_pagefault!(get_tss_ss_esp(cs_info.dpl())); + + let ss_selector = SegmentSelector::of_u16(new_ss as u16); + let ss_info = match return_on_pagefault!(lookup_segment_selector(ss_selector)) { + Ok((desc, _)) => desc, + Err(selector_unusable) => match selector_unusable { + SelectorNullOrInvalid::IsNull => { + panic!("null ss: {}", new_ss); + }, + SelectorNullOrInvalid::OutsideOfTableLimit => { + panic!("invalid ss: {}", new_ss); + }, + }, + }; + + dbg_assert!(!ss_info.is_dc(), "TODO: Handle direction bit"); + dbg_assert!(new_esp as u32 <= ss_info.effective_limit()); + dbg_assert!(!ss_info.is_system() && ss_info.is_writable()); + + if ss_selector.rpl() != cs_info.dpl() + // xxx: 0 in v86 mode + { + panic!("#TS handler"); + } + if ss_info.dpl() != cs_info.dpl() || !ss_info.is_writable() { + panic!("#TS handler"); + } + if !ss_info.is_present() { + panic!("#SS handler"); + } + + let parameter_count = (info.raw >> 32 & 0x1F) as i32; + let mut stack_space = if is_16 { 4 } else { 8 }; + if is_call { + stack_space += + if is_16 { 4 + 2 * parameter_count } else { 8 + 4 * parameter_count }; + } + if ss_info.is_32() { + return_on_pagefault!(writable_or_pagefault( + ss_info.base() + new_esp - stack_space, + stack_space + )); // , cs_info.dpl + } + else { + return_on_pagefault!(writable_or_pagefault( + ss_info.base() + (new_esp - stack_space & 0xFFFF), + stack_space + )); // , cs_info.dpl + } + + let old_esp = read_reg32(ESP); + let old_ss = *sreg.offset(SS as isize); + let old_stack_pointer = get_stack_pointer(0); + + //dbg_log!("old_esp=" + h(old_esp)); + + *cpl = cs_info.dpl(); + cpl_changed(); + + update_cs_size(cs_info.is_32()); + + // XXX: Should be checked before side effects + if !switch_seg(SS, new_ss) { + dbg_assert!(false); + }; + set_stack_reg(new_esp); + + //dbg_log!("parameter_count=" + parameter_count); + //dbg_assert!(parameter_count == 0, "TODO"); + + if is_16 { + push16(old_ss as i32).unwrap(); + push16(old_esp).unwrap(); + } + else { + push32(old_ss as i32).unwrap(); + push32(old_esp).unwrap(); + } + + if is_call { + if is_16 { + for i in (0..parameter_count).rev() { + //for(let i = parameter_count - 1; i >= 0; i--) + let parameter = safe_read16(old_stack_pointer + 2 * i).unwrap(); + push16(parameter).unwrap(); + } + + //writable_or_pagefault(get_stack_pointer(-4), 4); + push16(*sreg.offset(CS as isize) as i32).unwrap(); + push16(get_real_eip()).unwrap(); + } + else { + for i in (0..parameter_count).rev() { + //for(let i = parameter_count - 1; i >= 0; i--) + let parameter = safe_read32s(old_stack_pointer + 4 * i).unwrap(); + push32(parameter).unwrap(); + } + + //writable_or_pagefault(get_stack_pointer(-8), 8); + push32(*sreg.offset(CS as isize) as i32).unwrap(); + push32(get_real_eip()).unwrap(); + } + } + } + else { + dbg_log!( + "same privilege call gate is_16={} from={} to={} conforming={}", + is_16, + *cpl, + cs_info.dpl(), + cs_info.is_dc() + ); + // ok + + if is_call { + if is_16 { + return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-4), 4)); + + push16(*sreg.offset(CS as isize) as i32).unwrap(); + push16(get_real_eip()).unwrap(); + } + else { + return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-8), 8)); + + push32(*sreg.offset(CS as isize) as i32).unwrap(); + push32(get_real_eip()).unwrap(); + } + } + } + + // Note: eip from call is ignored + let mut new_eip = (info.raw & 0xFFFF) as i32; + if !is_16 { + new_eip |= ((info.raw >> 32) & 0xFFFF0000) as i32; + } + + dbg_log!( + "call gate eip={:x} cs={:x} conforming={}", + new_eip as u32, + cs_selector, + cs_info.is_dc() + ); + dbg_assert!((new_eip as u32) <= cs_info.effective_limit(), "todo: #gp"); + + update_cs_size(cs_info.is_32()); + + *segment_is_null.offset(CS as isize) = false; + *segment_limits.offset(CS as isize) = cs_info.effective_limit(); + *segment_offsets.offset(CS as isize) = cs_info.base(); + *sreg.offset(CS as isize) = cs_selector as u16 & !3 | *cpl as u16; + dbg_assert!(*sreg.offset(CS as isize) & 3 == *cpl as u16); + + *instruction_pointer = get_seg_cs() + new_eip; + + update_state_flags(); + } + else { + dbg_assert!(false); + //let types = { 9: "Available 386 TSS", 0xb: "Busy 386 TSS", 4: "286 Call Gate", 0xc: "386 Call Gate" }; + //throw debug.unimpl("load system segment descriptor, type = " + (info.access & 15) + " (" + types[info.access & 15] + ")"); + } + } + else { + if !info.is_executable() { + dbg_log!("#gp non-executable cs: {:x}", selector); + trigger_gp(selector & !3); + return; + } + + if info.is_dc() { + // conforming code segment + if info.dpl() > *cpl { + dbg_log!("#gp cs dpl > cpl: {:x}", selector); + trigger_gp(selector & !3); + return; + } + } + else { + // non-conforming code segment + + if cs_selector.rpl() > *cpl || info.dpl() != *cpl { + dbg_log!("#gp cs rpl > cpl or dpl != cpl: {:x}", selector); + trigger_gp(selector & !3); + return; + } + } + + if !info.is_present() { + dbg_log!("#NP for loading not-present in cs sel={:x}", selector); + dbg_trace(); + trigger_np(selector & !3); + return; + } + + if is_call { + if is_osize_32 { + return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-8), 8)); + + push32(*sreg.offset(CS as isize) as i32).unwrap(); + push32(get_real_eip()).unwrap(); + } + else { + return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-4), 4)); + + push16(*sreg.offset(CS as isize) as i32).unwrap(); + push16(get_real_eip()).unwrap(); + } + } + + dbg_assert!((eip as u32) <= info.effective_limit(), "todo: #gp"); + + update_cs_size(info.is_32()); + + *segment_is_null.offset(CS as isize) = false; + *segment_limits.offset(CS as isize) = info.effective_limit(); + + *segment_offsets.offset(CS as isize) = info.base(); + *sreg.offset(CS as isize) = selector as u16 & !3 | *cpl as u16; + + *instruction_pointer = get_seg_cs() + eip; + + update_state_flags(); + } + + //dbg_log!("far " + ["jump", "call"][+is_call] + " to:", LOG_CPU) + //CPU_LOG_VERBOSE && debug.dump_state("far " + ["jump", "call"][+is_call] + " end"); +} + +pub unsafe fn far_return(eip: i32, selector: i32, stack_adjust: i32, is_osize_32: bool) { + dbg_assert!(selector < 0x10000 && selector >= 0); + + //dbg_log("far return eip=" + h(eip >>> 0, 8) + " cs=" + h(selector, 4) + " stack_adjust=" + h(stack_adjust), LOG_CPU); + //CPU_LOG_VERBOSE && this.debug.dump_state("far ret start"); + + if !*protected_mode { + dbg_assert!(!*is_32); + //dbg_assert(!this.stack_size_32[0]); + } + + if !*protected_mode || vm86_mode() { + switch_cs_real_mode(selector); + *instruction_pointer = get_seg_cs() + eip; + adjust_stack_reg(2 * (if is_osize_32 { 4 } else { 2 }) + stack_adjust); + update_state_flags(); + return; + } + + let cs_selector = SegmentSelector::of_u16(selector as u16); + let info = match return_on_pagefault!(lookup_segment_selector(cs_selector)) { + Ok((desc, _)) => desc, + Err(selector_unusable) => match selector_unusable { + SelectorNullOrInvalid::IsNull => { + dbg_log!("far return: #gp null cs"); + trigger_gp(0); + return; + }, + SelectorNullOrInvalid::OutsideOfTableLimit => { + dbg_log!("far return: #gp invalid cs: {:x}", selector); + trigger_gp(selector & !3); + return; + }, + }, + }; + + if info.is_system() { + dbg_assert!(false, "is system in far return"); + trigger_gp(selector & !3); + return; + } + + if !info.is_executable() { + dbg_log!("non-executable cs: {:x}", selector); + trigger_gp(selector & !3); + return; + } + + if cs_selector.rpl() < *cpl { + dbg_log!("cs rpl < cpl: {:x}", selector); + trigger_gp(selector & !3); + return; + } + + if info.is_dc() && info.dpl() > cs_selector.rpl() { + dbg_log!("cs conforming and dpl > rpl: {:x}", selector); + trigger_gp(selector & !3); + return; + } + + if !info.is_dc() && info.dpl() != cs_selector.rpl() { + dbg_log!("cs non-conforming and dpl != rpl: {:x}", selector); + trigger_gp(selector & !3); + return; + } + + if !info.is_present() { + dbg_log!("#NP for loading not-present in cs sel={:x}", selector); + dbg_trace(); + trigger_np(selector & !3); + return; + } + + if cs_selector.rpl() > *cpl { + dbg_log!( + "far return privilege change cs: {:x} from={} to={} is_16={}", + selector, + *cpl, + cs_selector.rpl(), + is_osize_32 + ); + + let temp_esp; + let temp_ss; + if is_osize_32 { + //dbg_log!("esp read from " + h(translate_address_system_read(get_stack_pointer(stack_adjust + 8)))) + temp_esp = safe_read32s(get_stack_pointer(stack_adjust + 8)).unwrap(); + //dbg_log!("esp=" + h(temp_esp)); + temp_ss = safe_read16(get_stack_pointer(stack_adjust + 12)).unwrap(); + } + else { + //dbg_log!("esp read from " + h(translate_address_system_read(get_stack_pointer(stack_adjust + 4)))); + temp_esp = safe_read16(get_stack_pointer(stack_adjust + 4)).unwrap(); + //dbg_log!("esp=" + h(temp_esp)); + temp_ss = safe_read16(get_stack_pointer(stack_adjust + 6)).unwrap(); + } + + *cpl = cs_selector.rpl(); + cpl_changed(); + + // XXX: This failure should be checked before side effects + if !switch_seg(SS, temp_ss) { + dbg_assert!(false); + } + set_stack_reg(temp_esp + stack_adjust); + + //if(is_osize_32) + //{ + // adjust_stack_reg(2 * 4); + //} + //else + //{ + // adjust_stack_reg(2 * 2); + //} + + //throw debug.unimpl("privilege change"); + + //adjust_stack_reg(stack_adjust); + } + else { + if is_osize_32 { + adjust_stack_reg(2 * 4 + stack_adjust); + } + else { + adjust_stack_reg(2 * 2 + stack_adjust); + } + } + + //dbg_assert(*cpl == info.dpl); + + update_cs_size(info.is_32()); + + *segment_is_null.offset(CS as isize) = false; + *segment_limits.offset(CS as isize) = info.effective_limit(); + + *segment_offsets.offset(CS as isize) = info.base(); + *sreg.offset(CS as isize) = selector as u16; + dbg_assert!(selector & 3 == *cpl as i32); + + *instruction_pointer = get_seg_cs() + eip; + + update_state_flags(); + + //dbg_log("far return to:", LOG_CPU) + //CPU_LOG_VERBOSE && debug.dump_state("far ret end"); +} + +pub unsafe fn do_task_switch(selector: i32, error_code: Option) { + dbg_log!("do_task_switch sel={:x}", selector); + + dbg_assert!(*tss_size_32, "TODO: 16-bit TSS in task switch"); + + let selector = SegmentSelector::of_u16(selector as u16); + let (descriptor, descriptor_address) = + match lookup_segment_selector(selector).expect("TODO: handle pagefault") { + Ok(desc) => desc, + Err(_) => { + panic!("#GP handler"); + }, + }; + + dbg_assert!(selector.is_gdt()); + dbg_assert!((descriptor.system_type() & !2) == 1 || (descriptor.system_type() & !2) == 9); + let tss_is_16 = descriptor.system_type() <= 3; + let tss_is_busy = (descriptor.system_type() & 2) == 2; + + if (descriptor.system_type() & 2) == 2 { + // is busy + panic!("#GP handler"); + } + + if !descriptor.is_present() { + panic!("#NP handler"); + } + + if descriptor.effective_limit() < 103 { + panic!("#NP handler"); + } + + let _tsr_size = *segment_limits.offset(TR as isize); + let tsr_offset = *segment_offsets.offset(TR as isize); + + let mut old_eflags = get_eflags(); + + if tss_is_busy { + old_eflags &= !FLAG_NT; + } + + writable_or_pagefault(tsr_offset, 0x66).unwrap(); + + //safe_write32(tsr_offset + TSR_CR3, *cr.offset(3)); + + // TODO: Write 16 bit values if old tss is 16 bit + safe_write32(tsr_offset + TSR_EIP, get_real_eip()).unwrap(); + safe_write32(tsr_offset + TSR_EFLAGS, old_eflags).unwrap(); + + safe_write32(tsr_offset + TSR_EAX, read_reg32(EAX)).unwrap(); + safe_write32(tsr_offset + TSR_ECX, read_reg32(ECX)).unwrap(); + safe_write32(tsr_offset + TSR_EDX, read_reg32(EDX)).unwrap(); + safe_write32(tsr_offset + TSR_EBX, read_reg32(EBX)).unwrap(); + + safe_write32(tsr_offset + TSR_ESP, read_reg32(ESP)).unwrap(); + safe_write32(tsr_offset + TSR_EBP, read_reg32(EBP)).unwrap(); + safe_write32(tsr_offset + TSR_ESI, read_reg32(ESI)).unwrap(); + safe_write32(tsr_offset + TSR_EDI, read_reg32(EDI)).unwrap(); + + safe_write32(tsr_offset + TSR_ES, *sreg.offset(ES as isize) as i32).unwrap(); + safe_write32(tsr_offset + TSR_CS, *sreg.offset(CS as isize) as i32).unwrap(); + safe_write32(tsr_offset + TSR_SS, *sreg.offset(SS as isize) as i32).unwrap(); + safe_write32(tsr_offset + TSR_DS, *sreg.offset(DS as isize) as i32).unwrap(); + safe_write32(tsr_offset + TSR_FS, *sreg.offset(FS as isize) as i32).unwrap(); + safe_write32(tsr_offset + TSR_GS, *sreg.offset(GS as isize) as i32).unwrap(); + + //safe_write32(tsr_offset + TSR_LDT, *sreg.offset(reg_ldtr)); + + if true + /* is jump or call or int */ + { + safe_write64(descriptor_address, descriptor.set_busy().raw).unwrap(); + } + + //let new_tsr_size = descriptor.effective_limit; + let new_tsr_offset = descriptor.base(); + + dbg_assert!(!tss_is_16, "unimplemented"); + + if true + /* is call or int */ + { + safe_write16( + new_tsr_offset + TSR_BACKLINK, + *sreg.offset(TR as isize) as i32, + ) + .unwrap(); + } + + let new_cr3 = safe_read32s(new_tsr_offset + TSR_CR3).unwrap(); + + *flags &= !FLAG_VM; + + let new_eip = safe_read32s(new_tsr_offset + TSR_EIP).unwrap(); + let new_cs = safe_read16(new_tsr_offset + TSR_CS).unwrap(); + let new_cs_selector = SegmentSelector::of_u16(new_cs as u16); + let new_cs_descriptor = + match lookup_segment_selector(new_cs_selector).expect("TODO: handle pagefault") { + Ok((desc, _)) => desc, + Err(SelectorNullOrInvalid::IsNull) => { + dbg_log!("null cs"); + panic!("#TS handler"); + }, + Err(SelectorNullOrInvalid::OutsideOfTableLimit) => { + dbg_log!("invalid cs: {:x}", new_cs); + panic!("#TS handler"); + }, + }; + + if new_cs_descriptor.is_system() { + panic!("#TS handler"); + } + + if !new_cs_descriptor.is_executable() { + panic!("#TS handler"); + } + + if new_cs_descriptor.is_dc() && new_cs_descriptor.dpl() > new_cs_selector.rpl() { + dbg_log!("cs conforming and dpl > rpl: {:x}", selector.raw); + panic!("#TS handler"); + } + + if !new_cs_descriptor.is_dc() && new_cs_descriptor.dpl() != new_cs_selector.rpl() { + dbg_log!("cs non-conforming and dpl != rpl: {:x}", selector.raw); + panic!("#TS handler"); + } + + if !new_cs_descriptor.is_present() { + dbg_log!("#NP for loading not-present in cs sel={:x}", selector.raw); + panic!("#TS handler"); + } + + *segment_is_null.offset(CS as isize) = false; + *segment_limits.offset(CS as isize) = new_cs_descriptor.effective_limit(); + *segment_offsets.offset(CS as isize) = new_cs_descriptor.base(); + *sreg.offset(CS as isize) = new_cs as u16; + + *cpl = new_cs_descriptor.dpl(); + cpl_changed(); + + dbg_assert!((*sreg.offset(CS as isize) & 3) as u8 == *cpl); + + dbg_assert!( + new_eip as u32 <= new_cs_descriptor.effective_limit(), + "todo: #gp" + ); + update_cs_size(new_cs_descriptor.is_32()); + + let mut new_eflags = safe_read32s(new_tsr_offset + TSR_EFLAGS).unwrap(); + + if true + /* is call or int */ + { + safe_write32(tsr_offset + TSR_BACKLINK, selector.raw as i32).unwrap(); + new_eflags |= FLAG_NT; + } + + if new_eflags & FLAG_VM != 0 { + panic!("task switch to VM mode"); + } + + update_eflags(new_eflags); + + if true + /* call or int */ + { + *flags |= FLAG_NT; + } + + let new_ldt = safe_read16(new_tsr_offset + TSR_LDT).unwrap(); + load_ldt(new_ldt).unwrap(); + + write_reg32(EAX, safe_read32s(new_tsr_offset + TSR_EAX).unwrap()); + write_reg32(ECX, safe_read32s(new_tsr_offset + TSR_ECX).unwrap()); + write_reg32(EDX, safe_read32s(new_tsr_offset + TSR_EDX).unwrap()); + write_reg32(EBX, safe_read32s(new_tsr_offset + TSR_EBX).unwrap()); + + write_reg32(ESP, safe_read32s(new_tsr_offset + TSR_ESP).unwrap()); + write_reg32(EBP, safe_read32s(new_tsr_offset + TSR_EBP).unwrap()); + write_reg32(ESI, safe_read32s(new_tsr_offset + TSR_ESI).unwrap()); + write_reg32(EDI, safe_read32s(new_tsr_offset + TSR_EDI).unwrap()); + + if !switch_seg(ES, safe_read16(new_tsr_offset + TSR_ES).unwrap()) + || !switch_seg(SS, safe_read16(new_tsr_offset + TSR_SS).unwrap()) + || !switch_seg(DS, safe_read16(new_tsr_offset + TSR_DS).unwrap()) + || !switch_seg(FS, safe_read16(new_tsr_offset + TSR_FS).unwrap()) + || !switch_seg(GS, safe_read16(new_tsr_offset + TSR_GS).unwrap()) + { + // XXX: Should be checked before side effects + dbg_assert!(false); + } + + *instruction_pointer = get_seg_cs() + new_eip; + + *segment_offsets.offset(TR as isize) = descriptor.base(); + *segment_limits.offset(TR as isize) = descriptor.effective_limit(); + *sreg.offset(TR as isize) = selector.raw; + + set_cr3(new_cr3); + + *cr.offset(0) |= CR0_TS; + + if let Some(error_code) = error_code { + if tss_is_16 { + push16(error_code & 0xFFFF).unwrap(); + } + else { + push32(error_code).unwrap(); + } + } + + update_state_flags(); +} + +pub unsafe fn after_block_boundary() { jit_block_boundary = true; } + +#[no_mangle] +pub fn track_jit_exit(phys_addr: u32) { + unsafe { + debug_last_jump = LastJump::Compiled { phys_addr }; + } +} + +#[no_mangle] +pub unsafe fn get_eflags() -> i32 { + return *flags & !FLAGS_ALL + | getcf() as i32 + | (getpf() as i32) << 2 + | (getaf() as i32) << 4 + | (getzf() as i32) << 6 + | (getsf() as i32) << 7 + | (getof() as i32) << 11; +} + +#[no_mangle] +pub unsafe fn get_eflags_no_arith() -> i32 { return *flags; } + +pub unsafe fn readable_or_pagefault(addr: i32, size: i32) -> OrPageFault<()> { + dbg_assert!(size < 0x1000); + dbg_assert!(size > 0); + + let user = *cpl == 3; + translate_address(addr, false, user, false, true)?; + + let end = addr + size - 1 & !0xFFF; + if addr & !0xFFF != end & !0xFFF { + translate_address(end, false, user, false, true)?; + } + + return Ok(()); +} + +pub unsafe fn writable_or_pagefault(addr: i32, size: i32) -> OrPageFault<()> { + dbg_assert!(size < 0x1000); + dbg_assert!(size > 0); + + let user = *cpl == 3; + translate_address(addr, true, user, false, true)?; + + let end = addr + size - 1 & !0xFFF; + if addr & !0xFFF != end & !0xFFF { + translate_address(end, true, user, false, true)?; + } + + return Ok(()); +} + +pub fn translate_address_read_no_side_effects(address: i32) -> OrPageFault { + unsafe { translate_address(address, false, *cpl == 3, false, false) } +} +pub fn translate_address_read(address: i32) -> OrPageFault { + unsafe { translate_address(address, false, *cpl == 3, false, true) } +} +pub unsafe fn translate_address_read_jit(address: i32) -> OrPageFault { + translate_address(address, false, *cpl == 3, true, true) +} + +pub unsafe fn translate_address_write(address: i32) -> OrPageFault { + translate_address(address, true, *cpl == 3, false, true) +} +pub unsafe fn translate_address_write_jit_and_can_skip_dirty( + address: i32, +) -> OrPageFault<(u32, bool)> { + let entry = tlb_data[(address as u32 >> 12) as usize]; + let user = *cpl == 3; + if entry & (TLB_VALID | if user { TLB_NO_USER } else { 0 } | TLB_READONLY) == TLB_VALID { + Ok(( + (entry & !0xFFF ^ address) as u32 - memory::mem8 as u32, + entry & TLB_HAS_CODE == 0, + )) + } + else { + match do_page_walk(address, true, user, true) { + Ok((phys_addr_high, skip)) => Ok((phys_addr_high | address as u32 & 0xFFF, skip)), + Err(pagefault) => { + trigger_pagefault_jit(pagefault); + Err(()) + }, + } + } +} + +pub unsafe fn translate_address_system_read(address: i32) -> OrPageFault { + translate_address(address, false, false, false, true) +} +pub unsafe fn translate_address_system_write(address: i32) -> OrPageFault { + translate_address(address, true, false, false, true) +} + +#[inline(always)] +pub unsafe fn translate_address( + address: i32, + for_writing: bool, + user: bool, + jit: bool, + side_effects: bool, +) -> OrPageFault { + let entry = tlb_data[(address as u32 >> 12) as usize]; + if entry + & (TLB_VALID + | if user { TLB_NO_USER } else { 0 } + | if for_writing { TLB_READONLY } else { 0 }) + == TLB_VALID + { + Ok((entry & !0xFFF ^ address) as u32 - memory::mem8 as u32) + } + else { + match do_page_walk(address, for_writing, user, side_effects) { + Ok((phys_addr_high, _)) => Ok(phys_addr_high | address as u32 & 0xFFF), + Err(pagefault) => { + if side_effects { + if jit { + trigger_pagefault_jit(pagefault); + } + else { + trigger_pagefault(pagefault); + } + } + Err(()) + }, + } + } +} + +pub unsafe fn translate_address_write_and_can_skip_dirty(address: i32) -> OrPageFault<(u32, bool)> { + let entry = tlb_data[(address as u32 >> 12) as usize]; + let user = *cpl == 3; + if entry & (TLB_VALID | if user { TLB_NO_USER } else { 0 } | TLB_READONLY) == TLB_VALID { + Ok(( + (entry & !0xFFF ^ address) as u32 - memory::mem8 as u32, + entry & TLB_HAS_CODE == 0, + )) + } + else { + match do_page_walk(address, true, user, true) { + Ok((phys_addr_high, skip)) => Ok((phys_addr_high | address as u32 & 0xFFF, skip)), + Err(pagefault) => { + trigger_pagefault(pagefault); + Err(()) + }, + } + } +} + +pub struct PageFault { + addr: i32, + for_writing: bool, + user: bool, + present: bool, +} + +// 32-bit paging: +// - 10 bits PD | 10 bits PT | 12 bits offset +// - 10 bits PD | 22 bits offset (4MB huge page) +// +// PAE paging: +// - 2 bits PDPT | 9 bits PD | 9 bits PT | 12 bits offset +// - 2 bits PDPT | 9 bits PD | 21 bits offset (2MB huge page) +// +// Note that PAE entries are 64-bit, and can describe physical addresses over 32 +// bits. However, since we support only 32-bit physical addresses, we require +// the high half of the entry to be 0. +#[inline(never)] +pub unsafe fn do_page_walk( + addr: i32, + for_writing: bool, + user: bool, + side_effects: bool, +) -> Result<(u32, bool), PageFault> { + let global; + let mut allow_user: bool = true; + let page = (addr as u32 >> 12) as i32; + let high; + + let cr0 = *cr; + let cr4 = *cr.offset(4); + + if cr0 & CR0_PG == 0 { + // paging disabled + high = addr as u32 & 0xFFFFF000; + global = false + } + else { + profiler::stat_increment(TLB_MISS); + + let pae = cr4 & CR4_PAE != 0; + + let (page_dir_addr, page_dir_entry) = if pae { + let pdpt_entry = *reg_pdpte.offset(((addr as u32) >> 30) as isize); + if pdpt_entry as i32 & PAGE_TABLE_PRESENT_MASK == 0 { + return Err(PageFault { + addr, + for_writing, + user, + present: false, + }); + } + + let page_dir_addr = + (pdpt_entry as u32 & 0xFFFFF000) + ((((addr as u32) >> 21) & 0x1FF) << 3); + let page_dir_entry = read64s(page_dir_addr); + dbg_assert!( + page_dir_entry as u64 & 0x7FFF_FFFF_0000_0000 == 0, + "Unsupported: Page directory entry larger than 32 bits" + ); + dbg_assert!( + page_dir_entry & 0x8000_0000_0000_0000u64 as i64 == 0, + "Unsupported: NX bit" + ); + + (page_dir_addr, page_dir_entry as i32) + } + else { + let page_dir_addr = *cr.offset(3) as u32 + (((addr as u32) >> 22) << 2); + let page_dir_entry = read32s(page_dir_addr); + (page_dir_addr, page_dir_entry) + }; + + if page_dir_entry & PAGE_TABLE_PRESENT_MASK == 0 { + return Err(PageFault { + addr, + for_writing, + user, + present: false, + }); + } + + let kernel_write_override = !user && 0 == cr0 & CR0_WP; + if page_dir_entry & PAGE_TABLE_RW_MASK == 0 && !kernel_write_override && for_writing { + return Err(PageFault { + addr, + for_writing, + user, + present: true, + }); + } + + if page_dir_entry & PAGE_TABLE_USER_MASK == 0 { + allow_user = false; + if user { + // Page Fault: page table accessed by non-supervisor + return Err(PageFault { + addr, + for_writing, + user, + present: true, + }); + } + } + + if 0 != page_dir_entry & PAGE_TABLE_PSE_MASK && 0 != cr4 & CR4_PSE { + // size bit is set + // set the accessed and dirty bits + + let new_page_dir_entry = page_dir_entry + | PAGE_TABLE_ACCESSED_MASK + | if for_writing { PAGE_TABLE_DIRTY_MASK } else { 0 }; + + if side_effects && page_dir_entry != new_page_dir_entry { + write8(page_dir_addr, new_page_dir_entry); + } + + high = if pae { + page_dir_entry as u32 & 0xFFE00000 | (addr & 0x1FF000) as u32 + } + else { + page_dir_entry as u32 & 0xFFC00000 | (addr & 0x3FF000) as u32 + }; + global = page_dir_entry & PAGE_TABLE_GLOBAL_MASK == PAGE_TABLE_GLOBAL_MASK + } + else { + let (page_table_addr, page_table_entry) = if pae { + let page_table_addr = + (page_dir_entry as u32 & 0xFFFFF000) + (((addr as u32 >> 12) & 0x1FF) << 3); + let page_table_entry = read64s(page_table_addr); + dbg_assert!( + page_table_entry as u64 & 0x7FFF_FFFF_0000_0000 == 0, + "Unsupported: Page table entry larger than 32 bits" + ); + dbg_assert!( + page_table_entry & 0x8000_0000_0000_0000u64 as i64 == 0, + "Unsupported: NX bit" + ); + + (page_table_addr, page_table_entry as i32) + } + else { + let page_table_addr = + (page_dir_entry as u32 & 0xFFFFF000) + (((addr as u32 >> 12) & 0x3FF) << 2); + let page_table_entry = read32s(page_table_addr); + (page_table_addr, page_table_entry) + }; + + if page_table_entry & PAGE_TABLE_PRESENT_MASK == 0 { + return Err(PageFault { + addr, + for_writing, + user, + present: false, + }); + } + + if page_table_entry & PAGE_TABLE_RW_MASK == 0 && !kernel_write_override && for_writing { + return Err(PageFault { + addr, + for_writing, + user, + present: true, + }); + } + if page_table_entry & PAGE_TABLE_USER_MASK == 0 { + allow_user = false; + if user { + return Err(PageFault { + addr, + for_writing, + user, + present: true, + }); + } + } + + // Set the accessed and dirty bits + // Note: dirty bit is only set on the page table entry + let new_page_dir_entry = page_dir_entry | PAGE_TABLE_ACCESSED_MASK; + if side_effects && new_page_dir_entry != page_dir_entry { + write8(page_dir_addr, new_page_dir_entry); + } + let new_page_table_entry = page_table_entry + | PAGE_TABLE_ACCESSED_MASK + | if for_writing { PAGE_TABLE_DIRTY_MASK } else { 0 }; + if side_effects && page_table_entry != new_page_table_entry { + write8(page_table_addr, new_page_table_entry); + } + + high = page_table_entry as u32 & 0xFFFFF000; + global = page_table_entry & PAGE_TABLE_GLOBAL_MASK == PAGE_TABLE_GLOBAL_MASK + } + } + + if side_effects && tlb_data[page as usize] == 0 { + if valid_tlb_entries_count == VALID_TLB_ENTRY_MAX { + profiler::stat_increment(TLB_FULL); + clear_tlb(); + // also clear global entries if tlb is almost full after clearing non-global pages + if valid_tlb_entries_count > VALID_TLB_ENTRY_MAX * 3 / 4 { + profiler::stat_increment(TLB_GLOBAL_FULL); + full_clear_tlb(); + } + } + dbg_assert!(valid_tlb_entries_count < VALID_TLB_ENTRY_MAX); + valid_tlb_entries[valid_tlb_entries_count as usize] = page; + valid_tlb_entries_count += 1; + // TODO: Check that there are no duplicates in valid_tlb_entries + // XXX: There will probably be duplicates due to invlpg deleting + // entries from tlb_data but not from valid_tlb_entries + } + else if side_effects && CHECK_TLB_INVARIANTS { + let mut found: bool = false; + for i in 0..valid_tlb_entries_count { + if valid_tlb_entries[i as usize] == page { + found = true; + break; + } + } + dbg_assert!(found); + } + + let is_in_mapped_range = in_mapped_range(high); + let has_code = !is_in_mapped_range && jit::jit_page_has_code(Page::page_of(high)); + let info_bits = TLB_VALID + | if for_writing { 0 } else { TLB_READONLY } + | if allow_user { 0 } else { TLB_NO_USER } + | if is_in_mapped_range { TLB_IN_MAPPED_RANGE } else { 0 } + | if global && 0 != cr4 & CR4_PGE { TLB_GLOBAL } else { 0 } + | if has_code { TLB_HAS_CODE } else { 0 }; + + dbg_assert!((high ^ (page as u32) << 12) & 0xFFF == 0); + if side_effects { + // bake in the addition with memory::mem8 to save an instruction from the fast path + // of memory accesses + tlb_data[page as usize] = + (high + memory::mem8 as u32) as i32 ^ page << 12 | info_bits as i32; + + jit::update_tlb_code(Page::page_of(addr as u32), Page::page_of(high)); + } + + return Ok((high, !has_code)); +} + +#[no_mangle] +pub unsafe fn full_clear_tlb() { + profiler::stat_increment(FULL_CLEAR_TLB); + // clear tlb including global pages + *last_virt_eip = -1; + for i in 0..valid_tlb_entries_count { + let page = valid_tlb_entries[i as usize]; + clear_tlb_code(page); + tlb_data[page as usize] = 0; + } + valid_tlb_entries_count = 0; + + if CHECK_TLB_INVARIANTS { + for &entry in tlb_data.iter() { + dbg_assert!(entry == 0); + } + }; +} + +#[no_mangle] +pub unsafe fn clear_tlb() { + profiler::stat_increment(CLEAR_TLB); + // clear tlb excluding global pages + *last_virt_eip = -1; + let mut global_page_offset: i32 = 0; + for i in 0..valid_tlb_entries_count { + let page = valid_tlb_entries[i as usize]; + let entry = tlb_data[page as usize]; + if 0 != entry & TLB_GLOBAL { + // reinsert at the front + valid_tlb_entries[global_page_offset as usize] = page; + global_page_offset += 1; + } + else { + clear_tlb_code(page); + tlb_data[page as usize] = 0; + } + } + valid_tlb_entries_count = global_page_offset; + + if CHECK_TLB_INVARIANTS { + for &entry in tlb_data.iter() { + dbg_assert!(entry == 0 || 0 != entry & TLB_GLOBAL); + } + }; +} + +/// Pagefault handling with the jit works as follows: +/// - If the slow path is taken, it calls safe_{read,write}*_jit +/// - safe_{read,write}*_jit call translate_address_{read,write}_jit +/// - translate_address_{read,write}_jit do the normal page walk and call this method instead of +/// trigger_pagefault when a page fault happens +/// - this method prepares a page fault by setting cr2, and writes the error code +/// into jit_fault. This method *doesn't* trigger the interrupt, as registers are +/// still stored in the wasm module +/// - back in the wasm module, the generated code detects the page fault, restores the registers +/// and finally calls trigger_fault_end_jit, which does the interrupt +pub unsafe fn trigger_pagefault_jit(fault: PageFault) { + let write = fault.for_writing; + let addr = fault.addr; + let present = fault.present; + let user = fault.user; + + if ::config::LOG_PAGE_FAULTS { + dbg_log!( + "page fault jit w={} u={} p={} eip={:x} cr2={:x}", + write as i32, + user as i32, + present as i32, + *previous_ip, + addr + ); + dbg_trace(); + } + profiler::stat_increment(PAGE_FAULT); + *cr.offset(2) = addr; + // invalidate tlb entry + let page = ((addr as u32) >> 12) as i32; + clear_tlb_code(page); + tlb_data[page as usize] = 0; + if DEBUG { + if cpu_exception_hook(CPU_EXCEPTION_PF) { + return; + } + } + let error_code = (user as i32) << 2 | (write as i32) << 1 | present as i32; + jit_fault = Some((CPU_EXCEPTION_PF, Some(error_code))); +} + +#[no_mangle] +pub unsafe fn trigger_de_jit(start_eip: i32) { + dbg_log!("#de in jit mode"); + *instruction_pointer = *instruction_pointer & !0xFFF | start_eip & 0xFFF; + jit_fault = Some((CPU_EXCEPTION_DE, None)) +} + +#[no_mangle] +pub unsafe fn trigger_ud_jit(start_eip: i32) { + dbg_log!("#ud in jit mode"); + *instruction_pointer = *instruction_pointer & !0xFFF | start_eip & 0xFFF; + jit_fault = Some((CPU_EXCEPTION_UD, None)) +} + +#[no_mangle] +pub unsafe fn trigger_nm_jit(start_eip: i32) { + dbg_log!("#nm in jit mode"); + *instruction_pointer = *instruction_pointer & !0xFFF | start_eip & 0xFFF; + jit_fault = Some((CPU_EXCEPTION_NM, None)) +} + +#[no_mangle] +pub unsafe fn trigger_gp_jit(code: i32, start_eip: i32) { + dbg_log!("#gp in jit mode"); + *instruction_pointer = *instruction_pointer & !0xFFF | start_eip & 0xFFF; + jit_fault = Some((CPU_EXCEPTION_GP, Some(code))) +} + +#[no_mangle] +pub unsafe fn trigger_fault_end_jit() { + let (code, error_code) = jit_fault.take().unwrap(); + if DEBUG { + if cpu_exception_hook(code) { + return; + } + } + call_interrupt_vector(code, false, error_code); +} + +pub unsafe fn trigger_pagefault(fault: PageFault) { + let write = fault.for_writing; + let addr = fault.addr; + let present = fault.present; + let user = fault.user; + + if ::config::LOG_PAGE_FAULTS { + dbg_log!( + "page fault w={} u={} p={} eip={:x} cr2={:x}", + write as i32, + user as i32, + present as i32, + *previous_ip, + addr + ); + dbg_trace(); + } + profiler::stat_increment(PAGE_FAULT); + *cr.offset(2) = addr; + // invalidate tlb entry + let page = ((addr as u32) >> 12) as i32; + clear_tlb_code(page); + tlb_data[page as usize] = 0; + *instruction_pointer = *previous_ip; + call_interrupt_vector( + CPU_EXCEPTION_PF, + false, + Some((user as i32) << 2 | (write as i32) << 1 | present as i32), + ); +} + +pub fn tlb_set_has_code(physical_page: Page, has_code: bool) { + for i in 0..unsafe { valid_tlb_entries_count } { + let page = unsafe { valid_tlb_entries[i as usize] }; + let entry = unsafe { tlb_data[page as usize] }; + if 0 != entry { + let tlb_physical_page = Page::of_u32( + (entry as u32 >> 12 ^ page as u32) - (unsafe { memory::mem8 } as u32 >> 12), + ); + if physical_page == tlb_physical_page { + unsafe { + tlb_data[page as usize] = + if has_code { entry | TLB_HAS_CODE } else { entry & !TLB_HAS_CODE } + } + if !has_code { + clear_tlb_code(page); + } + } + } + } + + check_tlb_invariants(); +} +pub fn tlb_set_has_code_multiple(physical_pages: &HashSet, has_code: bool) { + let physical_pages: Vec = physical_pages.into_iter().copied().collect(); + for i in 0..unsafe { valid_tlb_entries_count } { + let page = unsafe { valid_tlb_entries[i as usize] }; + let entry = unsafe { tlb_data[page as usize] }; + if 0 != entry { + let tlb_physical_page = Page::of_u32( + (entry as u32 >> 12 ^ page as u32) - (unsafe { memory::mem8 } as u32 >> 12), + ); + if physical_pages.contains(&tlb_physical_page) { + unsafe { + tlb_data[page as usize] = + if has_code { entry | TLB_HAS_CODE } else { entry & !TLB_HAS_CODE } + } + } + } + } + + check_tlb_invariants(); +} + +pub fn check_tlb_invariants() { + if !CHECK_TLB_INVARIANTS { + return; + } + + for i in 0..unsafe { valid_tlb_entries_count } { + let page = unsafe { valid_tlb_entries[i as usize] }; + let entry = unsafe { tlb_data[page as usize] }; + + if 0 == entry || 0 != entry & TLB_IN_MAPPED_RANGE { + // there's no code in mapped memory + continue; + } + + let target = (entry ^ page << 12) as u32 - unsafe { memory::mem8 } as u32; + dbg_assert!(!in_mapped_range(target)); + + let entry_has_code = entry & TLB_HAS_CODE != 0; + let has_code = jit::jit_page_has_code(Page::page_of(target)); + + // If some code has been created in a page, the corresponding tlb entries must be marked + dbg_assert!(!has_code || entry_has_code); + } +} + +pub const DISABLE_EIP_TRANSLATION_OPTIMISATION: bool = false; + +pub unsafe fn read_imm8() -> OrPageFault { + let eip = *instruction_pointer; + if DISABLE_EIP_TRANSLATION_OPTIMISATION || 0 != eip & !0xFFF ^ *last_virt_eip { + *eip_phys = (translate_address_read(eip)? ^ eip as u32) as i32; + *last_virt_eip = eip & !0xFFF + } + dbg_assert!(!in_mapped_range((*eip_phys ^ eip) as u32)); + let data8 = *mem8.offset((*eip_phys ^ eip) as isize) as i32; + *instruction_pointer = eip + 1; + return Ok(data8); +} + +pub unsafe fn read_imm8s() -> OrPageFault { return Ok(read_imm8()? << 24 >> 24); } + +pub unsafe fn read_imm16() -> OrPageFault { + // Two checks in one comparison: + // 1. Did the high 20 bits of eip change + // or 2. Are the low 12 bits of eip 0xFFF (and this read crosses a page boundary) + if DISABLE_EIP_TRANSLATION_OPTIMISATION + || (*instruction_pointer ^ *last_virt_eip) as u32 > 0xFFE + { + return Ok(read_imm8()? | read_imm8()? << 8); + } + else { + let data16 = read16((*eip_phys ^ *instruction_pointer) as u32); + *instruction_pointer = *instruction_pointer + 2; + return Ok(data16); + }; +} + +pub unsafe fn read_imm32s() -> OrPageFault { + // Analogue to the above comment + if DISABLE_EIP_TRANSLATION_OPTIMISATION + || (*instruction_pointer ^ *last_virt_eip) as u32 > 0xFFC + { + return Ok(read_imm16()? | read_imm16()? << 16); + } + else { + let data32 = read32s((*eip_phys ^ *instruction_pointer) as u32); + *instruction_pointer = *instruction_pointer + 4; + return Ok(data32); + }; +} + +pub unsafe fn is_osize_32() -> bool { + dbg_assert!(!in_jit); + return *is_32 != (*prefixes as i32 & PREFIX_MASK_OPSIZE == PREFIX_MASK_OPSIZE); +} + +pub unsafe fn is_asize_32() -> bool { + dbg_assert!(!in_jit); + return *is_32 != (*prefixes as i32 & PREFIX_MASK_ADDRSIZE == PREFIX_MASK_ADDRSIZE); +} + +pub unsafe fn lookup_segment_selector( + selector: SegmentSelector, +) -> OrPageFault> { + if selector.is_null() { + return Ok(Err(SelectorNullOrInvalid::IsNull)); + } + + let (table_offset, table_limit) = if selector.is_gdt() { + (*gdtr_offset as u32, *gdtr_size as u16) + } + else { + ( + *segment_offsets.offset(LDTR as isize) as u32, + *segment_limits.offset(LDTR as isize) as u16, + ) + }; + + if selector.descriptor_offset() > table_limit { + return Ok(Err(SelectorNullOrInvalid::OutsideOfTableLimit)); + } + + let descriptor_address = selector.descriptor_offset() as i32 + table_offset as i32; + + let descriptor = SegmentDescriptor::of_u64(read64s(translate_address_system_read( + descriptor_address, + )?) as u64); + + Ok(Ok((descriptor, descriptor_address))) +} + +#[inline(never)] +pub unsafe fn switch_seg(reg: i32, selector_raw: i32) -> bool { + dbg_assert!(reg >= 0 && reg <= 5); + dbg_assert!(selector_raw >= 0 && selector_raw < 0x10000); + + if !*protected_mode || vm86_mode() { + *sreg.offset(reg as isize) = selector_raw as u16; + *segment_is_null.offset(reg as isize) = false; + *segment_offsets.offset(reg as isize) = selector_raw << 4; + + if reg == SS { + *stack_size_32 = false; + } + update_state_flags(); + return true; + } + + let selector = SegmentSelector::of_u16(selector_raw as u16); + let descriptor = match return_on_pagefault!(lookup_segment_selector(selector), false) { + Ok((desc, _)) => desc, + Err(selector_unusable) => { + // The selector couldn't be used to fetch a descriptor, so we handle all of those + // cases + if selector_unusable == SelectorNullOrInvalid::IsNull { + if reg == SS { + dbg_log!("#GP for loading 0 in SS sel={:x}", selector_raw); + trigger_gp(0); + return false; + } + else if reg != CS { + // es, ds, fs, gs + *sreg.offset(reg as isize) = selector_raw as u16; + *segment_is_null.offset(reg as isize) = true; + update_state_flags(); + return true; + } + } + else if selector_unusable == SelectorNullOrInvalid::OutsideOfTableLimit { + dbg_log!( + "#GP for loading invalid in seg={} sel={:x}", + reg, + selector_raw + ); + trigger_gp(selector_raw & !3); + return false; + } + + dbg_assert!(false); + return false; + }, + }; + + if reg == SS { + if descriptor.is_system() + || selector.rpl() != *cpl + || !descriptor.is_writable() + || descriptor.dpl() != *cpl + { + dbg_log!("#GP for loading invalid in SS sel={:x}", selector_raw); + trigger_gp(selector_raw & !3); + return false; + } + + if !descriptor.is_present() { + dbg_log!("#SS for loading non-present in SS sel={:x}", selector_raw); + trigger_ss(selector_raw & !3); + return false; + } + + *stack_size_32 = descriptor.is_32(); + } + else if reg == CS { + // handled by switch_cs_real_mode, far_return or far_jump + dbg_assert!(false); + } + else { + if descriptor.is_system() + || !descriptor.is_readable() + || (!descriptor.is_conforming_executable() + && (selector.rpl() > descriptor.dpl() || *cpl > descriptor.dpl())) + { + dbg_log!( + "#GP for loading invalid in seg {} sel={:x}", + reg, + selector_raw, + ); + trigger_gp(selector_raw & !3); + return false; + } + + if !descriptor.is_present() { + dbg_log!( + "#NP for loading not-present in seg {} sel={:x}", + reg, + selector_raw, + ); + trigger_np(selector_raw & !3); + return false; + } + } + + *segment_is_null.offset(reg as isize) = false; + *segment_limits.offset(reg as isize) = descriptor.effective_limit(); + *segment_offsets.offset(reg as isize) = descriptor.base(); + *sreg.offset(reg as isize) = selector_raw as u16; + + update_state_flags(); + + true +} + +pub unsafe fn load_tr(selector: i32) { + let selector = SegmentSelector::of_u16(selector as u16); + dbg_assert!(selector.is_gdt(), "TODO: TR can only be loaded from GDT"); + + let (descriptor, descriptor_address) = + match return_on_pagefault!(lookup_segment_selector(selector)) { + Ok((desc, addr)) => (desc, addr), + Err(SelectorNullOrInvalid::IsNull) => { + panic!("TODO: null TR"); + }, + Err(SelectorNullOrInvalid::OutsideOfTableLimit) => { + panic!("TODO: TR selector outside of table limit"); + }, + }; + + //dbg_log!( + // "load tr: {:x} offset={:x} limit={:x} is32={}", + // selector.raw, + // descriptor.base(), + // descriptor.effective_limit(), + // descriptor.system_type() == 9, + //); + + if !descriptor.is_system() { + panic!("#GP | ltr: not a system entry (happens when running kvm-unit-test without ACPI)"); + } + + if descriptor.system_type() != 9 && descriptor.system_type() != 1 { + // 0xB: busy 386 TSS (GP) + // 0x9: 386 TSS + // 0x3: busy 286 TSS (GP) + // 0x1: 286 TSS (??) + panic!( + "#GP | ltr: invalid type (type = 0x{:x})", + descriptor.system_type() + ); + } + + if !descriptor.is_present() { + panic!("#NT | present bit not set (ltr)"); + } + + *tss_size_32 = descriptor.system_type() == 9; + *segment_limits.offset(TR as isize) = descriptor.effective_limit(); + *segment_offsets.offset(TR as isize) = descriptor.base(); + *sreg.offset(TR as isize) = selector.raw; + + // Mark task as busy + safe_write64(descriptor_address, descriptor.set_busy().raw).unwrap(); +} + +pub unsafe fn load_ldt(selector: i32) -> OrPageFault<()> { + let selector = SegmentSelector::of_u16(selector as u16); + + if selector.is_null() { + *segment_limits.offset(LDTR as isize) = 0; + *segment_offsets.offset(LDTR as isize) = 0; + *sreg.offset(LDTR as isize) = selector.raw; + return Ok(()); + } + + dbg_assert!(selector.is_gdt(), "TODO: LDT can only be loaded from GDT"); + + let (descriptor, _) = match lookup_segment_selector(selector)? { + Ok((desc, addr)) => (desc, addr), + Err(SelectorNullOrInvalid::IsNull) => { + panic!("TODO: null TR"); + }, + Err(SelectorNullOrInvalid::OutsideOfTableLimit) => { + panic!("TODO: TR selector outside of table limit"); + }, + }; + + if !descriptor.is_present() { + panic!("#NT | present bit not set (lldt)"); + } + + if !descriptor.is_system() { + panic!("#GP | lldt: not a system entry"); + } + + if descriptor.system_type() != 2 { + panic!( + "#GP | lldt: invalid type (type = 0x{:x})", + descriptor.system_type() + ); + } + + *segment_limits.offset(LDTR as isize) = descriptor.effective_limit(); + *segment_offsets.offset(LDTR as isize) = descriptor.base(); + *sreg.offset(LDTR as isize) = selector.raw; + + Ok(()) +} + +#[no_mangle] +#[cfg(feature = "profiler")] +pub unsafe fn log_segment_null(segment: i32) { + dbg_assert!(segment >= 0 && segment < 8); + if *segment_is_null.offset(segment as isize) { + dbg_assert!(segment != CS && segment != SS); + dbg_log!("#gp: Access null segment in jit"); + } +} + +pub unsafe fn get_seg(segment: i32) -> OrPageFault { + dbg_assert!(segment >= 0 && segment < 8); + if *segment_is_null.offset(segment as isize) { + dbg_assert!(segment != CS && segment != SS); + dbg_log!("#gp: Access null segment"); + dbg_trace(); + dbg_assert!(!in_jit); + trigger_gp(0); + return Err(()); + } + return Ok(*segment_offsets.offset(segment as isize)); +} + +pub unsafe fn set_cr0(cr0: i32) { + let old_cr0 = *cr; + + if old_cr0 & CR0_AM == 0 && cr0 & CR0_AM != 0 { + dbg_log!("Warning: Unimplemented: cr0 alignment mask"); + } + if (cr0 & (CR0_PE | CR0_PG)) == CR0_PG { + panic!("cannot load PG without PE"); + } + + *cr = cr0; + *cr |= CR0_ET; + + if old_cr0 & (CR0_PG | CR0_WP) != cr0 & (CR0_PG | CR0_WP) { + full_clear_tlb(); + } + + if *cr.offset(4) & CR4_PAE != 0 + && old_cr0 & (CR0_CD | CR0_NW | CR0_PG) != cr0 & (CR0_CD | CR0_NW | CR0_PG) + { + load_pdpte(*cr.offset(3)) + } + + *protected_mode = (*cr & CR0_PE) == CR0_PE; +} + +pub unsafe fn set_cr3(mut cr3: i32) { + if false { + dbg_log!("cr3 <- {:x}", cr3); + } + if *cr.offset(4) & CR4_PAE != 0 { + cr3 &= !0b1111; + load_pdpte(cr3); + } + else { + cr3 &= !0b111111100111; + dbg_assert!(cr3 & 0xFFF == 0, "TODO"); + } + *cr.offset(3) = cr3; + clear_tlb(); +} + +pub unsafe fn load_pdpte(cr3: i32) { + dbg_assert!(cr3 & 0b1111 == 0); + for i in 0..4 { + let mut pdpt_entry = read64s(cr3 as u32 + 8 * i as u32) as u64; + pdpt_entry &= !0b1110_0000_0000; + dbg_assert!(pdpt_entry & 0b11000 == 0, "TODO"); + dbg_assert!( + pdpt_entry as u64 & 0xFFFF_FFFF_0000_0000 == 0, + "Unsupported: PDPT entry larger than 32 bits" + ); + if pdpt_entry as i32 & PAGE_TABLE_PRESENT_MASK != 0 { + dbg_assert!( + pdpt_entry & 0b1_1110_0110 == 0, + "TODO: #gp reserved bit in pdpte" + ); + } + *reg_pdpte.offset(i) = pdpt_entry; + } +} + +pub unsafe fn cpl_changed() { *last_virt_eip = -1 } + +pub unsafe fn update_cs_size(new_size: bool) { + if *is_32 != new_size { + *is_32 = new_size; + } +} + +#[inline(never)] +pub unsafe fn test_privileges_for_io(port: i32, size: i32) -> bool { + if *protected_mode && (*cpl > getiopl() as u8 || (*flags & FLAG_VM != 0)) { + if !*tss_size_32 { + dbg_log!("#GP for port io, 16-bit TSS port={:x} size={}", port, size); + trigger_gp(0); + return false; + } + + let tsr_size = *segment_limits.offset(TR as isize); + let tsr_offset = *segment_offsets.offset(TR as isize); + + if tsr_size >= 0x67 { + dbg_assert!(tsr_offset + 0x64 + 2 & 0xFFF < 0xFFF); + + let iomap_base = read16(return_on_pagefault!( + translate_address_system_read(tsr_offset + 0x64 + 2), + false + )); + let high_port = port + size - 1; + + if tsr_size >= (iomap_base + (high_port >> 3)) as u32 { + let mask = ((1 << size) - 1) << (port & 7); + let addr = return_on_pagefault!( + translate_address_system_read(tsr_offset + iomap_base + (port >> 3)), + false + ); + let port_info = if mask & 0xFF00 != 0 { read16(addr) } else { read8(addr) }; + + dbg_assert!(addr & 0xFFF < 0xFFF); + + if port_info & mask == 0 { + return true; + } + } + } + + dbg_log!("#GP for port io port={:x} size={}", port, size); + trigger_gp(0); + return false; + } + + return true; +} + +pub unsafe fn popa16() { + return_on_pagefault!(readable_or_pagefault(get_stack_pointer(0), 16)); + + write_reg16(DI, pop16().unwrap()); + write_reg16(SI, pop16().unwrap()); + write_reg16(BP, pop16().unwrap()); + adjust_stack_reg(2); + write_reg16(BX, pop16().unwrap()); + write_reg16(DX, pop16().unwrap()); + write_reg16(CX, pop16().unwrap()); + write_reg16(AX, pop16().unwrap()); +} + +pub unsafe fn popa32() { + return_on_pagefault!(readable_or_pagefault(get_stack_pointer(0), 32)); + + write_reg32(EDI, pop32s().unwrap()); + write_reg32(ESI, pop32s().unwrap()); + write_reg32(EBP, pop32s().unwrap()); + adjust_stack_reg(4); + write_reg32(EBX, pop32s().unwrap()); + write_reg32(EDX, pop32s().unwrap()); + write_reg32(ECX, pop32s().unwrap()); + write_reg32(EAX, pop32s().unwrap()); +} + +pub fn get_state_flags() -> CachedStateFlags { unsafe { *state_flags } } + +#[no_mangle] +pub fn get_seg_cs() -> i32 { unsafe { *segment_offsets.offset(CS as isize) } } + +pub unsafe fn get_seg_ss() -> i32 { return *segment_offsets.offset(SS as isize); } + +pub unsafe fn get_seg_prefix(default_segment: i32) -> OrPageFault { + dbg_assert!(!in_jit); + let prefix = *prefixes as i32 & PREFIX_MASK_SEGMENT; + if 0 != prefix { + if prefix == SEG_PREFIX_ZERO { + return Ok(0); + } + else { + return get_seg(prefix - 1); + } + } + else { + return get_seg(default_segment); + }; +} + +pub unsafe fn get_seg_prefix_ds(offset: i32) -> OrPageFault { + Ok(get_seg_prefix(DS)? + offset) +} + +pub unsafe fn get_seg_prefix_ss(offset: i32) -> OrPageFault { + Ok(get_seg_prefix(SS)? + offset) +} + +pub unsafe fn modrm_resolve(modrm_byte: i32) -> OrPageFault { + if is_asize_32() { resolve_modrm32(modrm_byte) } else { resolve_modrm16(modrm_byte) } +} + +pub unsafe fn run_instruction(opcode: i32) { ::gen::interpreter::run(opcode as u32) } +pub unsafe fn run_instruction0f_16(opcode: i32) { ::gen::interpreter0f::run(opcode as u32) } +pub unsafe fn run_instruction0f_32(opcode: i32) { ::gen::interpreter0f::run(opcode as u32 | 0x100) } + +#[no_mangle] +pub unsafe fn cycle_internal() { + profiler::stat_increment(CYCLE_INTERNAL); + if !::config::FORCE_DISABLE_JIT { + let mut jit_entry = None; + let initial_eip = *instruction_pointer; + let initial_state_flags = *state_flags; + + match tlb_code[(initial_eip as u32 >> 12) as usize] { + None => {}, + Some(c) => { + let c = c.as_ref(); + + if initial_state_flags == c.state_flags { + let state = c.state_table[initial_eip as usize & 0xFFF]; + if state != u16::MAX { + jit_entry = Some((c.wasm_table_index.to_u16(), state)); + } + else { + profiler::stat_increment(if is_near_end_of_page(initial_eip as u32) { + RUN_INTERPRETED_NEAR_END_OF_PAGE + } + else { + RUN_INTERPRETED_PAGE_HAS_CODE + }) + } + } + else { + profiler::stat_increment(RUN_INTERPRETED_DIFFERENT_STATE); + let s = *state_flags; + if c.state_flags.cpl3() != s.cpl3() { + profiler::stat_increment(RUN_INTERPRETED_DIFFERENT_STATE_CPL3); + } + if c.state_flags.has_flat_segmentation() != s.has_flat_segmentation() { + profiler::stat_increment(RUN_INTERPRETED_DIFFERENT_STATE_FLAT); + } + if c.state_flags.is_32() != s.is_32() { + profiler::stat_increment(RUN_INTERPRETED_DIFFERENT_STATE_IS32); + } + if c.state_flags.ssize_32() != s.ssize_32() { + profiler::stat_increment(RUN_INTERPRETED_DIFFERENT_STATE_SS32); + } + } + }, + } + + if let Some((wasm_table_index, initial_state)) = jit_entry { + if jit::CHECK_JIT_STATE_INVARIANTS { + match get_phys_eip() { + Err(()) => dbg_assert!(false), + Ok(phys_eip) => { + let entry = jit::jit_find_cache_entry(phys_eip, initial_state_flags); + dbg_assert!(entry.wasm_table_index.to_u16() == wasm_table_index); + dbg_assert!(entry.initial_state == initial_state); + }, + } + } + profiler::stat_increment(RUN_FROM_CACHE); + let initial_instruction_counter = *instruction_counter; + #[cfg(debug_assertions)] + { + in_jit = true; + } + call_indirect1( + wasm_table_index as i32 + WASM_TABLE_OFFSET as i32, + initial_state, + ); + #[cfg(debug_assertions)] + { + in_jit = false; + } + profiler::stat_increment_by( + RUN_FROM_CACHE_STEPS, + (*instruction_counter - initial_instruction_counter) as u64, + ); + dbg_assert!( + *instruction_counter != initial_instruction_counter, + "Instruction counter didn't change" + ); + + if cfg!(feature = "profiler") { + dbg_assert!(match ::cpu::cpu::debug_last_jump { + LastJump::Compiled { .. } => true, + _ => false, + }); + let last_jump_addr = ::cpu::cpu::debug_last_jump.phys_address().unwrap(); + let last_jump_opcode = if last_jump_addr != 0 { + read32s(last_jump_addr) + } + else { + // Happens during exit due to loop iteration limit + 0 + }; + + ::opstats::record_opstat_jit_exit(last_jump_opcode as u32); + } + + if is_near_end_of_page(*instruction_pointer as u32) { + profiler::stat_increment(RUN_FROM_CACHE_EXIT_NEAR_END_OF_PAGE); + } + else if Page::page_of(initial_eip as u32) + == Page::page_of(*instruction_pointer as u32) + { + profiler::stat_increment(RUN_FROM_CACHE_EXIT_SAME_PAGE); + } + else { + profiler::stat_increment(RUN_FROM_CACHE_EXIT_DIFFERENT_PAGE); + } + } + else { + *previous_ip = initial_eip; + let phys_addr = return_on_pagefault!(get_phys_eip()); + + match tlb_code[(initial_eip as u32 >> 12) as usize] { + None => {}, + Some(c) => { + let c = c.as_ref(); + + if initial_state_flags == c.state_flags + && c.state_table[initial_eip as usize & 0xFFF] != u16::MAX + { + profiler::stat_increment(RUN_INTERPRETED_PAGE_HAS_ENTRY_AFTER_PAGE_WALK); + return; + } + }, + } + + #[cfg(feature = "profiler")] + { + if CHECK_MISSED_ENTRY_POINTS { + jit::check_missed_entry_points(phys_addr, initial_state_flags); + } + } + + let initial_instruction_counter = *instruction_counter; + jit_run_interpreted(phys_addr); + + jit::jit_increase_hotness_and_maybe_compile( + initial_eip, + phys_addr, + get_seg_cs() as u32, + initial_state_flags, + *instruction_counter - initial_instruction_counter, + ); + + profiler::stat_increment_by( + RUN_INTERPRETED_STEPS, + (*instruction_counter - initial_instruction_counter) as u64, + ); + dbg_assert!( + *instruction_counter != initial_instruction_counter, + "Instruction counter didn't change" + ); + }; + } + else { + *previous_ip = *instruction_pointer; + + let opcode = return_on_pagefault!(read_imm8()); + *instruction_counter += 1; + dbg_assert!(*prefixes == 0); + run_instruction(opcode | (*is_32 as i32) << 8); + dbg_assert!(*prefixes == 0); + } +} + +pub unsafe fn get_phys_eip() -> OrPageFault { + let eip = *instruction_pointer; + if 0 != eip & !0xFFF ^ *last_virt_eip { + *eip_phys = (translate_address_read(eip)? ^ eip as u32) as i32; + *last_virt_eip = eip & !0xFFF + } + let phys_addr = (*eip_phys ^ eip) as u32; + dbg_assert!(!in_mapped_range(phys_addr)); + return Ok(phys_addr); +} + +unsafe fn jit_run_interpreted(mut phys_addr: u32) { + profiler::stat_increment(RUN_INTERPRETED); + dbg_assert!(!in_mapped_range(phys_addr)); + + jit_block_boundary = false; + let mut i = 0; + + loop { + if CHECK_MISSED_ENTRY_POINTS { + let entry = jit::jit_find_cache_entry(phys_addr, *state_flags); + if entry != jit::CachedCode::NONE { + profiler::stat_increment(RUN_INTERPRETED_MISSED_COMPILED_ENTRY_RUN_INTERPRETED); + } + } + + i += 1; + let start_eip = *instruction_pointer; + let opcode = *mem8.offset(phys_addr as isize) as i32; + *instruction_pointer += 1; + dbg_assert!(*prefixes == 0); + run_instruction(opcode | (*is_32 as i32) << 8); + dbg_assert!(*prefixes == 0); + + if jit_block_boundary + || Page::page_of(start_eip as u32) != Page::page_of(*instruction_pointer as u32) + // Limit the number of iterations, as jumps within the same page are not counted as + // block boundaries for the interpreter, but only on the next backwards jump + || (i >= INTERPRETER_ITERATION_LIMIT + && (start_eip as u32) >= (*instruction_pointer as u32)) + { + break; + } + + *previous_ip = *instruction_pointer; + phys_addr = return_on_pagefault!(get_phys_eip()) as u32; + } + + if cfg!(debug_assertions) { + debug_last_jump = LastJump::Interpreted { phys_addr }; + } + + *instruction_counter += i; +} + +#[no_mangle] +pub fn update_state_flags() { + unsafe { + *state_flags = CachedStateFlags::of_u32( + (*is_32 as u32) << 0 + | (*stack_size_32 as u32) << 1 + | ((*cpl == 3) as u32) << 2 + | (has_flat_segmentation() as u32) << 3, + ) + } +} + +#[no_mangle] +pub unsafe fn has_flat_segmentation() -> bool { + // cs/ss can't be null + return *segment_offsets.offset(SS as isize) == 0 + && !*segment_is_null.offset(DS as isize) + && *segment_offsets.offset(DS as isize) == 0 + && *segment_offsets.offset(CS as isize) == 0; +} + +pub unsafe fn run_prefix_instruction() { + run_instruction(return_on_pagefault!(read_imm8()) | (is_osize_32() as i32) << 8); +} + +pub unsafe fn segment_prefix_op(seg: i32) { + dbg_assert!(seg <= 5); + *prefixes = (*prefixes as i32 | seg + 1) as u8; + run_prefix_instruction(); + *prefixes = 0 +} + +#[no_mangle] +pub unsafe fn do_many_cycles_native() { + profiler::stat_increment(DO_MANY_CYCLES); + let initial_instruction_counter = *instruction_counter; + while (*instruction_counter).wrapping_sub(initial_instruction_counter) < LOOP_COUNTER as u32 + && !*in_hlt + { + cycle_internal(); + } +} + +#[inline(never)] +pub unsafe fn trigger_de() { + dbg_log!("#de"); + *instruction_pointer = *previous_ip; + if DEBUG { + if cpu_exception_hook(CPU_EXCEPTION_DE) { + return; + } + } + call_interrupt_vector(CPU_EXCEPTION_DE, false, None); +} + +#[inline(never)] +pub unsafe fn trigger_ud() { + dbg_log!("#ud"); + dbg_trace(); + *instruction_pointer = *previous_ip; + if DEBUG { + if cpu_exception_hook(CPU_EXCEPTION_UD) { + return; + } + } + call_interrupt_vector(CPU_EXCEPTION_UD, false, None); +} + +#[inline(never)] +pub unsafe fn trigger_nm() { + dbg_log!("#nm eip={:x}", *previous_ip); + dbg_trace(); + *instruction_pointer = *previous_ip; + if DEBUG { + if cpu_exception_hook(CPU_EXCEPTION_NM) { + return; + } + } + call_interrupt_vector(CPU_EXCEPTION_NM, false, None); +} + +#[inline(never)] +pub unsafe fn trigger_gp(code: i32) { + dbg_log!("#gp"); + *instruction_pointer = *previous_ip; + if DEBUG { + if cpu_exception_hook(CPU_EXCEPTION_GP) { + return; + } + } + call_interrupt_vector(CPU_EXCEPTION_GP, false, Some(code)); +} + +pub unsafe fn virt_boundary_read16(low: u32, high: u32) -> i32 { + dbg_assert!(low & 0xFFF == 0xFFF); + dbg_assert!(high & 0xFFF == 0); + return read8(low as u32) | read8(high as u32) << 8; +} + +pub unsafe fn virt_boundary_read32s(low: u32, high: u32) -> i32 { + dbg_assert!(low & 0xFFF >= 0xFFD); + dbg_assert!(high - 3 & 0xFFF == low & 0xFFF); + let mid; + if 0 != low & 1 { + if 0 != low & 2 { + // 0xFFF + mid = read16(high - 2) + } + else { + // 0xFFD + mid = read16(low + 1) + } + } + else { + // 0xFFE + mid = virt_boundary_read16(low + 1, high - 1) + } + return read8(low as u32) | mid << 8 | read8(high as u32) << 24; +} + +pub unsafe fn virt_boundary_write16(low: u32, high: u32, value: i32) { + dbg_assert!(low & 0xFFF == 0xFFF); + dbg_assert!(high & 0xFFF == 0); + write8(low as u32, value); + write8(high as u32, value >> 8); +} + +pub unsafe fn virt_boundary_write32(low: u32, high: u32, value: i32) { + dbg_assert!(low & 0xFFF >= 0xFFD); + dbg_assert!(high - 3 & 0xFFF == low & 0xFFF); + write8(low as u32, value); + if 0 != low & 1 { + if 0 != low & 2 { + // 0xFFF + write8((high - 2) as u32, value >> 8); + write8((high - 1) as u32, value >> 16); + } + else { + // 0xFFD + write8((low + 1) as u32, value >> 8); + write8((low + 2) as u32, value >> 16); + } + } + else { + // 0xFFE + write8((low + 1) as u32, value >> 8); + write8((high - 1) as u32, value >> 16); + } + write8(high as u32, value >> 24); +} + +pub unsafe fn safe_read8(addr: i32) -> OrPageFault { Ok(read8(translate_address_read(addr)?)) } + +pub unsafe fn safe_read16(addr: i32) -> OrPageFault { + if addr & 0xFFF == 0xFFF { + Ok(safe_read8(addr)? | safe_read8(addr + 1)? << 8) + } + else { + Ok(read16(translate_address_read(addr)?)) + } +} + +pub unsafe fn safe_read32s(addr: i32) -> OrPageFault { + if addr & 0xFFF >= 0xFFD { + Ok(safe_read16(addr)? | safe_read16(addr + 2)? << 16) + } + else { + Ok(read32s(translate_address_read(addr)?)) + } +} + +pub unsafe fn safe_read_f32(addr: i32) -> OrPageFault { + Ok(std::mem::transmute(safe_read32s(addr)?)) +} + +pub unsafe fn safe_read64s(addr: i32) -> OrPageFault { + if addr & 0xFFF > 0x1000 - 8 { + Ok(safe_read32s(addr)? as u32 as u64 | (safe_read32s(addr + 4)? as u32 as u64) << 32) + } + else { + Ok(read64s(translate_address_read(addr)?) as u64) + } +} + +pub unsafe fn safe_read128s(addr: i32) -> OrPageFault { + if addr & 0xFFF > 0x1000 - 16 { + Ok(reg128 { + u64: [safe_read64s(addr)?, safe_read64s(addr + 8)?], + }) + } + else { + Ok(read128(translate_address_read(addr)?)) + } +} + +#[no_mangle] +#[cfg(feature = "profiler")] +pub fn report_safe_read_jit_slow(address: u32, entry: i32) { + if entry & TLB_VALID == 0 { + profiler::stat_increment(SAFE_READ_SLOW_NOT_VALID); + } + else if entry & TLB_IN_MAPPED_RANGE != 0 { + profiler::stat_increment(SAFE_READ_SLOW_IN_MAPPED_RANGE); + } + else if entry & TLB_NO_USER != 0 { + profiler::stat_increment(SAFE_READ_SLOW_NOT_USER); + } + else if address & 0xFFF > 0x1000 - 16 { + profiler::stat_increment(SAFE_READ_SLOW_PAGE_CROSSED); + } + else { + dbg_log!("Unexpected entry bit: {:x} (read at {:x})", entry, address); + dbg_assert!(false); + } +} + +#[no_mangle] +#[cfg(feature = "profiler")] +pub fn report_safe_write_jit_slow(address: u32, entry: i32) { + if entry & TLB_VALID == 0 { + profiler::stat_increment(SAFE_WRITE_SLOW_NOT_VALID); + } + else if entry & TLB_IN_MAPPED_RANGE != 0 { + profiler::stat_increment(SAFE_WRITE_SLOW_IN_MAPPED_RANGE); + } + else if entry & TLB_HAS_CODE != 0 { + profiler::stat_increment(SAFE_WRITE_SLOW_HAS_CODE); + } + else if entry & TLB_READONLY != 0 { + profiler::stat_increment(SAFE_WRITE_SLOW_READ_ONLY); + } + else if entry & TLB_NO_USER != 0 { + profiler::stat_increment(SAFE_WRITE_SLOW_NOT_USER); + } + else if address & 0xFFF > 0x1000 - 16 { + profiler::stat_increment(SAFE_WRITE_SLOW_PAGE_CROSSED); + } + else { + dbg_assert!(false); + } +} + +#[no_mangle] +#[cfg(feature = "profiler")] +pub fn report_safe_read_write_jit_slow(address: u32, entry: i32) { + if entry & TLB_VALID == 0 { + profiler::stat_increment(SAFE_READ_WRITE_SLOW_NOT_VALID); + } + else if entry & TLB_IN_MAPPED_RANGE != 0 { + profiler::stat_increment(SAFE_READ_WRITE_SLOW_IN_MAPPED_RANGE); + } + else if entry & TLB_HAS_CODE != 0 { + profiler::stat_increment(SAFE_READ_WRITE_SLOW_HAS_CODE); + } + else if entry & TLB_READONLY != 0 { + profiler::stat_increment(SAFE_READ_WRITE_SLOW_READ_ONLY); + } + else if entry & TLB_NO_USER != 0 { + profiler::stat_increment(SAFE_READ_WRITE_SLOW_NOT_USER); + } + else if address & 0xFFF > 0x1000 - 16 { + profiler::stat_increment(SAFE_READ_WRITE_SLOW_PAGE_CROSSED); + } + else { + dbg_assert!(false); + } +} + +#[repr(align(0x1000))] +struct ScratchBuffer([u8; 0x1000 * 2]); +static mut jit_paging_scratch_buffer: ScratchBuffer = ScratchBuffer([0; 2 * 0x1000]); + +pub unsafe fn safe_read_slow_jit(addr: i32, bitsize: i32, start_eip: i32, is_write: bool) -> i32 { + if is_write && Page::page_of(*instruction_pointer as u32) == Page::page_of(addr as u32) { + // XXX: Check based on virtual address + dbg_log!( + "SMC (rmw): bits={} eip={:x} writeaddr={:x}", + bitsize, + start_eip as u32, + addr as u32 + ); + } + let crosses_page = (addr & 0xFFF) + bitsize / 8 > 0x1000; + let addr_low = match if is_write { + translate_address_write_jit_and_can_skip_dirty(addr).map(|x| x.0) + } + else { + translate_address_read_jit(addr) + } { + Err(()) => { + *instruction_pointer = *instruction_pointer & !0xFFF | start_eip & 0xFFF; + return 1; + }, + Ok(addr) => addr, + }; + if crosses_page { + let boundary_addr = (addr | 0xFFF) + 1; + let addr_high = match if is_write { + translate_address_write_jit_and_can_skip_dirty(boundary_addr).map(|x| x.0) + } + else { + translate_address_read_jit(boundary_addr) + } { + Err(()) => { + *instruction_pointer = *instruction_pointer & !0xFFF | start_eip & 0xFFF; + return 1; + }, + Ok(addr) => addr, + }; + // TODO: Could check if virtual pages point to consecutive physical and go to fast path + // do read, write into scratch buffer + + let scratch = jit_paging_scratch_buffer.0.as_mut_ptr() as u32; + dbg_assert!(scratch & 0xFFF == 0); + + for s in addr_low..((addr_low | 0xFFF) + 1) { + *(scratch as *mut u8).offset((s & 0xFFF) as isize) = read8(s) as u8 + } + for s in addr_high..(addr_high + (addr + bitsize / 8 & 0xFFF) as u32) { + *(scratch as *mut u8).offset((0x1000 | s & 0xFFF) as isize) = read8(s) as u8 + } + + ((scratch as i32) ^ addr) & !0xFFF + } + else if in_mapped_range(addr_low) { + let scratch = jit_paging_scratch_buffer.0.as_mut_ptr(); + + match bitsize { + 128 => { + *(scratch.offset(addr_low as isize & 0xFFF) as *mut reg128) = + memory::read128(addr_low) + }, + 64 => { + *(scratch.offset(addr_low as isize & 0xFFF) as *mut i64) = memory::read64s(addr_low) + }, + 32 => { + *(scratch.offset(addr_low as isize & 0xFFF) as *mut i32) = memory::read32s(addr_low) + }, + 16 => { + *(scratch.offset(addr_low as isize & 0xFFF) as *mut u16) = + memory::read16(addr_low) as u16 + }, + 8 => { + *(scratch.offset(addr_low as isize & 0xFFF) as *mut u8) = + memory::read8(addr_low) as u8 + }, + _ => { + dbg_assert!(false); + }, + } + + ((scratch as i32) ^ addr) & !0xFFF + } + else { + ((addr_low as i32 + memory::mem8 as i32) ^ addr) & !0xFFF + } +} + +#[no_mangle] +pub unsafe fn safe_read8_slow_jit(addr: i32, eip: i32) -> i32 { + safe_read_slow_jit(addr, 8, eip, false) +} +#[no_mangle] +pub unsafe fn safe_read16_slow_jit(addr: i32, eip: i32) -> i32 { + safe_read_slow_jit(addr, 16, eip, false) +} +#[no_mangle] +pub unsafe fn safe_read32s_slow_jit(addr: i32, eip: i32) -> i32 { + safe_read_slow_jit(addr, 32, eip, false) +} +#[no_mangle] +pub unsafe fn safe_read64s_slow_jit(addr: i32, eip: i32) -> i32 { + safe_read_slow_jit(addr, 64, eip, false) +} +#[no_mangle] +pub unsafe fn safe_read128s_slow_jit(addr: i32, eip: i32) -> i32 { + safe_read_slow_jit(addr, 128, eip, false) +} + +#[no_mangle] +pub unsafe fn get_phys_eip_slow_jit(addr: i32) -> i32 { + match translate_address_read_jit(addr) { + Err(()) => 1, + Ok(addr_low) => { + dbg_assert!(!in_mapped_range(addr_low as u32)); // same assumption as in read_imm8 + ((addr_low as i32 + memory::mem8 as i32) ^ addr) & !0xFFF + }, + } +} + +#[no_mangle] +pub unsafe fn safe_read_write8_slow_jit(addr: i32, eip: i32) -> i32 { + safe_read_slow_jit(addr, 8, eip, true) +} +#[no_mangle] +pub unsafe fn safe_read_write16_slow_jit(addr: i32, eip: i32) -> i32 { + safe_read_slow_jit(addr, 16, eip, true) +} +#[no_mangle] +pub unsafe fn safe_read_write32s_slow_jit(addr: i32, eip: i32) -> i32 { + safe_read_slow_jit(addr, 32, eip, true) +} +#[no_mangle] +pub unsafe fn safe_read_write64_slow_jit(addr: i32, eip: i32) -> i32 { + safe_read_slow_jit(addr, 64, eip, true) +} + +pub unsafe fn safe_write_slow_jit( + addr: i32, + bitsize: i32, + value_low: u64, + value_high: u64, + start_eip: i32, +) -> i32 { + if Page::page_of(*instruction_pointer as u32) == Page::page_of(addr as u32) { + // XXX: Check based on virtual address + dbg_log!( + "SMC: bits={} eip={:x} writeaddr={:x}", + bitsize, + start_eip as u32, + addr as u32 + ); + } + let crosses_page = (addr & 0xFFF) + bitsize / 8 > 0x1000; + let (addr_low, can_skip_dirty_page) = match translate_address_write_jit_and_can_skip_dirty(addr) + { + Err(()) => { + *instruction_pointer = *instruction_pointer & !0xFFF | start_eip & 0xFFF; + return 1; + }, + Ok(x) => x, + }; + if crosses_page { + let (addr_high, _) = + match translate_address_write_jit_and_can_skip_dirty((addr | 0xFFF) + 1) { + Err(()) => { + *instruction_pointer = *instruction_pointer & !0xFFF | start_eip & 0xFFF; + return 1; + }, + Ok(x) => x, + }; + // TODO: Could check if virtual pages point to consecutive physical and go to fast path + + // do write, return dummy pointer for fast path to write into + + match bitsize { + 128 => safe_write128( + addr, + reg128 { + u64: [value_low, value_high], + }, + ) + .unwrap(), + 64 => safe_write64(addr, value_low).unwrap(), + 32 => virt_boundary_write32( + addr_low, + addr_high | (addr as u32 + 3 & 3), + value_low as i32, + ), + 16 => virt_boundary_write16(addr_low, addr_high, value_low as i32), + 8 => { + dbg_assert!(false); + }, + _ => { + dbg_assert!(false); + }, + } + + let scratch = jit_paging_scratch_buffer.0.as_mut_ptr() as u32; + dbg_assert!(scratch & 0xFFF == 0); + ((scratch as i32) ^ addr) & !0xFFF + } + else if in_mapped_range(addr_low) { + match bitsize { + 128 => memory::mmap_write128(addr_low, value_low, value_high), + 64 => memory::mmap_write64(addr_low, value_low), + 32 => memory::mmap_write32(addr_low, value_low as i32), + 16 => memory::mmap_write16(addr_low, (value_low & 0xFFFF) as i32), + 8 => memory::mmap_write8(addr_low, (value_low & 0xFF) as i32), + _ => { + dbg_assert!(false); + }, + } + + let scratch = jit_paging_scratch_buffer.0.as_mut_ptr() as u32; + dbg_assert!(scratch & 0xFFF == 0); + ((scratch as i32) ^ addr) & !0xFFF + } + else { + if !can_skip_dirty_page { + jit::jit_dirty_page(jit::get_jit_state(), Page::page_of(addr_low)); + } + ((addr_low as i32 + memory::mem8 as i32) ^ addr) & !0xFFF + } +} + +#[no_mangle] +pub unsafe fn safe_write8_slow_jit(addr: i32, value: u32, start_eip: i32) -> i32 { + safe_write_slow_jit(addr, 8, value as u64, 0, start_eip) +} +#[no_mangle] +pub unsafe fn safe_write16_slow_jit(addr: i32, value: u32, start_eip: i32) -> i32 { + safe_write_slow_jit(addr, 16, value as u64, 0, start_eip) +} +#[no_mangle] +pub unsafe fn safe_write32_slow_jit(addr: i32, value: u32, start_eip: i32) -> i32 { + safe_write_slow_jit(addr, 32, value as u64, 0, start_eip) +} +#[no_mangle] +pub unsafe fn safe_write64_slow_jit(addr: i32, value: u64, start_eip: i32) -> i32 { + safe_write_slow_jit(addr, 64, value, 0, start_eip) +} +#[no_mangle] +pub unsafe fn safe_write128_slow_jit(addr: i32, low: u64, high: u64, start_eip: i32) -> i32 { + safe_write_slow_jit(addr, 128, low, high, start_eip) +} + +pub unsafe fn safe_write8(addr: i32, value: i32) -> OrPageFault<()> { + let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?; + if in_mapped_range(phys_addr) { + memory::mmap_write8(phys_addr, value); + } + else { + if !can_skip_dirty_page { + jit::jit_dirty_page(jit::get_jit_state(), Page::page_of(phys_addr)); + } + else { + dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32))); + } + memory::write8_no_mmap_or_dirty_check(phys_addr, value); + }; + Ok(()) +} + +pub unsafe fn safe_write16(addr: i32, value: i32) -> OrPageFault<()> { + let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?; + if addr & 0xFFF == 0xFFF { + virt_boundary_write16(phys_addr, translate_address_write(addr + 1)?, value); + } + else if in_mapped_range(phys_addr) { + memory::mmap_write16(phys_addr, value); + } + else { + if !can_skip_dirty_page { + jit::jit_dirty_page(jit::get_jit_state(), Page::page_of(phys_addr)); + } + else { + dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32))); + } + memory::write16_no_mmap_or_dirty_check(phys_addr, value); + }; + Ok(()) +} + +pub unsafe fn safe_write32(addr: i32, value: i32) -> OrPageFault<()> { + let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?; + if addr & 0xFFF > 0x1000 - 4 { + virt_boundary_write32( + phys_addr, + translate_address_write(addr + 3 & !3)? | (addr as u32 + 3 & 3), + value, + ); + } + else if in_mapped_range(phys_addr) { + memory::mmap_write32(phys_addr, value); + } + else { + if !can_skip_dirty_page { + jit::jit_dirty_page(jit::get_jit_state(), Page::page_of(phys_addr)); + } + else { + dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32))); + } + memory::write32_no_mmap_or_dirty_check(phys_addr, value); + }; + Ok(()) +} + +pub unsafe fn safe_write64(addr: i32, value: u64) -> OrPageFault<()> { + if addr & 0xFFF > 0x1000 - 8 { + writable_or_pagefault(addr, 8)?; + safe_write32(addr, value as i32).unwrap(); + safe_write32(addr + 4, (value >> 32) as i32).unwrap(); + } + else { + let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?; + if in_mapped_range(phys_addr) { + memory::mmap_write64(phys_addr, value); + } + else { + if !can_skip_dirty_page { + jit::jit_dirty_page(jit::get_jit_state(), Page::page_of(phys_addr)); + } + else { + dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32))); + } + memory::write64_no_mmap_or_dirty_check(phys_addr, value); + } + }; + Ok(()) +} + +pub unsafe fn safe_write128(addr: i32, value: reg128) -> OrPageFault<()> { + if addr & 0xFFF > 0x1000 - 16 { + writable_or_pagefault(addr, 16)?; + safe_write64(addr, value.u64[0]).unwrap(); + safe_write64(addr + 8, value.u64[1]).unwrap(); + } + else { + let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?; + if in_mapped_range(phys_addr) { + memory::mmap_write128(phys_addr, value.u64[0], value.u64[1]); + } + else { + if !can_skip_dirty_page { + jit::jit_dirty_page(jit::get_jit_state(), Page::page_of(phys_addr)); + } + else { + dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32))); + } + memory::write128_no_mmap_or_dirty_check(phys_addr, value); + } + }; + Ok(()) +} + +#[inline(always)] +pub unsafe fn safe_read_write8(addr: i32, instruction: &dyn Fn(i32) -> i32) { + let (phys_addr, can_skip_dirty_page) = + return_on_pagefault!(translate_address_write_and_can_skip_dirty(addr)); + let x = memory::read8(phys_addr); + let value = instruction(x); + if memory::in_mapped_range(phys_addr) { + memory::mmap_write8(phys_addr, value); + } + else { + if !can_skip_dirty_page { + ::jit::jit_dirty_page(::jit::get_jit_state(), Page::page_of(phys_addr)); + } + else { + dbg_assert!(!::jit::jit_page_has_code(Page::page_of(phys_addr as u32))); + } + memory::write8_no_mmap_or_dirty_check(phys_addr, value); + } +} + +#[inline(always)] +pub unsafe fn safe_read_write16(addr: i32, instruction: &dyn Fn(i32) -> i32) { + let (phys_addr, can_skip_dirty_page) = + return_on_pagefault!(translate_address_write_and_can_skip_dirty(addr)); + if phys_addr & 0xFFF == 0xFFF { + let phys_addr_high = return_on_pagefault!(translate_address_write(addr + 1)); + let x = virt_boundary_read16(phys_addr, phys_addr_high); + virt_boundary_write16(phys_addr, phys_addr_high, instruction(x)); + } + else { + let x = memory::read16(phys_addr); + let value = instruction(x); + if memory::in_mapped_range(phys_addr) { + memory::mmap_write16(phys_addr, value); + } + else { + if !can_skip_dirty_page { + ::jit::jit_dirty_page(::jit::get_jit_state(), Page::page_of(phys_addr)); + } + else { + dbg_assert!(!::jit::jit_page_has_code(Page::page_of(phys_addr as u32))); + } + memory::write16_no_mmap_or_dirty_check(phys_addr, value); + }; + } +} + +#[inline(always)] +pub unsafe fn safe_read_write32(addr: i32, instruction: &dyn Fn(i32) -> i32) { + let (phys_addr, can_skip_dirty_page) = + return_on_pagefault!(translate_address_write_and_can_skip_dirty(addr)); + if phys_addr & 0xFFF >= 0xFFD { + let phys_addr_high = return_on_pagefault!(translate_address_write(addr + 3 & !3)); + let phys_addr_high = phys_addr_high | (addr as u32) + 3 & 3; + let x = virt_boundary_read32s(phys_addr, phys_addr_high); + virt_boundary_write32(phys_addr, phys_addr_high, instruction(x)); + } + else { + let x = memory::read32s(phys_addr); + let value = instruction(x); + if memory::in_mapped_range(phys_addr) { + memory::mmap_write32(phys_addr, value); + } + else { + if !can_skip_dirty_page { + ::jit::jit_dirty_page(::jit::get_jit_state(), Page::page_of(phys_addr)); + } + else { + dbg_assert!(!::jit::jit_page_has_code(Page::page_of(phys_addr as u32))); + } + memory::write32_no_mmap_or_dirty_check(phys_addr, value); + }; + } +} + +fn get_reg8_index(index: i32) -> i32 { return index << 2 & 12 | index >> 2 & 1; } + +pub unsafe fn read_reg8(index: i32) -> i32 { + dbg_assert!(index >= 0 && index < 8); + return *reg8.offset(get_reg8_index(index) as isize) as i32; +} + +pub unsafe fn write_reg8(index: i32, value: i32) { + dbg_assert!(index >= 0 && index < 8); + *reg8.offset(get_reg8_index(index) as isize) = value as u8; +} + +fn get_reg16_index(index: i32) -> i32 { return index << 1; } + +pub unsafe fn read_reg16(index: i32) -> i32 { + dbg_assert!(index >= 0 && index < 8); + return *reg16.offset(get_reg16_index(index) as isize) as i32; +} + +pub unsafe fn write_reg16(index: i32, value: i32) { + dbg_assert!(index >= 0 && index < 8); + *reg16.offset(get_reg16_index(index) as isize) = value as u16; +} + +pub unsafe fn read_reg32(index: i32) -> i32 { + dbg_assert!(index >= 0 && index < 8); + *reg32.offset(index as isize) +} + +pub unsafe fn write_reg32(index: i32, value: i32) { + dbg_assert!(index >= 0 && index < 8); + *reg32.offset(index as isize) = value; +} + +pub unsafe fn read_mmx32s(r: i32) -> i32 { (*fpu_st.offset(r as isize)).mantissa as i32 } + +pub unsafe fn read_mmx64s(r: i32) -> u64 { (*fpu_st.offset(r as isize)).mantissa } + +pub unsafe fn write_mmx_reg64(r: i32, data: u64) { (*fpu_st.offset(r as isize)).mantissa = data; } + +pub unsafe fn read_xmm_f32(r: i32) -> f32 { return (*reg_xmm.offset(r as isize)).f32[0]; } + +pub unsafe fn read_xmm32(r: i32) -> i32 { return (*reg_xmm.offset(r as isize)).u32[0] as i32; } + +pub unsafe fn read_xmm64s(r: i32) -> u64 { (*reg_xmm.offset(r as isize)).u64[0] } + +pub unsafe fn read_xmm128s(r: i32) -> reg128 { return *reg_xmm.offset(r as isize); } + +pub unsafe fn write_xmm_f32(r: i32, data: f32) { (*reg_xmm.offset(r as isize)).f32[0] = data; } + +pub unsafe fn write_xmm32(r: i32, data: i32) { (*reg_xmm.offset(r as isize)).i32[0] = data; } + +pub unsafe fn write_xmm64(r: i32, data: u64) { (*reg_xmm.offset(r as isize)).u64[0] = data } +pub unsafe fn write_xmm_f64(r: i32, data: f64) { (*reg_xmm.offset(r as isize)).f64[0] = data } + +pub unsafe fn write_xmm128(r: i32, i0: i32, i1: i32, i2: i32, i3: i32) { + let x = reg128 { + u32: [i0 as u32, i1 as u32, i2 as u32, i3 as u32], + }; + *reg_xmm.offset(r as isize) = x; +} + +pub unsafe fn write_xmm128_2(r: i32, i0: u64, i1: u64) { + *reg_xmm.offset(r as isize) = reg128 { u64: [i0, i1] }; +} + +pub unsafe fn write_xmm_reg128(r: i32, data: reg128) { *reg_xmm.offset(r as isize) = data; } + +/// Set the fpu tag word to valid and the top-of-stack to 0 on mmx instructions +pub fn transition_fpu_to_mmx() { + unsafe { + fpu_set_tag_word(0); + *fpu_stack_ptr = 0; + } +} + +pub unsafe fn task_switch_test() -> bool { + if 0 != *cr & (CR0_EM | CR0_TS) { + trigger_nm(); + return false; + } + else { + return true; + }; +} + +pub unsafe fn set_mxcsr(new_mxcsr: i32) { + dbg_assert!(new_mxcsr & !MXCSR_MASK == 0); // checked by caller + + if *mxcsr & MXCSR_DAZ == 0 && new_mxcsr & MXCSR_DAZ != 0 { + dbg_log!("Warning: Unimplemented MXCSR bit: Denormals Are Zero"); + } + if *mxcsr & MXCSR_FZ == 0 && new_mxcsr & MXCSR_FZ != 0 { + dbg_log!("Warning: Unimplemented MXCSR bit: Flush To Zero"); + } + + let rounding_mode = new_mxcsr >> MXCSR_RC_SHIFT & 3; + if *mxcsr >> MXCSR_RC_SHIFT & 3 == 0 && rounding_mode != 0 { + dbg_log!( + "Warning: Unimplemented MXCSR rounding mode: {}", + rounding_mode + ); + } + + let exception_mask = new_mxcsr >> 7 & 0b111111; + if *mxcsr >> 7 & 0b111111 != exception_mask && exception_mask != 0b111111 { + dbg_log!( + "Warning: Unimplemented MXCSR exception mask: 0b{:b}", + exception_mask + ); + } + + *mxcsr = new_mxcsr; +} + +#[no_mangle] +pub unsafe fn task_switch_test_jit(start_eip: i32) { + dbg_assert!(0 != *cr & (CR0_EM | CR0_TS)); + trigger_nm_jit(start_eip); +} + +pub unsafe fn task_switch_test_mmx() -> bool { + if *cr.offset(4) & CR4_OSFXSR == 0 { + dbg_log!("Warning: Unimplemented task switch test with cr4.osfxsr=0"); + } + if 0 != *cr & CR0_EM { + trigger_ud(); + return false; + } + else if 0 != *cr & CR0_TS { + trigger_nm(); + return false; + } + else { + return true; + }; +} + +#[no_mangle] +pub unsafe fn task_switch_test_mmx_jit(start_eip: i32) { + if *cr.offset(4) & CR4_OSFXSR == 0 { + dbg_log!("Warning: Unimplemented task switch test with cr4.osfxsr=0"); + } + if 0 != *cr & CR0_EM { + trigger_ud_jit(start_eip); + } + else if 0 != *cr & CR0_TS { + trigger_nm_jit(start_eip); + } + else { + dbg_assert!(false); + } +} + +pub unsafe fn read_moffs() -> OrPageFault { + // read 2 or 4 byte from ip, depending on address size attribute + if is_asize_32() { read_imm32s() } else { read_imm16() } +} + +#[no_mangle] +pub unsafe fn get_real_eip() -> i32 { + // Returns the 'real' instruction pointer, without segment offset + return *instruction_pointer - get_seg_cs(); +} + +pub unsafe fn get_stack_reg() -> i32 { + if *stack_size_32 { + return read_reg32(ESP); + } + else { + return read_reg16(SP); + }; +} + +pub unsafe fn set_stack_reg(value: i32) { + if *stack_size_32 { + write_reg32(ESP, value) + } + else { + write_reg16(SP, value) + }; +} + +pub unsafe fn get_reg_asize(reg: i32) -> i32 { + dbg_assert!(reg == ECX || reg == ESI || reg == EDI); + let r = read_reg32(reg); + if is_asize_32() { + return r; + } + else { + return r & 0xFFFF; + }; +} + +pub unsafe fn set_reg_asize(is_asize_32: bool, reg: i32, value: i32) { + dbg_assert!(reg == ECX || reg == ESI || reg == EDI); + if is_asize_32 { + write_reg32(reg, value) + } + else { + write_reg16(reg, value) + }; +} + +pub unsafe fn decr_ecx_asize(is_asize_32: bool) -> i32 { + return if is_asize_32 { + write_reg32(ECX, read_reg32(ECX) - 1); + read_reg32(ECX) + } + else { + write_reg16(CX, read_reg16(CX) - 1); + read_reg16(CX) + }; +} + +#[no_mangle] +pub unsafe fn set_tsc(low: u32, high: u32) { + let new_value = low as u64 | (high as u64) << 32; + let current_value = read_tsc(); + tsc_offset = current_value.wrapping_sub(new_value); +} + +#[no_mangle] +pub unsafe fn read_tsc() -> u64 { + let n = microtick() * TSC_RATE; + let value = (n as u64).wrapping_sub(tsc_offset); + if true { + return value; + } + else { + if value == rdtsc_last_value { + // don't go past 1ms + if (rdtsc_imprecision_offset as f64) < TSC_RATE { + rdtsc_imprecision_offset = rdtsc_imprecision_offset.wrapping_add(1) + } + } + else { + let previous_value = rdtsc_last_value.wrapping_add(rdtsc_imprecision_offset); + if previous_value <= value { + rdtsc_last_value = value; + rdtsc_imprecision_offset = 0 + } + else { + dbg_log!( + "XXX: Overshot tsc prev={:x}:{:x} offset={:x}:{:x} curr={:x}:{:x}", + (rdtsc_last_value >> 32) as u32 as i32, + rdtsc_last_value as u32 as i32, + (rdtsc_imprecision_offset >> 32) as u32 as i32, + rdtsc_imprecision_offset as u32 as i32, + (value >> 32) as u32 as i32, + value as u32 as i32 + ); + dbg_assert!(false); + // Keep current value until time catches up + } + } + return rdtsc_last_value.wrapping_add(rdtsc_imprecision_offset); + }; +} + +pub unsafe fn vm86_mode() -> bool { return *flags & FLAG_VM == FLAG_VM; } + +#[no_mangle] +pub unsafe fn getiopl() -> i32 { return *flags >> 12 & 3; } + +#[no_mangle] +#[cfg(feature = "profiler")] +pub unsafe fn get_opstats_buffer( + compiled: bool, + jit_exit: bool, + unguarded_register: bool, + wasm_size: bool, + opcode: u8, + is_0f: bool, + is_mem: bool, + fixed_g: u8, +) -> f64 { + { + let index = (is_0f as usize) << 12 + | (opcode as usize) << 4 + | (is_mem as usize) << 3 + | fixed_g as usize; + (if compiled { + ::opstats::opstats_compiled_buffer[index] + } + else if jit_exit { + ::opstats::opstats_jit_exit_buffer[index] + } + else if unguarded_register { + ::opstats::opstats_unguarded_register_buffer[index] + } + else if wasm_size { + ::opstats::opstats_wasm_size[index] + } + else { + ::opstats::opstats_buffer[index] + }) as f64 + } +} + +#[no_mangle] +#[cfg(not(feature = "profiler"))] +pub unsafe fn get_opstats_buffer() -> f64 { 0.0 } + +pub fn clear_tlb_code(page: i32) { + unsafe { + if let Some(c) = tlb_code[page as usize] { + drop(Box::from_raw(c.as_ptr())); + } + tlb_code[page as usize] = None; + } +} + +pub unsafe fn invlpg(addr: i32) { + let page = (addr as u32 >> 12) as i32; + // Note: Doesn't remove this page from valid_tlb_entries: This isn't + // necessary, because when valid_tlb_entries grows too large, it will be + // empties by calling clear_tlb, which removes this entry as it isn't global. + // This however means that valid_tlb_entries can contain some invalid entries + clear_tlb_code(page); + tlb_data[page as usize] = 0; + *last_virt_eip = -1; +} + +#[no_mangle] +pub unsafe fn update_eflags(new_flags: i32) { + let mut dont_update: i32 = FLAG_RF | FLAG_VM | FLAG_VIP | FLAG_VIF; + let mut clear: i32 = !FLAG_VIP & !FLAG_VIF & FLAGS_MASK; + if 0 != *flags & FLAG_VM { + // other case needs to be handled in popf or iret + dbg_assert!(getiopl() == 3); + dont_update |= FLAG_IOPL; + // don't clear vip or vif + clear |= FLAG_VIP | FLAG_VIF + } + else { + if !*protected_mode { + dbg_assert!(*cpl == 0); + } + if 0 != *cpl { + // cpl > 0 + // cannot update iopl + dont_update |= FLAG_IOPL; + if *cpl as i32 > getiopl() { + // cpl > iopl + // cannot update interrupt flag + dont_update |= FLAG_INTERRUPT + } + } + } + *flags = (new_flags ^ (*flags ^ new_flags) & dont_update) & clear | FLAGS_DEFAULT; + *flags_changed = 0; + + if *flags & FLAG_TRAP != 0 { + dbg_log!("Not supported: trap flag"); + } + *flags &= !FLAG_TRAP; +} + +#[no_mangle] +pub unsafe fn get_valid_tlb_entries_count() -> i32 { + if !cfg!(feature = "profiler") { + return 0; + } + let mut result: i32 = 0; + for i in 0..valid_tlb_entries_count { + let page = valid_tlb_entries[i as usize]; + let entry = tlb_data[page as usize]; + if 0 != entry { + result += 1 + } + } + return result; +} + +#[no_mangle] +pub unsafe fn get_valid_global_tlb_entries_count() -> i32 { + if !cfg!(feature = "profiler") { + return 0; + } + let mut result: i32 = 0; + for i in 0..valid_tlb_entries_count { + let page = valid_tlb_entries[i as usize]; + let entry = tlb_data[page as usize]; + if 0 != entry & TLB_GLOBAL { + result += 1 + } + } + return result; +} + +#[inline(never)] +pub unsafe fn trigger_np(code: i32) { + dbg_log!("#np"); + *instruction_pointer = *previous_ip; + if DEBUG { + if cpu_exception_hook(CPU_EXCEPTION_NP) { + return; + } + } + call_interrupt_vector(CPU_EXCEPTION_NP, false, Some(code)); +} + +#[inline(never)] +pub unsafe fn trigger_ss(code: i32) { + dbg_log!("#ss"); + *instruction_pointer = *previous_ip; + if DEBUG { + if cpu_exception_hook(CPU_EXCEPTION_SS) { + return; + } + } + call_interrupt_vector(CPU_EXCEPTION_SS, false, Some(code)); +} + +#[no_mangle] +pub unsafe fn store_current_tsc() { *current_tsc = read_tsc(); } + +#[no_mangle] +pub unsafe fn handle_irqs() { + if *flags & FLAG_INTERRUPT != 0 { + pic_acknowledge() + } +} + +#[no_mangle] +pub unsafe fn pic_call_irq(interrupt_nr: i32) { + *previous_ip = *instruction_pointer; // XXX: What if called after instruction (port IO) + call_interrupt_vector(interrupt_nr, false, None); +} + +#[no_mangle] +#[cfg(debug_assertions)] +pub unsafe fn check_page_switch(block_addr: u32, next_block_addr: u32) { + let x = translate_address_read_jit(*instruction_pointer); + if x != Ok(next_block_addr) { + dbg_log!( + "page switch from={:x} to={:x} prev_eip={:x} eip={:x} phys_eip={:x}", + block_addr, + next_block_addr, + *previous_ip, + *instruction_pointer, + x.unwrap_or(0), + ); + } + dbg_assert!(next_block_addr & 0xFFF == *instruction_pointer as u32 & 0xFFF); + dbg_assert!(x.is_ok()); + dbg_assert!(x == Ok(next_block_addr)); +} + +#[no_mangle] +pub unsafe fn reset_cpu() { + for i in 0..8 { + *segment_is_null.offset(i) = false; + *segment_limits.offset(i) = 0; + *segment_offsets.offset(i) = 0; + + *reg32.offset(i) = 0; + + *sreg.offset(i) = 0; + *dreg.offset(i) = 0; + + write_xmm128_2(i as i32, 0, 0); + + *fpu_st.offset(i) = ::softfloat::F80::ZERO; + } + + for i in 0..4 { + *reg_pdpte.offset(i) = 0 + } + + *fpu_stack_empty = 0xFF; + *fpu_stack_ptr = 0; + *fpu_control_word = 0x37F; + *fpu_status_word = 0; + *fpu_ip = 0; + *fpu_ip_selector = 0; + *fpu_opcode = 0; + *fpu_dp = 0; + *fpu_dp_selector = 0; + + *mxcsr = 0x1F80; + + full_clear_tlb(); + + *protected_mode = false; + + // http://www.sandpile.org/x86/initial.htm + *idtr_size = 0; + *idtr_offset = 0; + + *gdtr_size = 0; + *gdtr_offset = 0; + + *page_fault = false; + *cr = 1 << 30 | 1 << 29 | 1 << 4; + *cr.offset(2) = 0; + *cr.offset(3) = 0; + *cr.offset(4) = 0; + *dreg.offset(6) = 0xFFFF0FF0u32 as i32; + *dreg.offset(7) = 0x400; + *cpl = 0; + + *is_32 = false; + *stack_size_32 = false; + *prefixes = 0; + + *last_virt_eip = -1; + + *instruction_counter = 0; + *previous_ip = 0; + *in_hlt = false; + + *sysenter_cs = 0; + *sysenter_esp = 0; + *sysenter_eip = 0; + + *flags = FLAGS_DEFAULT; + *flags_changed = 0; + *last_result = 0; + *last_op1 = 0; + *last_op_size = 0; + + set_tsc(0, 0); + + *instruction_pointer = 0xFFFF0; + switch_cs_real_mode(0xF000); + + switch_seg(SS, 0x30); + write_reg32(ESP, 0x100); + + update_state_flags(); + + jit::jit_clear_cache(jit::get_jit_state()); +} + +#[no_mangle] +pub unsafe fn set_cpuid_level(level: u32) { cpuid_level = level } diff --git a/src/rust/cpu/fpu.rs b/src/rust/cpu/fpu.rs new file mode 100644 index 0000000..23e673f --- /dev/null +++ b/src/rust/cpu/fpu.rs @@ -0,0 +1,909 @@ +use cpu::cpu::*; +use cpu::global_pointers::*; +use paging::OrPageFault; +use softfloat::{Precision, RoundingMode, F80}; +use std::f64; + +const FPU_C0: u16 = 0x100; +const FPU_C1: u16 = 0x200; +const FPU_C2: u16 = 0x400; +const FPU_C3: u16 = 0x4000; +const FPU_RESULT_FLAGS: u16 = FPU_C0 | FPU_C1 | FPU_C2 | FPU_C3; + +const FPU_EX_I: u16 = 1 << 0; // invalid operation +#[allow(dead_code)] +const FPU_EX_D: u16 = 1 << 1; // denormal operand +const FPU_EX_Z: u16 = 1 << 2; // zero divide +#[allow(dead_code)] +const FPU_EX_O: u16 = 1 << 3; // overflow +const FPU_EX_U: u16 = 1 << 4; // underflow +#[allow(dead_code)] +const FPU_EX_P: u16 = 1 << 5; // precision +const FPU_EX_SF: u16 = 1 << 6; + +pub fn fpu_write_st(index: i32, value: F80) { + dbg_assert!(index >= 0 && index < 8); + unsafe { + *fpu_st.offset(index as isize) = value; + } +} + +#[no_mangle] +pub unsafe fn fpu_get_st0() -> F80 { + dbg_assert!(*fpu_stack_ptr < 8); + if 0 != *fpu_stack_empty >> *fpu_stack_ptr & 1 { + *fpu_status_word &= !FPU_C1; + fpu_stack_fault(); + return F80::INDEFINITE_NAN; + } + else { + return *fpu_st.offset(*fpu_stack_ptr as isize); + }; +} +#[no_mangle] +pub unsafe fn fpu_stack_fault() { + // TODO: Interrupt + *fpu_status_word |= FPU_EX_SF | FPU_EX_I; +} + +#[no_mangle] +pub unsafe fn fpu_zero_fault() { + // TODO: Interrupt + *fpu_status_word |= FPU_EX_Z; +} + +#[no_mangle] +pub unsafe fn fpu_underflow_fault() { + // TODO: Interrupt + *fpu_status_word |= FPU_EX_U; +} + +#[no_mangle] +pub unsafe fn fpu_sti_empty(mut i: i32) -> bool { + dbg_assert!(i >= 0 && i < 8); + i = i + *fpu_stack_ptr as i32 & 7; + return 0 != *fpu_stack_empty >> i & 1; +} + +#[no_mangle] +pub unsafe fn fpu_get_sti(mut i: i32) -> F80 { + dbg_assert!(i >= 0 && i < 8); + i = i + *fpu_stack_ptr as i32 & 7; + if 0 != *fpu_stack_empty >> i & 1 { + *fpu_status_word &= !FPU_C1; + fpu_stack_fault(); + return F80::INDEFINITE_NAN; + } + else { + return *fpu_st.offset(i as isize); + }; +} + +#[no_mangle] +pub unsafe fn fpu_get_sti_f64(mut i: i32) -> f64 { + i = i + *fpu_stack_ptr as i32 & 7; + std::mem::transmute((*fpu_st.offset(i as isize)).to_f64()) +} + +#[no_mangle] +pub unsafe fn f32_to_f80(v: i32) -> F80 { F80::of_f32(v) } +#[no_mangle] +pub unsafe fn f64_to_f80(v: u64) -> F80 { F80::of_f64(v) } +#[no_mangle] +pub unsafe fn f80_to_f32(v: F80) -> i32 { + F80::clear_exception_flags(); + let x = v.to_f32(); + *fpu_status_word |= F80::get_exception_flags() as u16; + x +} +#[no_mangle] +pub unsafe fn f80_to_f64(v: F80) -> u64 { + F80::clear_exception_flags(); + let x = v.to_f64(); + *fpu_status_word |= F80::get_exception_flags() as u16; + x +} + +#[no_mangle] +pub unsafe fn i32_to_f80(v: i32) -> F80 { F80::of_i32(v) } +#[no_mangle] +pub unsafe fn i64_to_f80(v: i64) -> F80 { F80::of_i64(v) } + +#[no_mangle] +pub unsafe fn fpu_load_i16(addr: i32) -> OrPageFault { + let v = safe_read16(addr)? as i16 as i32; + Ok(F80::of_i32(v)) +} +#[no_mangle] +pub unsafe fn fpu_load_i32(addr: i32) -> OrPageFault { + let v = safe_read32s(addr)?; + Ok(F80::of_i32(v)) +} +#[no_mangle] +pub unsafe fn fpu_load_i64(addr: i32) -> OrPageFault { + let v = safe_read64s(addr)? as i64; + Ok(F80::of_i64(v)) +} + +#[no_mangle] +pub unsafe fn fpu_load_m32(addr: i32) -> OrPageFault { + let v = safe_read32s(addr)?; + Ok(F80::of_f32(v)) +} +#[no_mangle] +pub unsafe fn fpu_load_m64(addr: i32) -> OrPageFault { + F80::clear_exception_flags(); + let v = F80::of_f64(safe_read64s(addr)?); + *fpu_status_word |= F80::get_exception_flags() as u16; + Ok(v) +} +#[no_mangle] +pub unsafe fn fpu_load_m80(addr: i32) -> OrPageFault { + let mantissa = safe_read64s(addr)?; + let sign_exponent = safe_read16(addr + 8)? as u16; + // TODO: Canonical form + Ok(F80 { + mantissa, + sign_exponent, + }) +} + +#[no_mangle] +pub unsafe fn fpu_load_status_word() -> u16 { + dbg_assert!(*fpu_stack_ptr < 8); + return *fpu_status_word & !(7 << 11) | (*fpu_stack_ptr as u16) << 11; +} +#[no_mangle] +pub unsafe fn fpu_fadd(target_index: i32, val: F80) { + F80::clear_exception_flags(); + let st0 = fpu_get_st0(); + fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, st0 + val); + *fpu_status_word |= F80::get_exception_flags() as u16; +} +#[no_mangle] +pub unsafe fn fpu_fclex() { *fpu_status_word = 0; } +#[no_mangle] +pub unsafe fn fpu_fcmovcc(condition: bool, r: i32) { + // outside of the condition is correct: A stack fault happens even if the condition is not + // fulfilled + let x = fpu_get_sti(r); + if fpu_sti_empty(r) { + fpu_write_st(*fpu_stack_ptr as i32, F80::INDEFINITE_NAN) + } + else { + if condition { + fpu_write_st(*fpu_stack_ptr as i32, x); + *fpu_stack_empty &= !(1 << *fpu_stack_ptr) + }; + } +} + +#[no_mangle] +pub unsafe fn fpu_fcom(y: F80) { + F80::clear_exception_flags(); + let x = fpu_get_st0(); + *fpu_status_word &= !FPU_RESULT_FLAGS; + match x.partial_cmp(&y) { + Some(std::cmp::Ordering::Greater) => {}, + Some(std::cmp::Ordering::Less) => *fpu_status_word |= FPU_C0, + Some(std::cmp::Ordering::Equal) => *fpu_status_word |= FPU_C3, + None => *fpu_status_word |= FPU_C0 | FPU_C2 | FPU_C3, + } + *fpu_status_word |= F80::get_exception_flags() as u16; +} + +#[no_mangle] +pub unsafe fn fpu_fcomi(r: i32) { + F80::clear_exception_flags(); + let x = fpu_get_st0(); + let y = fpu_get_sti(r); + *flags_changed = 0; + *flags &= !FLAGS_ALL; + match x.partial_cmp(&y) { + Some(std::cmp::Ordering::Greater) => {}, + Some(std::cmp::Ordering::Less) => *flags |= 1, + Some(std::cmp::Ordering::Equal) => *flags |= FLAG_ZERO, + None => *flags |= 1 | FLAG_PARITY | FLAG_ZERO, + } + *fpu_status_word |= F80::get_exception_flags() as u16; +} + +#[no_mangle] +pub unsafe fn fpu_fcomip(r: i32) { + fpu_fcomi(r); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_pop() { + dbg_assert!(*fpu_stack_ptr < 8); + *fpu_stack_empty |= 1 << *fpu_stack_ptr; + *fpu_stack_ptr = *fpu_stack_ptr + 1 & 7; +} + +#[no_mangle] +pub unsafe fn fpu_fcomp(val: F80) { + fpu_fcom(val); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_fdiv(target_index: i32, val: F80) { + F80::clear_exception_flags(); + let st0 = fpu_get_st0(); + fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, st0 / val); + *fpu_status_word |= F80::get_exception_flags() as u16; +} +#[no_mangle] +pub unsafe fn fpu_fdivr(target_index: i32, val: F80) { + F80::clear_exception_flags(); + let st0 = fpu_get_st0(); + fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, val / st0); + *fpu_status_word |= F80::get_exception_flags() as u16; +} +#[no_mangle] +pub unsafe fn fpu_ffree(r: i32) { *fpu_stack_empty |= 1 << (*fpu_stack_ptr as i32 + r & 7); } + +#[no_mangle] +pub unsafe fn fpu_fildm16(addr: i32) { fpu_push(return_on_pagefault!(fpu_load_i16(addr))); } +#[no_mangle] +pub unsafe fn fpu_fildm32(addr: i32) { fpu_push(return_on_pagefault!(fpu_load_i32(addr))); } +#[no_mangle] +pub unsafe fn fpu_fildm64(addr: i32) { fpu_push(return_on_pagefault!(fpu_load_i64(addr))); } + +#[no_mangle] +pub unsafe fn fpu_push(x: F80) { + *fpu_stack_ptr = *fpu_stack_ptr - 1 & 7; + if 0 != *fpu_stack_empty >> *fpu_stack_ptr & 1 { + *fpu_status_word &= !FPU_C1; + *fpu_stack_empty &= !(1 << *fpu_stack_ptr); + fpu_write_st(*fpu_stack_ptr as i32, x); + } + else { + *fpu_status_word |= FPU_C1; + fpu_stack_fault(); + fpu_write_st(*fpu_stack_ptr as i32, F80::INDEFINITE_NAN); + }; +} +#[no_mangle] +pub unsafe fn fpu_finit() { + set_control_word(0x37F); + *fpu_status_word = 0; + *fpu_ip = 0; + *fpu_dp = 0; + *fpu_opcode = 0; + *fpu_stack_empty = 0xFF; + *fpu_stack_ptr = 0; +} + +#[no_mangle] +pub unsafe fn set_control_word(cw: u16) { + *fpu_control_word = cw; + + let rc = cw >> 10 & 3; + F80::set_rounding_mode(match rc { + 0 => RoundingMode::NearEven, + 1 => RoundingMode::Floor, + 2 => RoundingMode::Ceil, + 3 => RoundingMode::Trunc, + _ => { + dbg_assert!(false); + RoundingMode::NearEven + }, + }); + + let precision_control = cw >> 8 & 3; + F80::set_precision(match precision_control { + 0 => Precision::P32, + 1 => Precision::P80, // undefined + 2 => Precision::P64, + 3 => Precision::P80, + _ => { + dbg_assert!(false); + Precision::P80 + }, + }); +} + +#[no_mangle] +pub unsafe fn fpu_invalid_arithmetic() { *fpu_status_word |= FPU_EX_I; } + +#[no_mangle] +pub unsafe fn fpu_convert_to_i16(f: F80) -> i16 { + let st0 = fpu_convert_to_i32(f); + if st0 < -0x8000 || st0 > 0x7FFF { + fpu_invalid_arithmetic(); + -0x8000 + } + else { + st0 as i16 + } +} +#[no_mangle] +pub unsafe fn fpu_fistm16(addr: i32) { + return_on_pagefault!(writable_or_pagefault(addr, 2)); + let v = fpu_convert_to_i16(fpu_get_st0()); + safe_write16(addr, v as i32).unwrap(); +} +#[no_mangle] +pub unsafe fn fpu_fistm16p(addr: i32) { + return_on_pagefault!(writable_or_pagefault(addr, 2)); + let v = fpu_convert_to_i16(fpu_get_st0()); + safe_write16(addr, v as i32).unwrap(); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_convert_to_i32(f: F80) -> i32 { + F80::clear_exception_flags(); + let x = f.to_i32(); + *fpu_status_word |= F80::get_exception_flags() as u16; + x +} +#[no_mangle] +pub unsafe fn fpu_fistm32(addr: i32) { + return_on_pagefault!(writable_or_pagefault(addr, 4)); + let v = fpu_convert_to_i32(fpu_get_st0()); + safe_write32(addr, v).unwrap(); +} +#[no_mangle] +pub unsafe fn fpu_fistm32p(addr: i32) { + return_on_pagefault!(writable_or_pagefault(addr, 4)); + let v = fpu_convert_to_i32(fpu_get_st0()); + safe_write32(addr, v).unwrap(); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_convert_to_i64(f: F80) -> i64 { + F80::clear_exception_flags(); + let x = f.to_i64(); + *fpu_status_word |= F80::get_exception_flags() as u16; + x +} +#[no_mangle] +pub unsafe fn fpu_fistm64p(addr: i32) { + return_on_pagefault!(writable_or_pagefault(addr, 8)); + let v = fpu_convert_to_i64(fpu_get_st0()); + safe_write64(addr, v as u64).unwrap(); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_fldcw(addr: i32) { + let word = return_on_pagefault!(safe_read16(addr)) as u16; + set_control_word(word); +} + +#[no_mangle] +pub unsafe fn fpu_fldenv16(_addr: i32) { + dbg_log!("fldenv16"); + fpu_unimpl(); +} +#[no_mangle] +pub unsafe fn fpu_fldenv32(addr: i32) { + if let Err(()) = readable_or_pagefault(addr, 28) { + *page_fault = true; + return; + } + *page_fault = false; + set_control_word(safe_read16(addr).unwrap() as u16); + fpu_set_status_word(safe_read16(addr + 4).unwrap() as u16); + fpu_set_tag_word(safe_read16(addr + 8).unwrap()); + *fpu_ip = safe_read32s(addr + 12).unwrap(); + *fpu_ip_selector = safe_read16(addr + 16).unwrap(); + *fpu_opcode = safe_read16(addr + 18).unwrap(); + *fpu_dp = safe_read32s(addr + 20).unwrap(); + *fpu_dp_selector = safe_read16(addr + 24).unwrap() +} +#[no_mangle] +pub unsafe fn fpu_unimpl() { + dbg_assert!(false); + trigger_ud(); +} +#[no_mangle] +pub unsafe fn fpu_set_tag_word(tag_word: i32) { + *fpu_stack_empty = 0; + for i in 0..8 { + let empty = tag_word >> (2 * i) & 3 == 3; + *fpu_stack_empty |= (empty as u8) << i; + } +} +#[no_mangle] +pub unsafe fn fpu_set_status_word(sw: u16) { + *fpu_status_word = sw & !(7 << 11); + *fpu_stack_ptr = (sw >> 11 & 7) as u8; +} + +#[no_mangle] +pub unsafe fn fpu_fldm32(addr: i32) { fpu_push(return_on_pagefault!(fpu_load_m32(addr))); } +#[no_mangle] +pub unsafe fn fpu_fldm64(addr: i32) { fpu_push(return_on_pagefault!(fpu_load_m64(addr))); } +#[no_mangle] +pub unsafe fn fpu_fldm80(addr: i32) { + match fpu_load_m80(addr) { + Ok(x) => { + *page_fault = false; + fpu_push(x) + }, + Err(()) => { + *page_fault = true; + }, + } +} + +#[no_mangle] +pub unsafe fn fpu_fmul(target_index: i32, val: F80) { + let st0 = fpu_get_st0(); + fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, st0 * val); +} +#[no_mangle] +pub unsafe fn fpu_fnstsw_mem(addr: i32) { + return_on_pagefault!(safe_write16(addr, fpu_load_status_word().into())); +} +#[no_mangle] +pub unsafe fn fpu_fnstsw_reg() { write_reg16(AX, fpu_load_status_word().into()); } +#[no_mangle] +pub unsafe fn fpu_fprem(ieee: bool) { + // false: Faster, fails nasmtests + // true: Slower, fails qemutests + let intel_compatibility = false; + + let st0 = fpu_get_st0(); + let st1 = fpu_get_sti(1); + + if st1 == F80::ZERO { + if st0 == F80::ZERO { + fpu_invalid_arithmetic(); + } + else { + fpu_zero_fault(); + } + fpu_write_st(*fpu_stack_ptr as i32, F80::INDEFINITE_NAN); + return; + } + + let exp0 = st0.log2(); + let exp1 = st1.log2(); + let d = (exp0 - exp1).abs(); + if !intel_compatibility || d < F80::of_f64(std::mem::transmute(64.0)) { + let fprem_quotient = + (if ieee { (st0 / st1).round() } else { (st0 / st1).trunc() }).to_i32(); + fpu_write_st(*fpu_stack_ptr as i32, st0 % st1); + *fpu_status_word &= !(FPU_C0 | FPU_C1 | FPU_C3); + if 0 != fprem_quotient & 1 { + *fpu_status_word |= FPU_C1 + } + if 0 != fprem_quotient & 1 << 1 { + *fpu_status_word |= FPU_C3 + } + if 0 != fprem_quotient & 1 << 2 { + *fpu_status_word |= FPU_C0 + } + *fpu_status_word &= !FPU_C2; + } + else { + let n = F80::of_f64(std::mem::transmute(32.0)); + let fprem_quotient = + (if ieee { (st0 / st1).round() } else { (st0 / st1).trunc() } / (d - n).two_pow()); + fpu_write_st( + *fpu_stack_ptr as i32, + st0 - st1 * fprem_quotient * (d - n).two_pow(), + ); + *fpu_status_word |= FPU_C2; + } +} + +#[no_mangle] +pub unsafe fn fpu_frstor16(_addr: i32) { + dbg_log!("frstor16"); + fpu_unimpl(); +} +#[no_mangle] +pub unsafe fn fpu_frstor32(mut addr: i32) { + return_on_pagefault!(readable_or_pagefault(addr, 28 + 8 * 10)); + fpu_fldenv32(addr); + addr += 28; + for i in 0..8 { + let reg_index = *fpu_stack_ptr as i32 + i & 7; + *fpu_st.offset(reg_index as isize) = fpu_load_m80(addr).unwrap(); + addr += 10; + } +} + +#[no_mangle] +pub unsafe fn fpu_fsave16(_addr: i32) { + dbg_log!("fsave16"); + fpu_unimpl(); +} +#[no_mangle] +pub unsafe fn fpu_fsave32(mut addr: i32) { + return_on_pagefault!(writable_or_pagefault(addr, 108)); + fpu_fstenv32(addr); + addr += 28; + for i in 0..8 { + let reg_index = i + *fpu_stack_ptr as i32 & 7; + fpu_store_m80(addr, *fpu_st.offset(reg_index as isize)); + addr += 10; + } + fpu_finit(); +} + +#[no_mangle] +pub unsafe fn fpu_store_m80(addr: i32, f: F80) { + // writable_or_pagefault must have checked called by the caller! + safe_write64(addr, f.mantissa).unwrap(); + safe_write16(addr + 8, f.sign_exponent as i32).unwrap(); +} + +#[no_mangle] +pub unsafe fn fpu_fstenv16(_addr: i32) { + dbg_log!("fstenv16"); + fpu_unimpl(); +} + +#[no_mangle] +pub unsafe fn fpu_fstenv32(addr: i32) { + match writable_or_pagefault(addr, 26) { + Ok(()) => *page_fault = false, + Err(()) => { + *page_fault = true; + return; + }, + } + let high_bits = 0xFFFF0000u32 as i32; + safe_write32(addr + 0, high_bits + *fpu_control_word as i32).unwrap(); + safe_write32(addr + 4, high_bits + fpu_load_status_word() as i32).unwrap(); + safe_write32(addr + 8, high_bits + fpu_load_tag_word()).unwrap(); + safe_write32(addr + 12, *fpu_ip).unwrap(); + safe_write16(addr + 16, *fpu_ip_selector).unwrap(); + safe_write16(addr + 18, *fpu_opcode).unwrap(); + safe_write32(addr + 20, *fpu_dp).unwrap(); + safe_write32(addr + 24, high_bits | *fpu_dp_selector).unwrap(); +} +#[no_mangle] +pub unsafe fn fpu_load_tag_word() -> i32 { + let mut tag_word: i32 = 0; + for i in 0..8 { + let value = *fpu_st.offset(i as isize); + if 0 != *fpu_stack_empty >> i & 1 { + tag_word |= 3 << (i << 1) + } + else if value == F80::ZERO { + tag_word |= 1 << (i << 1) + } + else if !value.is_finite() { + tag_word |= 2 << (i << 1) + } + } + return tag_word; +} +#[no_mangle] +pub unsafe fn fpu_fst(r: i32) { fpu_write_st(*fpu_stack_ptr as i32 + r & 7, fpu_get_st0()); } +#[no_mangle] +pub unsafe fn fpu_fst80p(addr: i32) { + return_on_pagefault!(writable_or_pagefault(addr, 10)); + fpu_store_m80(addr, fpu_get_st0()); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_fstcw(addr: i32) { + return_on_pagefault!(safe_write16(addr, (*fpu_control_word).into())); +} + +#[no_mangle] +pub unsafe fn fpu_fstm32(addr: i32) { + return_on_pagefault!(fpu_store_m32(addr, fpu_get_st0())); +} +#[no_mangle] +pub unsafe fn fpu_store_m32(addr: i32, x: F80) -> OrPageFault<()> { + F80::clear_exception_flags(); + safe_write32(addr, x.to_f32())?; + *fpu_status_word |= F80::get_exception_flags() as u16; + Ok(()) +} +#[no_mangle] +pub unsafe fn fpu_fstm32p(addr: i32) { + return_on_pagefault!(fpu_store_m32(addr, fpu_get_st0())); + fpu_pop(); +} +#[no_mangle] +pub unsafe fn fpu_fstm64(addr: i32) { + return_on_pagefault!(fpu_store_m64(addr, fpu_get_st0())); +} +#[no_mangle] +pub unsafe fn fpu_store_m64(addr: i32, x: F80) -> OrPageFault<()> { safe_write64(addr, x.to_f64()) } +#[no_mangle] +pub unsafe fn fpu_fstm64p(addr: i32) { + // XXX: writable_or_pagefault before get_st0 + return_on_pagefault!(fpu_store_m64(addr, fpu_get_st0())); + fpu_pop(); +} +#[no_mangle] +pub unsafe fn fpu_fstp(r: i32) { + fpu_fst(r); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_fbstp(addr: i32) { + match writable_or_pagefault(addr, 26) { + Ok(()) => *page_fault = false, + Err(()) => { + *page_fault = true; + return; + }, + } + let st0 = fpu_get_st0(); + let mut x = st0.to_i64().unsigned_abs(); + if x <= 99_9999_9999_9999_9999 { + for i in 0..=8 { + let low = x % 10; + x /= 10; + let high = x % 10; + x /= 10; + safe_write8(addr + i, (high as i32) << 4 | low as i32).unwrap(); + } + safe_write8(addr + 9, if st0.sign() { 0x80 } else { 0 }).unwrap(); + } + else { + fpu_invalid_arithmetic(); + safe_write64(addr + 0, 0xC000_0000_0000_0000).unwrap(); + safe_write16(addr + 8, 0xFFFF).unwrap(); + } + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_fsub(target_index: i32, val: F80) { + let st0 = fpu_get_st0(); + fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, st0 - val) +} +#[no_mangle] +pub unsafe fn fpu_fsubr(target_index: i32, val: F80) { + let st0 = fpu_get_st0(); + fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, val - st0) +} + +#[no_mangle] +pub unsafe fn fpu_ftst() { + let x = fpu_get_st0(); + *fpu_status_word &= !FPU_RESULT_FLAGS; + if x.is_nan() { + *fpu_status_word |= FPU_C3 | FPU_C2 | FPU_C0 + } + else if x == F80::ZERO { + *fpu_status_word |= FPU_C3 + } + else if x < F80::ZERO { + *fpu_status_word |= FPU_C0 + } + // TODO: unordered (x is nan, etc) +} + +#[no_mangle] +pub unsafe fn fpu_fucom(r: i32) { + F80::clear_exception_flags(); + let x = fpu_get_st0(); + let y = fpu_get_sti(r); + *fpu_status_word &= !FPU_RESULT_FLAGS; + match x.partial_cmp_quiet(&y) { + Some(std::cmp::Ordering::Greater) => {}, + Some(std::cmp::Ordering::Less) => *fpu_status_word |= FPU_C0, + Some(std::cmp::Ordering::Equal) => *fpu_status_word |= FPU_C3, + None => *fpu_status_word |= FPU_C0 | FPU_C2 | FPU_C3, + } + *fpu_status_word |= F80::get_exception_flags() as u16; +} + +#[no_mangle] +pub unsafe fn fpu_fucomi(r: i32) { + F80::clear_exception_flags(); + let x = fpu_get_st0(); + let y = fpu_get_sti(r); + *flags_changed = 0; + *flags &= !FLAGS_ALL; + match x.partial_cmp_quiet(&y) { + Some(std::cmp::Ordering::Greater) => {}, + Some(std::cmp::Ordering::Less) => *flags |= 1, + Some(std::cmp::Ordering::Equal) => *flags |= FLAG_ZERO, + None => *flags |= 1 | FLAG_PARITY | FLAG_ZERO, + } + *fpu_status_word |= F80::get_exception_flags() as u16; +} + +#[no_mangle] +pub unsafe fn fpu_fucomip(r: i32) { + fpu_fucomi(r); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_fucomp(r: i32) { + fpu_fucom(r); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_fucompp() { + fpu_fucom(1); + fpu_pop(); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_fxam() { + let x = fpu_get_st0(); + *fpu_status_word &= !FPU_RESULT_FLAGS; + *fpu_status_word |= (x.sign() as u16) << 9; + if 0 != *fpu_stack_empty >> *fpu_stack_ptr & 1 { + *fpu_status_word |= FPU_C3 | FPU_C0 + } + else if x.is_nan() { + *fpu_status_word |= FPU_C0 + } + else if x == F80::ZERO { + *fpu_status_word |= FPU_C3 + } + else if !x.is_finite() { + *fpu_status_word |= FPU_C2 | FPU_C0 + } + else { + *fpu_status_word |= FPU_C2 + } + // TODO: + // Unsupported, Denormal +} + +#[no_mangle] +pub unsafe fn fpu_fxch(i: i32) { + let sti = fpu_get_sti(i); + fpu_write_st(*fpu_stack_ptr as i32 + i & 7, fpu_get_st0()); + fpu_write_st(*fpu_stack_ptr as i32, sti); +} +pub unsafe fn fpu_fyl2x() { + let st0 = fpu_get_st0(); + if st0 < F80::ZERO { + fpu_invalid_arithmetic(); + } + else if st0 == F80::ZERO { + fpu_zero_fault(); + } + fpu_write_st( + *fpu_stack_ptr as i32 + 1 & 7, + fpu_get_sti(1) * st0.ln() / F80::LN_2, + ); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn fpu_fxtract() { + let st0 = fpu_get_st0(); + if st0 == F80::ZERO { + fpu_zero_fault(); + fpu_write_st(*fpu_stack_ptr as i32, F80::NEG_INFINITY); + fpu_push(st0); + } + else { + let exp = st0.exponent(); + fpu_write_st(*fpu_stack_ptr as i32, F80::of_i32(exp.into())); + fpu_push(F80 { + sign_exponent: 0x3FFF, + mantissa: st0.mantissa, + }); + } +} + +#[no_mangle] +pub unsafe fn fwait() { + // NOP unless FPU instructions run in parallel with CPU instructions +} + +pub unsafe fn fpu_fchs() { + let st0 = fpu_get_st0(); + fpu_write_st(*fpu_stack_ptr as i32, -st0); +} + +pub unsafe fn fpu_fabs() { + let st0 = fpu_get_st0(); + fpu_write_st(*fpu_stack_ptr as i32, st0.abs()); +} + +pub unsafe fn fpu_f2xm1() { + let st0 = fpu_get_st0(); + let r = st0.two_pow() - F80::ONE; + fpu_write_st(*fpu_stack_ptr as i32, r) +} + +pub unsafe fn fpu_fptan() { + let st0 = fpu_get_st0(); + //if -pow(2.0, 63.0) < st0 && st0 < pow(2.0, 63.0) { + fpu_write_st(*fpu_stack_ptr as i32, st0.tan()); + // no bug: push constant 1 + fpu_push(F80::ONE); + *fpu_status_word &= !FPU_C2; + //} + //else { + // *fpu_status_word |= FPU_C2; + //} +} + +pub unsafe fn fpu_fpatan() { + let st0 = fpu_get_st0(); + let st1 = fpu_get_sti(1); + fpu_write_st(*fpu_stack_ptr as i32 + 1 & 7, st1.atan2(st0)); + fpu_pop(); +} + +pub unsafe fn fpu_fyl2xp1() { + // fyl2xp1: y * log2(x+1) and pop + let st0 = fpu_get_st0(); + let st1 = fpu_get_sti(1); + let y = st1 * (st0 + F80::ONE).ln() / F80::LN_2; + fpu_write_st(*fpu_stack_ptr as i32 + 1 & 7, y); + fpu_pop(); +} + +pub unsafe fn fpu_fsqrt() { + let st0 = fpu_get_st0(); + //if st0 < 0.0 { + // fpu_invalid_arithmetic(); + //} + fpu_write_st(*fpu_stack_ptr as i32, st0.sqrt()) +} + +pub unsafe fn fpu_fsincos() { + let st0 = fpu_get_st0(); + //if pow(-2.0, 63.0) < st0 && st0 < pow(2.0, 63.0) { + fpu_write_st(*fpu_stack_ptr as i32, st0.sin()); + fpu_push(st0.cos()); + *fpu_status_word &= !FPU_C2; + //} + //else { + // *fpu_status_word |= FPU_C2; + //} +} + +pub unsafe fn fpu_frndint() { + let st0 = fpu_get_st0(); + fpu_write_st(*fpu_stack_ptr as i32, st0.round()); +} + +pub unsafe fn fpu_fscale() { + let st0 = fpu_get_st0(); + let y = st0 * fpu_get_sti(1).trunc().two_pow(); + fpu_write_st(*fpu_stack_ptr as i32, y); +} + +pub unsafe fn fpu_fsin() { + let st0 = fpu_get_st0(); + //if pow(-2.0, 63.0) < st0 && st0 < pow(2.0, 63.0) { + fpu_write_st(*fpu_stack_ptr as i32, st0.sin()); + *fpu_status_word &= !FPU_C2; + //} + //else { + // *fpu_status_word |= FPU_C2; + //} +} + +pub unsafe fn fpu_fcos() { + let st0 = fpu_get_st0(); + //if pow(-2.0, 63.0) < st0 && st0 < pow(2.0, 63.0) { + fpu_write_st(*fpu_stack_ptr as i32, st0.cos()); + *fpu_status_word &= !FPU_C2; + //} + //else { + // *fpu_status_word |= FPU_C2; + //} +} + +pub unsafe fn fpu_fdecstp() { + *fpu_stack_ptr = *fpu_stack_ptr - 1 & 7; + *fpu_status_word &= !FPU_C1 +} + +pub unsafe fn fpu_fincstp() { + *fpu_stack_ptr = *fpu_stack_ptr + 1 & 7; + *fpu_status_word &= !FPU_C1 +} diff --git a/src/rust/cpu/global_pointers.rs b/src/rust/cpu/global_pointers.rs new file mode 100644 index 0000000..9d368cf --- /dev/null +++ b/src/rust/cpu/global_pointers.rs @@ -0,0 +1,109 @@ +#![allow(non_upper_case_globals)] + +use cpu::cpu::reg128; +use softfloat::F80; +use state_flags::CachedStateFlags; + +pub const reg8: *mut u8 = 64 as *mut u8; +pub const reg16: *mut u16 = 64 as *mut u16; +pub const reg32: *mut i32 = 64 as *mut i32; + +pub const last_op_size: *mut i32 = 96 as *mut i32; +pub const flags_changed: *mut i32 = 100 as *mut i32; +pub const last_op1: *mut i32 = 104 as *mut i32; +pub const state_flags: *mut CachedStateFlags = 108 as *mut CachedStateFlags; +pub const last_result: *mut i32 = 112 as *mut i32; +pub const flags: *mut i32 = 120 as *mut i32; + +pub const page_fault: *mut bool = 540 as *mut bool; + +pub const apic_enabled: *mut bool = 548 as *mut bool; +pub const acpi_enabled: *mut bool = 552 as *mut bool; + +pub const instruction_pointer: *mut i32 = 556 as *mut i32; +pub const previous_ip: *mut i32 = 560 as *mut i32; +pub const idtr_size: *mut i32 = 564 as *mut i32; +pub const idtr_offset: *mut i32 = 568 as *mut i32; +pub const gdtr_size: *mut i32 = 572 as *mut i32; +pub const gdtr_offset: *mut i32 = 576 as *mut i32; +pub const cr: *mut i32 = 580 as *mut i32; +pub const cpl: *mut u8 = 612 as *mut u8; +pub const in_hlt: *mut bool = 616 as *mut bool; +pub const last_virt_eip: *mut i32 = 620 as *mut i32; +pub const eip_phys: *mut i32 = 624 as *mut i32; + +pub const sysenter_cs: *mut i32 = 636 as *mut i32; +pub const sysenter_esp: *mut i32 = 640 as *mut i32; +pub const sysenter_eip: *mut i32 = 644 as *mut i32; +pub const prefixes: *mut u8 = 648 as *mut u8; +pub const instruction_counter: *mut u32 = 664 as *mut u32; +pub const sreg: *mut u16 = 668 as *mut u16; +pub const dreg: *mut i32 = 684 as *mut i32; + +// filled in by svga_fill_pixel_buffer, read by javacsript for optimised putImageData calls +pub const svga_dirty_bitmap_min_offset: *mut u32 = 716 as *mut u32; +pub const svga_dirty_bitmap_max_offset: *mut u32 = 720 as *mut u32; + +pub const segment_is_null: *mut bool = 724 as *mut bool; +pub const segment_offsets: *mut i32 = 736 as *mut i32; +pub const segment_limits: *mut u32 = 768 as *mut u32; +pub const protected_mode: *mut bool = 800 as *mut bool; +pub const is_32: *mut bool = 804 as *mut bool; +pub const stack_size_32: *mut bool = 808 as *mut bool; +pub const memory_size: *mut u32 = 812 as *mut u32; +pub const fpu_stack_empty: *mut u8 = 816 as *mut u8; +pub const mxcsr: *mut i32 = 824 as *mut i32; + +pub const reg_xmm: *mut reg128 = 832 as *mut reg128; +pub const current_tsc: *mut u64 = 960 as *mut u64; + +pub const reg_pdpte: *mut u64 = 968 as *mut u64; // 4 64-bit entries + +pub const fpu_stack_ptr: *mut u8 = 1032 as *mut u8; +pub const fpu_control_word: *mut u16 = 1036 as *mut u16; +pub const fpu_status_word: *mut u16 = 1040 as *mut u16; +pub const fpu_opcode: *mut i32 = 1044 as *mut i32; +pub const fpu_ip: *mut i32 = 1048 as *mut i32; +pub const fpu_ip_selector: *mut i32 = 1052 as *mut i32; +pub const fpu_dp: *mut i32 = 1056 as *mut i32; +pub const fpu_dp_selector: *mut i32 = 1060 as *mut i32; +pub const tss_size_32: *mut bool = 1128 as *mut bool; + +pub const sse_scratch_register: *mut reg128 = 1136 as *mut reg128; + +pub const fpu_st: *mut F80 = 1152 as *mut F80; + +pub fn get_reg32_offset(r: u32) -> u32 { + dbg_assert!(r < 8); + (unsafe { reg32.offset(r as isize) }) as u32 +} + +pub fn get_reg_mmx_offset(r: u32) -> u32 { + dbg_assert!(r < 8); + (unsafe { fpu_st.offset(r as isize) }) as u32 +} + +pub fn get_reg_xmm_offset(r: u32) -> u32 { + dbg_assert!(r < 8); + (unsafe { reg_xmm.offset(r as isize) }) as u32 +} + +pub fn get_sreg_offset(s: u32) -> u32 { + dbg_assert!(s < 6); + (unsafe { sreg.offset(s as isize) }) as u32 +} + +pub fn get_seg_offset(s: u32) -> u32 { + dbg_assert!(s < 8); + (unsafe { segment_offsets.offset(s as isize) }) as u32 +} + +pub fn get_segment_is_null_offset(s: u32) -> u32 { + dbg_assert!(s < 8); + (unsafe { segment_is_null.offset(s as isize) }) as u32 +} + +pub fn get_creg_offset(i: u32) -> u32 { + dbg_assert!(i < 8); + (unsafe { cr.offset(i as isize) }) as u32 +} diff --git a/src/rust/cpu/instructions.rs b/src/rust/cpu/instructions.rs new file mode 100644 index 0000000..24b6667 --- /dev/null +++ b/src/rust/cpu/instructions.rs @@ -0,0 +1,2524 @@ +#![allow(non_snake_case)] + +extern "C" { + fn hlt_op(); +} + +use cpu::arith::*; +use cpu::cpu::*; +use cpu::fpu::*; +use cpu::global_pointers::*; +use cpu::misc_instr::*; +use cpu::misc_instr::{pop16, pop32s, push16, push32}; +use cpu::string::*; +use softfloat::F80; + +pub unsafe fn instr_00_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| add8(x, read_reg8(r))) } +pub unsafe fn instr_00_reg(r1: i32, r: i32) { write_reg8(r1, add8(read_reg8(r1), read_reg8(r))); } +pub unsafe fn instr16_01_mem(addr: i32, r: i32) { + safe_read_write16(addr, &|x| add16(x, read_reg16(r))) +} +pub unsafe fn instr16_01_reg(r1: i32, r: i32) { + write_reg16(r1, add16(read_reg16(r1), read_reg16(r))); +} +pub unsafe fn instr32_01_mem(addr: i32, r: i32) { + safe_read_write32(addr, &|x| add32(x, read_reg32(r))) +} +pub unsafe fn instr32_01_reg(r1: i32, r: i32) { + write_reg32(r1, add32(read_reg32(r1), read_reg32(r))); +} +pub unsafe fn instr_02_mem(addr: i32, r: i32) { + write_reg8( + r, + add8(read_reg8(r), return_on_pagefault!(safe_read8(addr))), + ); +} +pub unsafe fn instr_02_reg(r1: i32, r: i32) { write_reg8(r, add8(read_reg8(r), read_reg8(r1))); } +pub unsafe fn instr16_03_mem(addr: i32, r: i32) { + write_reg16( + r, + add16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_03_reg(r1: i32, r: i32) { + write_reg16(r, add16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_03_mem(addr: i32, r: i32) { + write_reg32( + r, + add32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_03_reg(r1: i32, r: i32) { + write_reg32(r, add32(read_reg32(r), read_reg32(r1))); +} +pub unsafe fn instr_04(imm8: i32) { write_reg8(AL, add8(read_reg8(AL), imm8)); } +pub unsafe fn instr16_05(imm16: i32) { write_reg16(AX, add16(read_reg16(AX), imm16)); } +pub unsafe fn instr32_05(imm32: i32) { write_reg32(EAX, add32(read_reg32(EAX), imm32)); } +pub unsafe fn instr16_06() { + return_on_pagefault!(push16(*sreg.offset(ES as isize) as i32)); +} +pub unsafe fn instr32_06() { return_on_pagefault!(push32_sreg(ES)) } + +#[no_mangle] +pub unsafe fn instr16_07() { + if !switch_seg(ES, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) { + return; + } + adjust_stack_reg(2); +} +#[no_mangle] +pub unsafe fn instr32_07() { + if !switch_seg( + ES, + return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF, + ) { + return; + } + adjust_stack_reg(4); +} + +pub unsafe fn instr_08_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| or8(x, read_reg8(r))) } +pub unsafe fn instr_08_reg(r1: i32, r: i32) { write_reg8(r1, or8(read_reg8(r1), read_reg8(r))); } +pub unsafe fn instr16_09_mem(addr: i32, r: i32) { + safe_read_write16(addr, &|x| or16(x, read_reg16(r))) +} +pub unsafe fn instr16_09_reg(r1: i32, r: i32) { + write_reg16(r1, or16(read_reg16(r1), read_reg16(r))); +} +pub unsafe fn instr32_09_mem(addr: i32, r: i32) { + safe_read_write32(addr, &|x| or32(x, read_reg32(r))) +} +pub unsafe fn instr32_09_reg(r1: i32, r: i32) { + write_reg32(r1, or32(read_reg32(r1), read_reg32(r))); +} +pub unsafe fn instr_0A_mem(addr: i32, r: i32) { + write_reg8(r, or8(read_reg8(r), return_on_pagefault!(safe_read8(addr)))); +} +pub unsafe fn instr_0A_reg(r1: i32, r: i32) { write_reg8(r, or8(read_reg8(r), read_reg8(r1))); } +pub unsafe fn instr16_0B_mem(addr: i32, r: i32) { + write_reg16( + r, + or16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_0B_reg(r1: i32, r: i32) { + write_reg16(r, or16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_0B_mem(addr: i32, r: i32) { + write_reg32( + r, + or32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_0B_reg(r1: i32, r: i32) { + write_reg32(r, or32(read_reg32(r), read_reg32(r1))); +} +pub unsafe fn instr_0C(imm8: i32) { write_reg8(AL, or8(read_reg8(AL), imm8)); } +pub unsafe fn instr16_0D(imm16: i32) { write_reg16(AX, or16(read_reg16(AX), imm16)); } +pub unsafe fn instr32_0D(imm32: i32) { write_reg32(EAX, or32(read_reg32(EAX), imm32)); } + +pub unsafe fn instr16_0E() { + return_on_pagefault!(push16(*sreg.offset(CS as isize) as i32)); +} +pub unsafe fn instr32_0E() { return_on_pagefault!(push32_sreg(CS)) } + +pub unsafe fn instr16_0F() { run_instruction0f_16(return_on_pagefault!(read_imm8())); } +pub unsafe fn instr32_0F() { run_instruction0f_32(return_on_pagefault!(read_imm8())); } + +pub unsafe fn instr_10_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| adc8(x, read_reg8(r))) } +pub unsafe fn instr_10_reg(r1: i32, r: i32) { write_reg8(r1, adc8(read_reg8(r1), read_reg8(r))); } +pub unsafe fn instr16_11_mem(addr: i32, r: i32) { + safe_read_write16(addr, &|x| adc16(x, read_reg16(r))) +} +pub unsafe fn instr16_11_reg(r1: i32, r: i32) { + write_reg16(r1, adc16(read_reg16(r1), read_reg16(r))); +} +pub unsafe fn instr32_11_mem(addr: i32, r: i32) { + safe_read_write32(addr, &|x| adc32(x, read_reg32(r))) +} +pub unsafe fn instr32_11_reg(r1: i32, r: i32) { + write_reg32(r1, adc32(read_reg32(r1), read_reg32(r))); +} +pub unsafe fn instr_12_mem(addr: i32, r: i32) { + write_reg8( + r, + adc8(read_reg8(r), return_on_pagefault!(safe_read8(addr))), + ); +} +pub unsafe fn instr_12_reg(r1: i32, r: i32) { write_reg8(r, adc8(read_reg8(r), read_reg8(r1))); } +pub unsafe fn instr16_13_mem(addr: i32, r: i32) { + write_reg16( + r, + adc16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_13_reg(r1: i32, r: i32) { + write_reg16(r, adc16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_13_mem(addr: i32, r: i32) { + write_reg32( + r, + adc32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_13_reg(r1: i32, r: i32) { + write_reg32(r, adc32(read_reg32(r), read_reg32(r1))); +} +pub unsafe fn instr_14(imm8: i32) { write_reg8(AL, adc8(read_reg8(AL), imm8)); } +pub unsafe fn instr16_15(imm16: i32) { write_reg16(AX, adc16(read_reg16(AX), imm16)); } +pub unsafe fn instr32_15(imm32: i32) { write_reg32(EAX, adc32(read_reg32(EAX), imm32)); } + +pub unsafe fn instr16_16() { + return_on_pagefault!(push16(*sreg.offset(SS as isize) as i32)); +} +pub unsafe fn instr32_16() { return_on_pagefault!(push32_sreg(SS)) } + +#[no_mangle] +pub unsafe fn instr16_17() { + if !switch_seg(SS, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) { + return; + } + adjust_stack_reg(2); +} +#[no_mangle] +pub unsafe fn instr32_17() { + if !switch_seg( + SS, + return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF, + ) { + return; + } + adjust_stack_reg(4); +} + +pub unsafe fn instr_18_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| sbb8(x, read_reg8(r))) } +pub unsafe fn instr_18_reg(r1: i32, r: i32) { write_reg8(r1, sbb8(read_reg8(r1), read_reg8(r))); } +pub unsafe fn instr16_19_mem(addr: i32, r: i32) { + safe_read_write16(addr, &|x| sbb16(x, read_reg16(r))) +} +pub unsafe fn instr16_19_reg(r1: i32, r: i32) { + write_reg16(r1, sbb16(read_reg16(r1), read_reg16(r))); +} +pub unsafe fn instr32_19_mem(addr: i32, r: i32) { + safe_read_write32(addr, &|x| sbb32(x, read_reg32(r))) +} +pub unsafe fn instr32_19_reg(r1: i32, r: i32) { + write_reg32(r1, sbb32(read_reg32(r1), read_reg32(r))); +} +pub unsafe fn instr_1A_mem(addr: i32, r: i32) { + write_reg8( + r, + sbb8(read_reg8(r), return_on_pagefault!(safe_read8(addr))), + ); +} +pub unsafe fn instr_1A_reg(r1: i32, r: i32) { write_reg8(r, sbb8(read_reg8(r), read_reg8(r1))); } +pub unsafe fn instr16_1B_mem(addr: i32, r: i32) { + write_reg16( + r, + sbb16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_1B_reg(r1: i32, r: i32) { + write_reg16(r, sbb16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_1B_mem(addr: i32, r: i32) { + write_reg32( + r, + sbb32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_1B_reg(r1: i32, r: i32) { + write_reg32(r, sbb32(read_reg32(r), read_reg32(r1))); +} +pub unsafe fn instr_1C(imm8: i32) { write_reg8(AL, sbb8(read_reg8(AL), imm8)); } +pub unsafe fn instr16_1D(imm16: i32) { write_reg16(AX, sbb16(read_reg16(AX), imm16)); } +pub unsafe fn instr32_1D(imm32: i32) { write_reg32(EAX, sbb32(read_reg32(EAX), imm32)); } + +pub unsafe fn instr16_1E() { + return_on_pagefault!(push16(*sreg.offset(DS as isize) as i32)); +} +pub unsafe fn instr32_1E() { return_on_pagefault!(push32_sreg(DS)) } + +#[no_mangle] +pub unsafe fn instr16_1F() { + if !switch_seg(DS, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) { + return; + } + adjust_stack_reg(2); +} +#[no_mangle] +pub unsafe fn instr32_1F() { + if !switch_seg( + DS, + return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF, + ) { + return; + } + adjust_stack_reg(4); +} + +pub unsafe fn instr_20_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| and8(x, read_reg8(r))) } +pub unsafe fn instr_20_reg(r1: i32, r: i32) { write_reg8(r1, and8(read_reg8(r1), read_reg8(r))); } +pub unsafe fn instr16_21_mem(addr: i32, r: i32) { + safe_read_write16(addr, &|x| and16(x, read_reg16(r))) +} +pub unsafe fn instr16_21_reg(r1: i32, r: i32) { + write_reg16(r1, and16(read_reg16(r1), read_reg16(r))); +} +pub unsafe fn instr32_21_mem(addr: i32, r: i32) { + safe_read_write32(addr, &|x| and32(x, read_reg32(r))) +} +pub unsafe fn instr32_21_reg(r1: i32, r: i32) { + write_reg32(r1, and32(read_reg32(r1), read_reg32(r))); +} +pub unsafe fn instr_22_mem(addr: i32, r: i32) { + write_reg8( + r, + and8(read_reg8(r), return_on_pagefault!(safe_read8(addr))), + ); +} +pub unsafe fn instr_22_reg(r1: i32, r: i32) { write_reg8(r, and8(read_reg8(r), read_reg8(r1))); } +pub unsafe fn instr16_23_mem(addr: i32, r: i32) { + write_reg16( + r, + and16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_23_reg(r1: i32, r: i32) { + write_reg16(r, and16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_23_mem(addr: i32, r: i32) { + write_reg32( + r, + and32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_23_reg(r1: i32, r: i32) { + write_reg32(r, and32(read_reg32(r), read_reg32(r1))); +} +pub unsafe fn instr_24(imm8: i32) { write_reg8(AL, and8(read_reg8(AL), imm8)); } +pub unsafe fn instr16_25(imm16: i32) { write_reg16(AX, and16(read_reg16(AX), imm16)); } +pub unsafe fn instr32_25(imm32: i32) { write_reg32(EAX, and32(read_reg32(EAX), imm32)); } + +pub unsafe fn instr_26() { segment_prefix_op(ES); } + +#[no_mangle] +pub unsafe fn instr_27() { bcd_daa(); } + +pub unsafe fn instr_28_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| sub8(x, read_reg8(r))) } +pub unsafe fn instr_28_reg(r1: i32, r: i32) { write_reg8(r1, sub8(read_reg8(r1), read_reg8(r))); } +pub unsafe fn instr16_29_mem(addr: i32, r: i32) { + safe_read_write16(addr, &|x| sub16(x, read_reg16(r))) +} +pub unsafe fn instr16_29_reg(r1: i32, r: i32) { + write_reg16(r1, sub16(read_reg16(r1), read_reg16(r))); +} +pub unsafe fn instr32_29_mem(addr: i32, r: i32) { + safe_read_write32(addr, &|x| sub32(x, read_reg32(r))) +} +pub unsafe fn instr32_29_reg(r1: i32, r: i32) { + write_reg32(r1, sub32(read_reg32(r1), read_reg32(r))); +} +pub unsafe fn instr_2A_mem(addr: i32, r: i32) { + write_reg8( + r, + sub8(read_reg8(r), return_on_pagefault!(safe_read8(addr))), + ); +} +pub unsafe fn instr_2A_reg(r1: i32, r: i32) { write_reg8(r, sub8(read_reg8(r), read_reg8(r1))); } +pub unsafe fn instr16_2B_mem(addr: i32, r: i32) { + write_reg16( + r, + sub16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_2B_reg(r1: i32, r: i32) { + write_reg16(r, sub16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_2B_mem(addr: i32, r: i32) { + write_reg32( + r, + sub32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_2B_reg(r1: i32, r: i32) { + write_reg32(r, sub32(read_reg32(r), read_reg32(r1))); +} +pub unsafe fn instr_2C(imm8: i32) { write_reg8(AL, sub8(read_reg8(AL), imm8)); } +pub unsafe fn instr16_2D(imm16: i32) { write_reg16(AX, sub16(read_reg16(AX), imm16)); } +pub unsafe fn instr32_2D(imm32: i32) { write_reg32(EAX, sub32(read_reg32(EAX), imm32)); } + +pub unsafe fn instr_2E() { segment_prefix_op(CS); } + +#[no_mangle] +pub unsafe fn instr_2F() { bcd_das(); } + +pub unsafe fn instr_30_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| xor8(x, read_reg8(r))) } +pub unsafe fn instr_30_reg(r1: i32, r: i32) { write_reg8(r1, xor8(read_reg8(r1), read_reg8(r))); } +pub unsafe fn instr16_31_mem(addr: i32, r: i32) { + safe_read_write16(addr, &|x| xor16(x, read_reg16(r))) +} +pub unsafe fn instr16_31_reg(r1: i32, r: i32) { + write_reg16(r1, xor16(read_reg16(r1), read_reg16(r))); +} +pub unsafe fn instr32_31_mem(addr: i32, r: i32) { + safe_read_write32(addr, &|x| xor32(x, read_reg32(r))) +} +pub unsafe fn instr32_31_reg(r1: i32, r: i32) { + write_reg32(r1, xor32(read_reg32(r1), read_reg32(r))); +} +pub unsafe fn instr_32_mem(addr: i32, r: i32) { + write_reg8( + r, + xor8(read_reg8(r), return_on_pagefault!(safe_read8(addr))), + ); +} +pub unsafe fn instr_32_reg(r1: i32, r: i32) { write_reg8(r, xor8(read_reg8(r), read_reg8(r1))); } +pub unsafe fn instr16_33_mem(addr: i32, r: i32) { + write_reg16( + r, + xor16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_33_reg(r1: i32, r: i32) { + write_reg16(r, xor16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_33_mem(addr: i32, r: i32) { + write_reg32( + r, + xor32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_33_reg(r1: i32, r: i32) { + write_reg32(r, xor32(read_reg32(r), read_reg32(r1))); +} +pub unsafe fn instr_34(imm8: i32) { write_reg8(AL, xor8(read_reg8(AL), imm8)); } +pub unsafe fn instr16_35(imm16: i32) { write_reg16(AX, xor16(read_reg16(AX), imm16)); } +pub unsafe fn instr32_35(imm32: i32) { write_reg32(EAX, xor32(read_reg32(EAX), imm32)); } + +pub unsafe fn instr_36() { segment_prefix_op(SS); } + +#[no_mangle] +pub unsafe fn instr_37() { bcd_aaa(); } + +pub unsafe fn instr_38_mem(addr: i32, r: i32) { + cmp8(return_on_pagefault!(safe_read8(addr)), read_reg8(r)); +} +pub unsafe fn instr_38_reg(r1: i32, r: i32) { cmp8(read_reg8(r1), read_reg8(r)); } +pub unsafe fn instr16_39_mem(addr: i32, r: i32) { + cmp16(return_on_pagefault!(safe_read16(addr)), read_reg16(r)); +} +pub unsafe fn instr16_39_reg(r1: i32, r: i32) { cmp16(read_reg16(r1), read_reg16(r)); } +pub unsafe fn instr32_39_mem(addr: i32, r: i32) { + cmp32(return_on_pagefault!(safe_read32s(addr)), read_reg32(r)); +} +pub unsafe fn instr32_39_reg(r1: i32, r: i32) { cmp32(read_reg32(r1), read_reg32(r)); } +pub unsafe fn instr_3A_mem(addr: i32, r: i32) { + cmp8(read_reg8(r), return_on_pagefault!(safe_read8(addr))); +} +pub unsafe fn instr_3A_reg(r1: i32, r: i32) { cmp8(read_reg8(r), read_reg8(r1)); } +pub unsafe fn instr16_3B_mem(addr: i32, r: i32) { + cmp16(read_reg16(r), return_on_pagefault!(safe_read16(addr))); +} +pub unsafe fn instr16_3B_reg(r1: i32, r: i32) { cmp16(read_reg16(r), read_reg16(r1)); } +pub unsafe fn instr32_3B_mem(addr: i32, r: i32) { + cmp32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))); +} +pub unsafe fn instr32_3B_reg(r1: i32, r: i32) { cmp32(read_reg32(r), read_reg32(r1)); } +pub unsafe fn instr_3C(imm8: i32) { cmp8(read_reg8(AL), imm8); } +pub unsafe fn instr16_3D(imm16: i32) { cmp16(read_reg16(AX), imm16); } +pub unsafe fn instr32_3D(imm32: i32) { cmp32(read_reg32(EAX), imm32); } + +pub unsafe fn instr_3E() { segment_prefix_op(DS); } + +#[no_mangle] +pub unsafe fn instr_3F() { bcd_aas(); } + +pub unsafe fn instr16_40() { write_reg16(AX, inc16(read_reg16(AX))); } +pub unsafe fn instr32_40() { write_reg32(EAX, inc32(read_reg32(EAX))); } +pub unsafe fn instr16_41() { write_reg16(CX, inc16(read_reg16(CX))); } +pub unsafe fn instr32_41() { write_reg32(ECX, inc32(read_reg32(ECX))); } +pub unsafe fn instr16_42() { write_reg16(DX, inc16(read_reg16(DX))); } +pub unsafe fn instr32_42() { write_reg32(EDX, inc32(read_reg32(EDX))); } +pub unsafe fn instr16_43() { write_reg16(BX, inc16(read_reg16(BX))); } +pub unsafe fn instr32_43() { write_reg32(EBX, inc32(read_reg32(EBX))); } +pub unsafe fn instr16_44() { write_reg16(SP, inc16(read_reg16(SP))); } +pub unsafe fn instr32_44() { write_reg32(ESP, inc32(read_reg32(ESP))); } +pub unsafe fn instr16_45() { write_reg16(BP, inc16(read_reg16(BP))); } +pub unsafe fn instr32_45() { write_reg32(EBP, inc32(read_reg32(EBP))); } +pub unsafe fn instr16_46() { write_reg16(SI, inc16(read_reg16(SI))); } +pub unsafe fn instr32_46() { write_reg32(ESI, inc32(read_reg32(ESI))); } +pub unsafe fn instr16_47() { write_reg16(DI, inc16(read_reg16(DI))); } +pub unsafe fn instr32_47() { write_reg32(EDI, inc32(read_reg32(EDI))); } +pub unsafe fn instr16_48() { write_reg16(AX, dec16(read_reg16(AX))); } +pub unsafe fn instr32_48() { write_reg32(EAX, dec32(read_reg32(EAX))); } +pub unsafe fn instr16_49() { write_reg16(CX, dec16(read_reg16(CX))); } +pub unsafe fn instr32_49() { write_reg32(ECX, dec32(read_reg32(ECX))); } +pub unsafe fn instr16_4A() { write_reg16(DX, dec16(read_reg16(DX))); } +pub unsafe fn instr32_4A() { write_reg32(EDX, dec32(read_reg32(EDX))); } +pub unsafe fn instr16_4B() { write_reg16(BX, dec16(read_reg16(BX))); } +pub unsafe fn instr32_4B() { write_reg32(EBX, dec32(read_reg32(EBX))); } +pub unsafe fn instr16_4C() { write_reg16(SP, dec16(read_reg16(SP))); } +pub unsafe fn instr32_4C() { write_reg32(ESP, dec32(read_reg32(ESP))); } +pub unsafe fn instr16_4D() { write_reg16(BP, dec16(read_reg16(BP))); } +pub unsafe fn instr32_4D() { write_reg32(EBP, dec32(read_reg32(EBP))); } +pub unsafe fn instr16_4E() { write_reg16(SI, dec16(read_reg16(SI))); } +pub unsafe fn instr32_4E() { write_reg32(ESI, dec32(read_reg32(ESI))); } +pub unsafe fn instr16_4F() { write_reg16(DI, dec16(read_reg16(DI))); } +pub unsafe fn instr32_4F() { write_reg32(EDI, dec32(read_reg32(EDI))); } + +pub unsafe fn push16_reg(r: i32) { + return_on_pagefault!(push16(read_reg16(r))); +} +pub unsafe fn push32_reg(r: i32) { + return_on_pagefault!(push32(read_reg32(r))); +} + +pub unsafe fn instr16_50() { push16_reg(AX) } +pub unsafe fn instr32_50() { push32_reg(EAX) } +pub unsafe fn instr16_51() { push16_reg(CX) } +pub unsafe fn instr32_51() { push32_reg(ECX) } +pub unsafe fn instr16_52() { push16_reg(DX) } +pub unsafe fn instr32_52() { push32_reg(EDX) } +pub unsafe fn instr16_53() { push16_reg(BX) } +pub unsafe fn instr32_53() { push32_reg(EBX) } +pub unsafe fn instr16_54() { push16_reg(SP) } +pub unsafe fn instr32_54() { push32_reg(ESP) } +pub unsafe fn instr16_55() { push16_reg(BP) } +pub unsafe fn instr32_55() { push32_reg(EBP) } +pub unsafe fn instr16_56() { push16_reg(SI) } +pub unsafe fn instr32_56() { push32_reg(ESI) } +pub unsafe fn instr16_57() { push16_reg(DI) } +pub unsafe fn instr32_57() { push32_reg(EDI) } +pub unsafe fn instr16_58() { write_reg16(AX, return_on_pagefault!(pop16())); } +pub unsafe fn instr32_58() { write_reg32(EAX, return_on_pagefault!(pop32s())); } +pub unsafe fn instr16_59() { write_reg16(CX, return_on_pagefault!(pop16())); } +pub unsafe fn instr32_59() { write_reg32(ECX, return_on_pagefault!(pop32s())); } +pub unsafe fn instr16_5A() { write_reg16(DX, return_on_pagefault!(pop16())); } +pub unsafe fn instr32_5A() { write_reg32(EDX, return_on_pagefault!(pop32s())); } +pub unsafe fn instr16_5B() { write_reg16(BX, return_on_pagefault!(pop16())); } +pub unsafe fn instr32_5B() { write_reg32(EBX, return_on_pagefault!(pop32s())); } +pub unsafe fn instr16_5C() { + write_reg16(SP, return_on_pagefault!(safe_read16(get_stack_pointer(0)))); +} +pub unsafe fn instr32_5C() { + write_reg32( + ESP, + return_on_pagefault!(safe_read32s(get_stack_pointer(0))), + ); +} +pub unsafe fn instr16_5D() { write_reg16(BP, return_on_pagefault!(pop16())); } +pub unsafe fn instr32_5D() { write_reg32(EBP, return_on_pagefault!(pop32s())); } +pub unsafe fn instr16_5E() { write_reg16(SI, return_on_pagefault!(pop16())); } +pub unsafe fn instr32_5E() { write_reg32(ESI, return_on_pagefault!(pop32s())); } +pub unsafe fn instr16_5F() { write_reg16(DI, return_on_pagefault!(pop16())); } +pub unsafe fn instr32_5F() { write_reg32(EDI, return_on_pagefault!(pop32s())); } + +#[no_mangle] +pub unsafe fn instr16_60() { pusha16(); } +#[no_mangle] +pub unsafe fn instr32_60() { pusha32(); } +#[no_mangle] +pub unsafe fn instr16_61() { popa16(); } +#[no_mangle] +pub unsafe fn instr32_61() { popa32(); } + +#[no_mangle] +pub unsafe fn instr_62_reg(_r2: i32, _r: i32) { + // bound + dbg_log!("Unimplemented BOUND instruction"); + dbg_assert!(false); +} +#[no_mangle] +pub unsafe fn instr_62_mem(_addr: i32, _r: i32) { + dbg_log!("Unimplemented BOUND instruction"); + dbg_assert!(false); +} + +pub unsafe fn arpl(seg: i32, r16: i32) -> i32 { + *flags_changed &= !FLAG_ZERO; + + if (seg & 3) < (r16 & 3) { + *flags |= FLAG_ZERO; + seg & !3 | r16 & 3 + } + else { + *flags &= !FLAG_ZERO; + seg + } +} + +#[no_mangle] +pub unsafe fn instr_63_mem(addr: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("arpl #ud"); + trigger_ud(); + return; + } + safe_read_write16(addr, &|x| arpl(x, read_reg16(r))) +} +#[no_mangle] +pub unsafe fn instr_63_reg(r1: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("arpl #ud"); + trigger_ud(); + return; + } + write_reg16(r1, arpl(read_reg16(r1), read_reg16(r))); +} + +pub unsafe fn instr_64() { segment_prefix_op(FS); } +pub unsafe fn instr_65() { segment_prefix_op(GS); } + +pub unsafe fn instr_66() { + // Operand-size override prefix + *prefixes = (*prefixes as i32 | PREFIX_MASK_OPSIZE) as u8; + run_prefix_instruction(); + *prefixes = 0; +} +pub unsafe fn instr_67() { + // Address-size override prefix + dbg_assert!(is_asize_32() == *is_32); + *prefixes = (*prefixes as i32 | PREFIX_MASK_ADDRSIZE) as u8; + run_prefix_instruction(); + *prefixes = 0; +} + +pub unsafe fn instr16_68(imm16: i32) { + return_on_pagefault!(push16(imm16)); +} +pub unsafe fn instr32_68(imm32: i32) { + return_on_pagefault!(push32(imm32)); +} +pub unsafe fn instr16_69_mem(addr: i32, r: i32, imm: i32) { + write_reg16(r, imul_reg16(return_on_pagefault!(safe_read16(addr)), imm)); +} +pub unsafe fn instr16_69_reg(r1: i32, r: i32, imm: i32) { + write_reg16(r, imul_reg16(read_reg16(r1), imm)); +} +pub unsafe fn instr32_69_mem(addr: i32, r: i32, imm: i32) { + write_reg32(r, imul_reg32(return_on_pagefault!(safe_read32s(addr)), imm)); +} +pub unsafe fn instr32_69_reg(r1: i32, r: i32, imm: i32) { + write_reg32(r, imul_reg32(read_reg32(r1), imm)); +} + +pub unsafe fn instr16_6A(imm8: i32) { + return_on_pagefault!(push16(imm8)); +} +pub unsafe fn instr32_6A(imm8: i32) { + return_on_pagefault!(push32(imm8)); +} +pub unsafe fn instr16_6B_mem(addr: i32, r: i32, imm: i32) { + write_reg16(r, imul_reg16(return_on_pagefault!(safe_read16(addr)), imm)); +} +pub unsafe fn instr16_6B_reg(r1: i32, r: i32, imm: i32) { + write_reg16(r, imul_reg16(read_reg16(r1), imm)); +} +pub unsafe fn instr32_6B_mem(addr: i32, r: i32, imm: i32) { + write_reg32(r, imul_reg32(return_on_pagefault!(safe_read32s(addr)), imm)); +} +pub unsafe fn instr32_6B_reg(r1: i32, r: i32, imm: i32) { + write_reg32(r, imul_reg32(read_reg32(r1), imm)); +} + +pub unsafe fn instr_6C() { insb_no_rep(is_asize_32()); } +pub unsafe fn instr_F26C() { insb_rep(is_asize_32()); } +pub unsafe fn instr_F36C() { insb_rep(is_asize_32()); } +pub unsafe fn instr16_6D() { insw_no_rep(is_asize_32()); } +pub unsafe fn instr32_6D() { insd_no_rep(is_asize_32()); } +pub unsafe fn instr16_F26D() { insw_rep(is_asize_32()); } +pub unsafe fn instr16_F36D() { insw_rep(is_asize_32()); } +pub unsafe fn instr32_F26D() { insd_rep(is_asize_32()); } +pub unsafe fn instr32_F36D() { insd_rep(is_asize_32()); } + +pub unsafe fn instr_6E() { outsb_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr_F26E() { outsb_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr_F36E() { outsb_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } + +pub unsafe fn instr16_6F() { + outsw_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr32_6F() { + outsd_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr16_F26F() { outsw_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr16_F36F() { outsw_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr32_F26F() { outsd_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr32_F36F() { outsd_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } + +pub unsafe fn instr16_70(imm8: i32) { jmpcc16(test_o(), imm8); } +pub unsafe fn instr16_71(imm8: i32) { jmpcc16(!test_o(), imm8); } +pub unsafe fn instr16_72(imm8: i32) { jmpcc16(test_b(), imm8); } +pub unsafe fn instr16_73(imm8: i32) { jmpcc16(!test_b(), imm8); } +pub unsafe fn instr16_74(imm8: i32) { jmpcc16(test_z(), imm8); } +pub unsafe fn instr16_75(imm8: i32) { jmpcc16(!test_z(), imm8); } +pub unsafe fn instr16_76(imm8: i32) { jmpcc16(test_be(), imm8); } +pub unsafe fn instr16_77(imm8: i32) { jmpcc16(!test_be(), imm8); } +pub unsafe fn instr16_78(imm8: i32) { jmpcc16(test_s(), imm8); } +pub unsafe fn instr16_79(imm8: i32) { jmpcc16(!test_s(), imm8); } +pub unsafe fn instr16_7A(imm8: i32) { jmpcc16(test_p(), imm8); } +pub unsafe fn instr16_7B(imm8: i32) { jmpcc16(!test_p(), imm8); } +pub unsafe fn instr16_7C(imm8: i32) { jmpcc16(test_l(), imm8); } +pub unsafe fn instr16_7D(imm8: i32) { jmpcc16(!test_l(), imm8); } +pub unsafe fn instr16_7E(imm8: i32) { jmpcc16(test_le(), imm8); } +pub unsafe fn instr16_7F(imm8: i32) { jmpcc16(!test_le(), imm8); } +pub unsafe fn instr32_70(imm8: i32) { jmpcc32(test_o(), imm8); } +pub unsafe fn instr32_71(imm8: i32) { jmpcc32(!test_o(), imm8); } +pub unsafe fn instr32_72(imm8: i32) { jmpcc32(test_b(), imm8); } +pub unsafe fn instr32_73(imm8: i32) { jmpcc32(!test_b(), imm8); } +pub unsafe fn instr32_74(imm8: i32) { jmpcc32(test_z(), imm8); } +pub unsafe fn instr32_75(imm8: i32) { jmpcc32(!test_z(), imm8); } +pub unsafe fn instr32_76(imm8: i32) { jmpcc32(test_be(), imm8); } +pub unsafe fn instr32_77(imm8: i32) { jmpcc32(!test_be(), imm8); } +pub unsafe fn instr32_78(imm8: i32) { jmpcc32(test_s(), imm8); } +pub unsafe fn instr32_79(imm8: i32) { jmpcc32(!test_s(), imm8); } +pub unsafe fn instr32_7A(imm8: i32) { jmpcc32(test_p(), imm8); } +pub unsafe fn instr32_7B(imm8: i32) { jmpcc32(!test_p(), imm8); } +pub unsafe fn instr32_7C(imm8: i32) { jmpcc32(test_l(), imm8); } +pub unsafe fn instr32_7D(imm8: i32) { jmpcc32(!test_l(), imm8); } +pub unsafe fn instr32_7E(imm8: i32) { jmpcc32(test_le(), imm8); } +pub unsafe fn instr32_7F(imm8: i32) { jmpcc32(!test_le(), imm8); } + +pub unsafe fn instr_80_0_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| add8(x, imm)) } +pub unsafe fn instr_80_0_reg(r1: i32, imm: i32) { write_reg8(r1, add8(read_reg8(r1), imm)); } +pub unsafe fn instr_80_1_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| or8(x, imm)) } +pub unsafe fn instr_80_1_reg(r1: i32, imm: i32) { write_reg8(r1, or8(read_reg8(r1), imm)); } +pub unsafe fn instr_80_2_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| adc8(x, imm)) } +pub unsafe fn instr_80_2_reg(r1: i32, imm: i32) { write_reg8(r1, adc8(read_reg8(r1), imm)); } +pub unsafe fn instr_80_3_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sbb8(x, imm)) } +pub unsafe fn instr_80_3_reg(r1: i32, imm: i32) { write_reg8(r1, sbb8(read_reg8(r1), imm)); } +pub unsafe fn instr_80_4_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| and8(x, imm)) } +pub unsafe fn instr_80_4_reg(r1: i32, imm: i32) { write_reg8(r1, and8(read_reg8(r1), imm)); } +pub unsafe fn instr_80_5_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sub8(x, imm)) } +pub unsafe fn instr_80_5_reg(r1: i32, imm: i32) { write_reg8(r1, sub8(read_reg8(r1), imm)); } +pub unsafe fn instr_80_6_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| xor8(x, imm)) } +pub unsafe fn instr_80_6_reg(r1: i32, imm: i32) { write_reg8(r1, xor8(read_reg8(r1), imm)); } +pub unsafe fn instr_80_7_reg(r: i32, imm: i32) { cmp8(read_reg8(r), imm); } +pub unsafe fn instr_80_7_mem(addr: i32, imm: i32) { + cmp8(return_on_pagefault!(safe_read8(addr)), imm); +} +pub unsafe fn instr16_81_0_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| add16(x, imm)) } +pub unsafe fn instr16_81_0_reg(r1: i32, imm: i32) { write_reg16(r1, add16(read_reg16(r1), imm)); } +pub unsafe fn instr16_81_1_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| or16(x, imm)) } +pub unsafe fn instr16_81_1_reg(r1: i32, imm: i32) { write_reg16(r1, or16(read_reg16(r1), imm)); } +pub unsafe fn instr16_81_2_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| adc16(x, imm)) } +pub unsafe fn instr16_81_2_reg(r1: i32, imm: i32) { write_reg16(r1, adc16(read_reg16(r1), imm)); } +pub unsafe fn instr16_81_3_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| sbb16(x, imm)) } +pub unsafe fn instr16_81_3_reg(r1: i32, imm: i32) { write_reg16(r1, sbb16(read_reg16(r1), imm)); } +pub unsafe fn instr16_81_4_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| and16(x, imm)) } +pub unsafe fn instr16_81_4_reg(r1: i32, imm: i32) { write_reg16(r1, and16(read_reg16(r1), imm)); } +pub unsafe fn instr16_81_5_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| sub16(x, imm)) } +pub unsafe fn instr16_81_5_reg(r1: i32, imm: i32) { write_reg16(r1, sub16(read_reg16(r1), imm)); } +pub unsafe fn instr16_81_6_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| xor16(x, imm)) } +pub unsafe fn instr16_81_6_reg(r1: i32, imm: i32) { write_reg16(r1, xor16(read_reg16(r1), imm)); } +pub unsafe fn instr16_81_7_reg(r: i32, imm: i32) { cmp16(read_reg16(r), imm); } +pub unsafe fn instr16_81_7_mem(addr: i32, imm: i32) { + cmp16(return_on_pagefault!(safe_read16(addr)), imm); +} +pub unsafe fn instr32_81_0_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| add32(x, imm)) } +pub unsafe fn instr32_81_0_reg(r1: i32, imm: i32) { write_reg32(r1, add32(read_reg32(r1), imm)); } +pub unsafe fn instr32_81_1_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| or32(x, imm)) } +pub unsafe fn instr32_81_1_reg(r1: i32, imm: i32) { write_reg32(r1, or32(read_reg32(r1), imm)); } +pub unsafe fn instr32_81_2_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| adc32(x, imm)) } +pub unsafe fn instr32_81_2_reg(r1: i32, imm: i32) { write_reg32(r1, adc32(read_reg32(r1), imm)); } +pub unsafe fn instr32_81_3_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| sbb32(x, imm)) } +pub unsafe fn instr32_81_3_reg(r1: i32, imm: i32) { write_reg32(r1, sbb32(read_reg32(r1), imm)); } +pub unsafe fn instr32_81_4_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| and32(x, imm)) } +pub unsafe fn instr32_81_4_reg(r1: i32, imm: i32) { write_reg32(r1, and32(read_reg32(r1), imm)); } +pub unsafe fn instr32_81_5_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| sub32(x, imm)) } +pub unsafe fn instr32_81_5_reg(r1: i32, imm: i32) { write_reg32(r1, sub32(read_reg32(r1), imm)); } +pub unsafe fn instr32_81_6_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| xor32(x, imm)) } +pub unsafe fn instr32_81_6_reg(r1: i32, imm: i32) { write_reg32(r1, xor32(read_reg32(r1), imm)); } +pub unsafe fn instr32_81_7_reg(r: i32, imm: i32) { cmp32(read_reg32(r), imm); } +pub unsafe fn instr32_81_7_mem(addr: i32, imm: i32) { + cmp32(return_on_pagefault!(safe_read32s(addr)), imm); +} +pub unsafe fn instr_82_0_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| add8(x, imm)) } +pub unsafe fn instr_82_0_reg(r1: i32, imm: i32) { write_reg8(r1, add8(read_reg8(r1), imm)); } +pub unsafe fn instr_82_1_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| or8(x, imm)) } +pub unsafe fn instr_82_1_reg(r1: i32, imm: i32) { write_reg8(r1, or8(read_reg8(r1), imm)); } +pub unsafe fn instr_82_2_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| adc8(x, imm)) } +pub unsafe fn instr_82_2_reg(r1: i32, imm: i32) { write_reg8(r1, adc8(read_reg8(r1), imm)); } +pub unsafe fn instr_82_3_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sbb8(x, imm)) } +pub unsafe fn instr_82_3_reg(r1: i32, imm: i32) { write_reg8(r1, sbb8(read_reg8(r1), imm)); } +pub unsafe fn instr_82_4_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| and8(x, imm)) } +pub unsafe fn instr_82_4_reg(r1: i32, imm: i32) { write_reg8(r1, and8(read_reg8(r1), imm)); } +pub unsafe fn instr_82_5_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sub8(x, imm)) } +pub unsafe fn instr_82_5_reg(r1: i32, imm: i32) { write_reg8(r1, sub8(read_reg8(r1), imm)); } +pub unsafe fn instr_82_6_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| xor8(x, imm)) } +pub unsafe fn instr_82_6_reg(r1: i32, imm: i32) { write_reg8(r1, xor8(read_reg8(r1), imm)); } +pub unsafe fn instr_82_7_reg(r: i32, imm: i32) { cmp8(read_reg8(r), imm); } +pub unsafe fn instr_82_7_mem(addr: i32, imm: i32) { + cmp8(return_on_pagefault!(safe_read8(addr)), imm); +} +pub unsafe fn instr16_83_0_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| add16(x, imm & 0xFFFF)) +} +pub unsafe fn instr16_83_0_reg(r1: i32, imm: i32) { + write_reg16(r1, add16(read_reg16(r1), imm & 0xFFFF)); +} +pub unsafe fn instr16_83_1_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| or16(x, imm & 0xFFFF)) +} +pub unsafe fn instr16_83_1_reg(r1: i32, imm: i32) { + write_reg16(r1, or16(read_reg16(r1), imm & 0xFFFF)); +} +pub unsafe fn instr16_83_2_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| adc16(x, imm & 0xFFFF)) +} +pub unsafe fn instr16_83_2_reg(r1: i32, imm: i32) { + write_reg16(r1, adc16(read_reg16(r1), imm & 0xFFFF)); +} +pub unsafe fn instr16_83_3_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| sbb16(x, imm & 0xFFFF)) +} +pub unsafe fn instr16_83_3_reg(r1: i32, imm: i32) { + write_reg16(r1, sbb16(read_reg16(r1), imm & 0xFFFF)); +} +pub unsafe fn instr16_83_4_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| and16(x, imm & 0xFFFF)) +} +pub unsafe fn instr16_83_4_reg(r1: i32, imm: i32) { + write_reg16(r1, and16(read_reg16(r1), imm & 0xFFFF)); +} +pub unsafe fn instr16_83_5_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| sub16(x, imm & 0xFFFF)) +} +pub unsafe fn instr16_83_5_reg(r1: i32, imm: i32) { + write_reg16(r1, sub16(read_reg16(r1), imm & 0xFFFF)); +} +pub unsafe fn instr16_83_6_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| xor16(x, imm & 0xFFFF)) +} +pub unsafe fn instr16_83_6_reg(r1: i32, imm: i32) { + write_reg16(r1, xor16(read_reg16(r1), imm & 0xFFFF)); +} +pub unsafe fn instr16_83_7_reg(r: i32, imm: i32) { cmp16(read_reg16(r), imm & 0xFFFF); } +pub unsafe fn instr16_83_7_mem(addr: i32, imm: i32) { + cmp16(return_on_pagefault!(safe_read16(addr)), imm & 0xFFFF); +} + +pub unsafe fn instr32_83_0_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| add32(x, imm)) } +pub unsafe fn instr32_83_0_reg(r1: i32, imm: i32) { write_reg32(r1, add32(read_reg32(r1), imm)); } +pub unsafe fn instr32_83_1_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| or32(x, imm)) } +pub unsafe fn instr32_83_1_reg(r1: i32, imm: i32) { write_reg32(r1, or32(read_reg32(r1), imm)); } +pub unsafe fn instr32_83_2_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| adc32(x, imm)) } +pub unsafe fn instr32_83_2_reg(r1: i32, imm: i32) { write_reg32(r1, adc32(read_reg32(r1), imm)); } +pub unsafe fn instr32_83_3_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| sbb32(x, imm)) } +pub unsafe fn instr32_83_3_reg(r1: i32, imm: i32) { write_reg32(r1, sbb32(read_reg32(r1), imm)); } +pub unsafe fn instr32_83_4_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| and32(x, imm)) } +pub unsafe fn instr32_83_4_reg(r1: i32, imm: i32) { write_reg32(r1, and32(read_reg32(r1), imm)); } +pub unsafe fn instr32_83_5_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| sub32(x, imm)) } +pub unsafe fn instr32_83_5_reg(r1: i32, imm: i32) { write_reg32(r1, sub32(read_reg32(r1), imm)); } +pub unsafe fn instr32_83_6_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| xor32(x, imm)) } +pub unsafe fn instr32_83_6_reg(r1: i32, imm: i32) { write_reg32(r1, xor32(read_reg32(r1), imm)); } +pub unsafe fn instr32_83_7_reg(r: i32, imm: i32) { cmp32(read_reg32(r), imm); } +pub unsafe fn instr32_83_7_mem(addr: i32, imm: i32) { + cmp32(return_on_pagefault!(safe_read32s(addr)), imm); +} + +pub unsafe fn instr_84_mem(addr: i32, r: i32) { + test8(return_on_pagefault!(safe_read8(addr)), read_reg8(r)); +} +pub unsafe fn instr_84_reg(r1: i32, r: i32) { test8(read_reg8(r1), read_reg8(r)); } +pub unsafe fn instr16_85_mem(addr: i32, r: i32) { + test16(return_on_pagefault!(safe_read16(addr)), read_reg16(r)); +} +pub unsafe fn instr16_85_reg(r1: i32, r: i32) { test16(read_reg16(r1), read_reg16(r)); } +pub unsafe fn instr32_85_mem(addr: i32, r: i32) { + test32(return_on_pagefault!(safe_read32s(addr)), read_reg32(r)); +} +pub unsafe fn instr32_85_reg(r1: i32, r: i32) { test32(read_reg32(r1), read_reg32(r)); } +pub unsafe fn instr_86_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| xchg8(x, r)) } +pub unsafe fn instr_86_reg(r1: i32, r: i32) { write_reg8(r1, xchg8(read_reg8(r1), r)); } +pub unsafe fn instr16_87_mem(addr: i32, r: i32) { safe_read_write16(addr, &|x| xchg16(x, r)) } +pub unsafe fn instr16_87_reg(r1: i32, r: i32) { write_reg16(r1, xchg16(read_reg16(r1), r)); } +pub unsafe fn instr32_87_mem(addr: i32, r: i32) { safe_read_write32(addr, &|x| xchg32(x, r)) } +pub unsafe fn instr32_87_reg(r1: i32, r: i32) { write_reg32(r1, xchg32(read_reg32(r1), r)); } +pub unsafe fn instr_88_reg(r2: i32, r: i32) { write_reg8(r2, read_reg8(r)); } +pub unsafe fn instr_88_mem(addr: i32, r: i32) { + return_on_pagefault!(safe_write8(addr, read_reg8(r))); +} +pub unsafe fn instr16_89_reg(r2: i32, r: i32) { write_reg16(r2, read_reg16(r)); } +pub unsafe fn instr16_89_mem(addr: i32, r: i32) { + return_on_pagefault!(safe_write16(addr, read_reg16(r))); +} +pub unsafe fn instr32_89_reg(r2: i32, r: i32) { write_reg32(r2, read_reg32(r)); } +pub unsafe fn instr32_89_mem(addr: i32, r: i32) { + return_on_pagefault!(safe_write32(addr, read_reg32(r))); +} +pub unsafe fn instr_8A_mem(addr: i32, r: i32) { + write_reg8(r, return_on_pagefault!(safe_read8(addr))); +} +pub unsafe fn instr_8A_reg(r1: i32, r: i32) { write_reg8(r, read_reg8(r1)); } +pub unsafe fn instr16_8B_mem(addr: i32, r: i32) { + write_reg16(r, return_on_pagefault!(safe_read16(addr))); +} +pub unsafe fn instr16_8B_reg(r1: i32, r: i32) { write_reg16(r, read_reg16(r1)); } +pub unsafe fn instr32_8B_mem(addr: i32, r: i32) { + write_reg32(r, return_on_pagefault!(safe_read32s(addr))); +} +pub unsafe fn instr32_8B_reg(r1: i32, r: i32) { write_reg32(r, read_reg32(r1)); } + +pub unsafe fn instr_8C_check_sreg(seg: i32) -> bool { + if seg >= 6 { + dbg_log!("mov sreg #ud"); + trigger_ud(); + return false; + } + else { + return true; + }; +} +pub unsafe fn instr16_8C_reg(r: i32, seg: i32) { + if instr_8C_check_sreg(seg) { + write_reg16(r, *sreg.offset(seg as isize) as i32); + }; +} +pub unsafe fn instr16_8C_mem(addr: i32, seg: i32) { + if instr_8C_check_sreg(seg) { + return_on_pagefault!(safe_write16(addr, *sreg.offset(seg as isize) as i32)); + }; +} +pub unsafe fn instr32_8C_reg(r: i32, seg: i32) { + if instr_8C_check_sreg(seg) { + write_reg32(r, *sreg.offset(seg as isize) as i32); + }; +} +pub unsafe fn instr32_8C_mem(addr: i32, seg: i32) { + if instr_8C_check_sreg(seg) { + return_on_pagefault!(safe_write16(addr, *sreg.offset(seg as isize) as i32)); + }; +} + +pub unsafe fn instr16_8D_reg(_r: i32, _r2: i32) { + dbg_log!("lea #ud"); + trigger_ud(); +} +pub unsafe fn instr16_8D_mem(modrm_byte: i32, r: i32) { + // lea + *prefixes = (*prefixes as i32 | SEG_PREFIX_ZERO) as u8; + if let Ok(addr) = modrm_resolve(modrm_byte) { + write_reg16(r, addr); + } + *prefixes = 0; +} +pub unsafe fn instr32_8D_reg(_r: i32, _r2: i32) { + dbg_log!("lea #ud"); + trigger_ud(); +} +pub unsafe fn instr32_8D_mem(modrm_byte: i32, r: i32) { + // lea + // override prefix, so modrm_resolve does not return the segment part + *prefixes = (*prefixes as i32 | SEG_PREFIX_ZERO) as u8; + if let Ok(addr) = modrm_resolve(modrm_byte) { + write_reg32(r, addr); + } + *prefixes = 0; +} + +#[no_mangle] +pub unsafe fn instr_8E_mem(addr: i32, r: i32) { + if r == ES || r == SS || r == DS || r == FS || r == GS { + if !switch_seg(r, return_on_pagefault!(safe_read16(addr))) { + return; + } + } + else { + dbg_log!("mov sreg #ud"); + trigger_ud(); + } +} +#[no_mangle] +pub unsafe fn instr_8E_reg(r1: i32, r: i32) { + if r == ES || r == SS || r == DS || r == FS || r == GS { + switch_seg(r, read_reg16(r1)); + } + else { + dbg_log!("mov sreg #ud"); + trigger_ud(); + } +} + +pub unsafe fn instr16_8F_0_mem(modrm_byte: i32) { + // pop + // Update esp *before* resolving the address + adjust_stack_reg(2); + match modrm_resolve(modrm_byte) { + Err(()) => { + // a pagefault happened, reset esp + adjust_stack_reg(-2); + }, + Ok(addr) => { + adjust_stack_reg(-2); + let stack_value = return_on_pagefault!(safe_read16(get_stack_pointer(0))); + return_on_pagefault!(safe_write16(addr, stack_value)); + adjust_stack_reg(2); + }, + } +} +pub unsafe fn instr16_8F_0_reg(r: i32) { write_reg16(r, return_on_pagefault!(pop16())); } +pub unsafe fn instr32_8F_0_mem(modrm_byte: i32) { + // Update esp *before* resolving the address + adjust_stack_reg(4); + match modrm_resolve(modrm_byte) { + Err(()) => { + // a pagefault happened, reset esp + adjust_stack_reg(-4); + }, + Ok(addr) => { + adjust_stack_reg(-4); + let stack_value = return_on_pagefault!(safe_read32s(get_stack_pointer(0))); + return_on_pagefault!(safe_write32(addr, stack_value)); + adjust_stack_reg(4); + }, + } +} +pub unsafe fn instr32_8F_0_reg(r: i32) { write_reg32(r, return_on_pagefault!(pop32s())); } + +pub unsafe fn instr_90() {} +pub unsafe fn instr16_91() { xchg16r(CX); } +pub unsafe fn instr32_91() { xchg32r(ECX); } +pub unsafe fn instr16_92() { xchg16r(DX); } +pub unsafe fn instr32_92() { xchg32r(EDX); } +pub unsafe fn instr16_93() { xchg16r(BX); } +pub unsafe fn instr32_93() { xchg32r(EBX); } +pub unsafe fn instr16_94() { xchg16r(SP); } +pub unsafe fn instr32_94() { xchg32r(ESP); } +pub unsafe fn instr16_95() { xchg16r(BP); } +pub unsafe fn instr32_95() { xchg32r(EBP); } +pub unsafe fn instr16_96() { xchg16r(SI); } +pub unsafe fn instr32_96() { xchg32r(ESI); } +pub unsafe fn instr16_97() { xchg16r(DI); } +pub unsafe fn instr32_97() { xchg32r(EDI); } + +pub unsafe fn instr16_98() { write_reg16(AX, read_reg8(AL) << 24 >> 24); } +pub unsafe fn instr32_98() { write_reg32(EAX, read_reg16(AX) as i16 as i32); } +pub unsafe fn instr16_99() { write_reg16(DX, read_reg16(AX) as i16 as i32 >> 15); } +pub unsafe fn instr32_99() { write_reg32(EDX, read_reg32(EAX) >> 31); } + +#[no_mangle] +pub unsafe fn instr16_9A(new_ip: i32, new_cs: i32) { + // callf + far_jump(new_ip, new_cs, true, false); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +#[no_mangle] +pub unsafe fn instr32_9A(new_ip: i32, new_cs: i32) { + if !*protected_mode || vm86_mode() { + if 0 != new_ip as u32 & 0xFFFF0000 { + dbg_assert!(false); + } + } + far_jump(new_ip, new_cs, true, true); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +#[no_mangle] +pub unsafe fn instr_9B() { + // fwait: check for pending fpu exceptions + if *cr & (CR0_MP | CR0_TS) == CR0_MP | CR0_TS { + // Note: Different from task_switch_test + // Triggers when TS and MP bits are set (EM bit is ignored) + trigger_nm(); + } + else { + fwait(); + }; +} +unsafe fn instr_pushf_popf_check() -> bool { 0 != *flags & FLAG_VM && getiopl() < 3 } +pub unsafe fn instr16_9C() { + // pushf + if instr_pushf_popf_check() { + dbg_assert!(*protected_mode); + dbg_log!("pushf #gp"); + trigger_gp(0); + } + else { + return_on_pagefault!(push16(get_eflags())); + }; +} +pub unsafe fn instr32_9C() { + // pushf + if instr_pushf_popf_check() { + // trap to virtual 8086 monitor + dbg_assert!(*protected_mode); + dbg_log!("pushf #gp"); + trigger_gp(0); + } + else { + // vm and rf flag are cleared in image stored on the stack + return_on_pagefault!(push32(get_eflags() & 0xFCFFFF)); + }; +} + +pub unsafe fn instr16_9D() { + // popf + if instr_pushf_popf_check() { + dbg_log!("popf #gp"); + trigger_gp(0); + return; + } + let old_eflags = *flags; + update_eflags(*flags & !0xFFFF | return_on_pagefault!(pop16())); + if old_eflags & FLAG_INTERRUPT == 0 && *flags & FLAG_INTERRUPT != 0 { + handle_irqs(); + } +} +pub unsafe fn instr32_9D() { + // popf + if instr_pushf_popf_check() { + dbg_log!("popf #gp"); + trigger_gp(0); + return; + } + let old_eflags = *flags; + update_eflags(return_on_pagefault!(pop32s())); + if old_eflags & FLAG_INTERRUPT == 0 && *flags & FLAG_INTERRUPT != 0 { + handle_irqs(); + } +} + +pub unsafe fn instr_9E() { + // sahf + *flags = *flags & !255 | read_reg8(AH); + *flags = *flags & FLAGS_MASK | FLAGS_DEFAULT; + *flags_changed &= !255; +} +pub unsafe fn instr_9F() { + // lahf + write_reg8(AH, get_eflags()); +} + +pub unsafe fn instr_A0(moffs: i32) { + // mov + let data = return_on_pagefault!(safe_read8(return_on_pagefault!(get_seg_prefix_ds(moffs)))); + write_reg8(AL, data); +} +pub unsafe fn instr16_A1(moffs: i32) { + // mov + let data = return_on_pagefault!(safe_read16(return_on_pagefault!(get_seg_prefix_ds(moffs)))); + write_reg16(AX, data); +} +pub unsafe fn instr32_A1(moffs: i32) { + let data = return_on_pagefault!(safe_read32s(return_on_pagefault!(get_seg_prefix_ds(moffs)))); + write_reg32(EAX, data); +} +pub unsafe fn instr_A2(moffs: i32) { + // mov + return_on_pagefault!(safe_write8( + return_on_pagefault!(get_seg_prefix_ds(moffs)), + read_reg8(AL) + )); +} +pub unsafe fn instr16_A3(moffs: i32) { + // mov + return_on_pagefault!(safe_write16( + return_on_pagefault!(get_seg_prefix_ds(moffs)), + read_reg16(AX) + )); +} +pub unsafe fn instr32_A3(moffs: i32) { + return_on_pagefault!(safe_write32( + return_on_pagefault!(get_seg_prefix_ds(moffs)), + read_reg32(EAX) + )); +} + +pub unsafe fn instr_A4() { movsb_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr_F2A4() { movsb_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr_F3A4() { movsb_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } + +pub unsafe fn instr16_A5() { + movsw_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr32_A5() { + movsd_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr16_F2A5() { movsw_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr16_F3A5() { movsw_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr32_F2A5() { movsd_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr32_F3A5() { movsd_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } + +pub unsafe fn instr_A6() { cmpsb_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr_F2A6() { cmpsb_repnz(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr_F3A6() { cmpsb_repz(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr16_A7() { + cmpsw_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr32_A7() { + cmpsd_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr16_F2A7() { + cmpsw_repnz(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr16_F3A7() { + cmpsw_repz(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr32_F2A7() { + cmpsd_repnz(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr32_F3A7() { + cmpsd_repz(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} + +pub unsafe fn instr_A8(imm8: i32) { test8(read_reg8(AL), imm8); } +pub unsafe fn instr16_A9(imm16: i32) { test16(read_reg16(AX), imm16); } +pub unsafe fn instr32_A9(imm32: i32) { test32(read_reg32(EAX), imm32); } + +pub unsafe fn instr_AA() { stosb_no_rep(is_asize_32()); } +pub unsafe fn instr_F2AA() { stosb_rep(is_asize_32()); } +pub unsafe fn instr_F3AA() { stosb_rep(is_asize_32()); } + +pub unsafe fn instr16_AB() { stosw_no_rep(is_asize_32()); } +pub unsafe fn instr32_AB() { stosd_no_rep(is_asize_32()); } +pub unsafe fn instr16_F2AB() { stosw_rep(is_asize_32()); } +pub unsafe fn instr16_F3AB() { stosw_rep(is_asize_32()); } +pub unsafe fn instr32_F2AB() { stosd_rep(is_asize_32()); } +pub unsafe fn instr32_F3AB() { stosd_rep(is_asize_32()); } + +pub unsafe fn instr_AC() { lodsb_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr_F2AC() { lodsb_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr_F3AC() { lodsb_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } + +pub unsafe fn instr16_AD() { + lodsw_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr32_AD() { + lodsd_no_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); +} +pub unsafe fn instr16_F2AD() { lodsw_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr16_F3AD() { lodsw_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr32_F2AD() { lodsd_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } +pub unsafe fn instr32_F3AD() { lodsd_rep(is_asize_32(), return_on_pagefault!(get_seg_prefix(DS))); } + +pub unsafe fn instr_AE() { scasb_no_rep(is_asize_32()); } +pub unsafe fn instr_F2AE() { scasb_repnz(is_asize_32()); } +pub unsafe fn instr_F3AE() { scasb_repz(is_asize_32()); } + +pub unsafe fn instr16_AF() { scasw_no_rep(is_asize_32()); } +pub unsafe fn instr32_AF() { scasd_no_rep(is_asize_32()); } +pub unsafe fn instr16_F2AF() { scasw_repnz(is_asize_32()); } +pub unsafe fn instr16_F3AF() { scasw_repz(is_asize_32()); } +pub unsafe fn instr32_F2AF() { scasd_repnz(is_asize_32()); } +pub unsafe fn instr32_F3AF() { scasd_repz(is_asize_32()); } + +pub unsafe fn instr_B0(imm8: i32) { write_reg8(AL, imm8); } +pub unsafe fn instr_B1(imm8: i32) { write_reg8(CL, imm8); } +pub unsafe fn instr_B2(imm8: i32) { write_reg8(DL, imm8); } +pub unsafe fn instr_B3(imm8: i32) { write_reg8(BL, imm8); } +pub unsafe fn instr_B4(imm8: i32) { write_reg8(AH, imm8); } +pub unsafe fn instr_B5(imm8: i32) { write_reg8(CH, imm8); } +pub unsafe fn instr_B6(imm8: i32) { write_reg8(DH, imm8); } +pub unsafe fn instr_B7(imm8: i32) { write_reg8(BH, imm8); } +pub unsafe fn instr16_B8(imm: i32) { write_reg16(AX, imm); } +pub unsafe fn instr32_B8(imm: i32) { write_reg32(EAX, imm); } +pub unsafe fn instr16_B9(imm: i32) { write_reg16(CX, imm); } +pub unsafe fn instr32_B9(imm: i32) { write_reg32(ECX, imm); } +pub unsafe fn instr16_BA(imm: i32) { write_reg16(DX, imm); } +pub unsafe fn instr32_BA(imm: i32) { write_reg32(EDX, imm); } +pub unsafe fn instr16_BB(imm: i32) { write_reg16(BX, imm); } +pub unsafe fn instr32_BB(imm: i32) { write_reg32(EBX, imm); } +pub unsafe fn instr16_BC(imm: i32) { write_reg16(SP, imm); } +pub unsafe fn instr32_BC(imm: i32) { write_reg32(ESP, imm); } +pub unsafe fn instr16_BD(imm: i32) { write_reg16(BP, imm); } +pub unsafe fn instr32_BD(imm: i32) { write_reg32(EBP, imm); } +pub unsafe fn instr16_BE(imm: i32) { write_reg16(SI, imm); } +pub unsafe fn instr32_BE(imm: i32) { write_reg32(ESI, imm); } +pub unsafe fn instr16_BF(imm: i32) { write_reg16(DI, imm); } +pub unsafe fn instr32_BF(imm: i32) { write_reg32(EDI, imm); } + +pub unsafe fn instr_C0_0_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| rol8(x, imm & 31)) } +pub unsafe fn instr_C0_0_reg(r1: i32, imm: i32) { write_reg8(r1, rol8(read_reg8(r1), imm & 31)); } +pub unsafe fn instr_C0_1_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| ror8(x, imm & 31)) } +pub unsafe fn instr_C0_1_reg(r1: i32, imm: i32) { write_reg8(r1, ror8(read_reg8(r1), imm & 31)); } +pub unsafe fn instr_C0_2_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| rcl8(x, imm & 31)) } +pub unsafe fn instr_C0_2_reg(r1: i32, imm: i32) { write_reg8(r1, rcl8(read_reg8(r1), imm & 31)); } +pub unsafe fn instr_C0_3_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| rcr8(x, imm & 31)) } +pub unsafe fn instr_C0_3_reg(r1: i32, imm: i32) { write_reg8(r1, rcr8(read_reg8(r1), imm & 31)); } +pub unsafe fn instr_C0_4_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| shl8(x, imm & 31)) } +pub unsafe fn instr_C0_4_reg(r1: i32, imm: i32) { write_reg8(r1, shl8(read_reg8(r1), imm & 31)); } +pub unsafe fn instr_C0_5_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| shr8(x, imm & 31)) } +pub unsafe fn instr_C0_5_reg(r1: i32, imm: i32) { write_reg8(r1, shr8(read_reg8(r1), imm & 31)); } +pub unsafe fn instr_C0_6_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| shl8(x, imm & 31)) } +pub unsafe fn instr_C0_6_reg(r1: i32, imm: i32) { write_reg8(r1, shl8(read_reg8(r1), imm & 31)); } +pub unsafe fn instr_C0_7_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sar8(x, imm & 31)) } +pub unsafe fn instr_C0_7_reg(r1: i32, imm: i32) { write_reg8(r1, sar8(read_reg8(r1), imm & 31)); } +pub unsafe fn instr16_C1_0_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| rol16(x, imm & 31)) +} +pub unsafe fn instr16_C1_0_reg(r1: i32, imm: i32) { + write_reg16(r1, rol16(read_reg16(r1), imm & 31)); +} +pub unsafe fn instr16_C1_1_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| ror16(x, imm & 31)) +} +pub unsafe fn instr16_C1_1_reg(r1: i32, imm: i32) { + write_reg16(r1, ror16(read_reg16(r1), imm & 31)); +} +pub unsafe fn instr16_C1_2_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| rcl16(x, imm & 31)) +} +pub unsafe fn instr16_C1_2_reg(r1: i32, imm: i32) { + write_reg16(r1, rcl16(read_reg16(r1), imm & 31)); +} +pub unsafe fn instr16_C1_3_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| rcr16(x, imm & 31)) +} +pub unsafe fn instr16_C1_3_reg(r1: i32, imm: i32) { + write_reg16(r1, rcr16(read_reg16(r1), imm & 31)); +} +pub unsafe fn instr16_C1_4_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| shl16(x, imm & 31)) +} +pub unsafe fn instr16_C1_4_reg(r1: i32, imm: i32) { + write_reg16(r1, shl16(read_reg16(r1), imm & 31)); +} +pub unsafe fn instr16_C1_5_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| shr16(x, imm & 31)) +} +pub unsafe fn instr16_C1_5_reg(r1: i32, imm: i32) { + write_reg16(r1, shr16(read_reg16(r1), imm & 31)); +} +pub unsafe fn instr16_C1_6_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| shl16(x, imm & 31)) +} +pub unsafe fn instr16_C1_6_reg(r1: i32, imm: i32) { + write_reg16(r1, shl16(read_reg16(r1), imm & 31)); +} +pub unsafe fn instr16_C1_7_mem(addr: i32, imm: i32) { + safe_read_write16(addr, &|x| sar16(x, imm & 31)) +} +pub unsafe fn instr16_C1_7_reg(r1: i32, imm: i32) { + write_reg16(r1, sar16(read_reg16(r1), imm & 31)); +} +pub unsafe fn instr32_C1_0_mem(addr: i32, imm: i32) { + safe_read_write32(addr, &|x| rol32(x, imm & 31)) +} +pub unsafe fn instr32_C1_0_reg(r1: i32, imm: i32) { + write_reg32(r1, rol32(read_reg32(r1), imm & 31)); +} +pub unsafe fn instr32_C1_1_mem(addr: i32, imm: i32) { + safe_read_write32(addr, &|x| ror32(x, imm & 31)) +} +pub unsafe fn instr32_C1_1_reg(r1: i32, imm: i32) { + write_reg32(r1, ror32(read_reg32(r1), imm & 31)); +} +pub unsafe fn instr32_C1_2_mem(addr: i32, imm: i32) { + safe_read_write32(addr, &|x| rcl32(x, imm & 31)) +} +pub unsafe fn instr32_C1_2_reg(r1: i32, imm: i32) { + write_reg32(r1, rcl32(read_reg32(r1), imm & 31)); +} +pub unsafe fn instr32_C1_3_mem(addr: i32, imm: i32) { + safe_read_write32(addr, &|x| rcr32(x, imm & 31)) +} +pub unsafe fn instr32_C1_3_reg(r1: i32, imm: i32) { + write_reg32(r1, rcr32(read_reg32(r1), imm & 31)); +} +pub unsafe fn instr32_C1_4_mem(addr: i32, imm: i32) { + safe_read_write32(addr, &|x| shl32(x, imm & 31)) +} +pub unsafe fn instr32_C1_4_reg(r1: i32, imm: i32) { + write_reg32(r1, shl32(read_reg32(r1), imm & 31)); +} +pub unsafe fn instr32_C1_5_mem(addr: i32, imm: i32) { + safe_read_write32(addr, &|x| shr32(x, imm & 31)) +} +pub unsafe fn instr32_C1_5_reg(r1: i32, imm: i32) { + write_reg32(r1, shr32(read_reg32(r1), imm & 31)); +} +pub unsafe fn instr32_C1_6_mem(addr: i32, imm: i32) { + safe_read_write32(addr, &|x| shl32(x, imm & 31)) +} +pub unsafe fn instr32_C1_6_reg(r1: i32, imm: i32) { + write_reg32(r1, shl32(read_reg32(r1), imm & 31)); +} +pub unsafe fn instr32_C1_7_mem(addr: i32, imm: i32) { + safe_read_write32(addr, &|x| sar32(x, imm & 31)) +} +pub unsafe fn instr32_C1_7_reg(r1: i32, imm: i32) { + write_reg32(r1, sar32(read_reg32(r1), imm & 31)); +} + +pub unsafe fn instr16_C2(imm16: i32) { + // retn + let cs = get_seg_cs(); + *instruction_pointer = cs + return_on_pagefault!(pop16()); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); + adjust_stack_reg(imm16); +} +pub unsafe fn instr32_C2(imm16: i32) { + // retn + let cs = get_seg_cs(); + let ip = return_on_pagefault!(pop32s()); + dbg_assert!(*is_32 || ip < 0x10000); + *instruction_pointer = cs + ip; + adjust_stack_reg(imm16); +} +pub unsafe fn instr16_C3() { + // retn + let cs = get_seg_cs(); + *instruction_pointer = cs + return_on_pagefault!(pop16()); +} +pub unsafe fn instr32_C3() { + // retn + let cs = get_seg_cs(); + let ip = return_on_pagefault!(pop32s()); + dbg_assert!(*is_32 || ip < 0x10000); + *instruction_pointer = cs + ip; +} + +#[no_mangle] +pub unsafe fn instr16_C4_reg(_unused1: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr16_C4_mem(addr: i32, r: i32) { lss16(addr, r, ES); } +#[no_mangle] +pub unsafe fn instr32_C4_reg(_unused1: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_C4_mem(addr: i32, r: i32) { lss32(addr, r, ES); } +#[no_mangle] +pub unsafe fn instr16_C5_reg(_unused1: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr16_C5_mem(addr: i32, r: i32) { lss16(addr, r, DS); } +#[no_mangle] +pub unsafe fn instr32_C5_reg(_unused1: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_C5_mem(addr: i32, r: i32) { lss32(addr, r, DS); } + +pub unsafe fn instr_C6_0_reg(r: i32, imm: i32) { write_reg8(r, imm); } +pub unsafe fn instr_C6_0_mem(addr: i32, imm: i32) { + return_on_pagefault!(safe_write8(addr, imm)); +} +pub unsafe fn instr16_C7_0_reg(r: i32, imm: i32) { write_reg16(r, imm); } +pub unsafe fn instr16_C7_0_mem(addr: i32, imm: i32) { + return_on_pagefault!(safe_write16(addr, imm)); +} +pub unsafe fn instr32_C7_0_reg(r: i32, imm: i32) { write_reg32(r, imm); } +pub unsafe fn instr32_C7_0_mem(addr: i32, imm: i32) { + return_on_pagefault!(safe_write32(addr, imm)); +} + +#[no_mangle] +pub unsafe fn instr16_C8(size: i32, nesting: i32) { enter16(size, nesting); } +#[no_mangle] +pub unsafe fn instr32_C8(size: i32, nesting: i32) { enter32(size, nesting); } + +pub unsafe fn instr16_C9() { + // leave + let old_vbp = if *stack_size_32 { read_reg32(EBP) } else { read_reg16(BP) }; + let new_bp = return_on_pagefault!(safe_read16(get_seg_ss() + old_vbp)); + set_stack_reg(old_vbp + 2); + write_reg16(BP, new_bp); +} +pub unsafe fn instr32_C9() { + let old_vbp = if *stack_size_32 { read_reg32(EBP) } else { read_reg16(BP) }; + let new_ebp = return_on_pagefault!(safe_read32s(get_seg_ss() + old_vbp)); + set_stack_reg(old_vbp + 4); + write_reg32(EBP, new_ebp); +} +#[no_mangle] +pub unsafe fn instr16_CA(imm16: i32) { + // retf + let ip = return_on_pagefault!(safe_read16(get_stack_pointer(0))); + let cs = return_on_pagefault!(safe_read16(get_stack_pointer(2))); + far_return(ip, cs, imm16, false); +} +#[no_mangle] +pub unsafe fn instr32_CA(imm16: i32) { + // retf + let ip = return_on_pagefault!(safe_read32s(get_stack_pointer(0))); + let cs = return_on_pagefault!(safe_read32s(get_stack_pointer(4))) & 0xFFFF; + far_return(ip, cs, imm16, true); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +#[no_mangle] +pub unsafe fn instr16_CB() { + // retf + let ip = return_on_pagefault!(safe_read16(get_stack_pointer(0))); + let cs = return_on_pagefault!(safe_read16(get_stack_pointer(2))); + far_return(ip, cs, 0, false); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +#[no_mangle] +pub unsafe fn instr32_CB() { + // retf + let ip = return_on_pagefault!(safe_read32s(get_stack_pointer(0))); + let cs = return_on_pagefault!(safe_read32s(get_stack_pointer(4))) & 0xFFFF; + far_return(ip, cs, 0, true); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +#[no_mangle] +pub unsafe fn instr_CC() { + // INT3 + // TODO: inhibit iopl checks + dbg_log!("INT3"); + call_interrupt_vector(3, true, None); +} +#[no_mangle] +pub unsafe fn instr_CD(imm8: i32) { + // INT + call_interrupt_vector(imm8, true, None); +} +#[no_mangle] +pub unsafe fn instr_CE() { + // INTO + dbg_log!("INTO"); + if getof() { + // TODO: inhibit iopl checks + call_interrupt_vector(CPU_EXCEPTION_OF, true, None); + }; +} +#[no_mangle] +pub unsafe fn instr16_CF() { + // iret + iret16(); +} +#[no_mangle] +pub unsafe fn instr32_CF() { iret32(); } + +pub unsafe fn instr_D0_0_mem(addr: i32) { safe_read_write8(addr, &|x| rol8(x, 1)) } +pub unsafe fn instr_D0_0_reg(r1: i32) { write_reg8(r1, rol8(read_reg8(r1), 1)); } +pub unsafe fn instr_D0_1_mem(addr: i32) { safe_read_write8(addr, &|x| ror8(x, 1)) } +pub unsafe fn instr_D0_1_reg(r1: i32) { write_reg8(r1, ror8(read_reg8(r1), 1)); } +pub unsafe fn instr_D0_2_mem(addr: i32) { safe_read_write8(addr, &|x| rcl8(x, 1)) } +pub unsafe fn instr_D0_2_reg(r1: i32) { write_reg8(r1, rcl8(read_reg8(r1), 1)); } +pub unsafe fn instr_D0_3_mem(addr: i32) { safe_read_write8(addr, &|x| rcr8(x, 1)) } +pub unsafe fn instr_D0_3_reg(r1: i32) { write_reg8(r1, rcr8(read_reg8(r1), 1)); } +pub unsafe fn instr_D0_4_mem(addr: i32) { safe_read_write8(addr, &|x| shl8(x, 1)) } +pub unsafe fn instr_D0_4_reg(r1: i32) { write_reg8(r1, shl8(read_reg8(r1), 1)); } +pub unsafe fn instr_D0_5_mem(addr: i32) { safe_read_write8(addr, &|x| shr8(x, 1)) } +pub unsafe fn instr_D0_5_reg(r1: i32) { write_reg8(r1, shr8(read_reg8(r1), 1)); } +pub unsafe fn instr_D0_6_mem(addr: i32) { safe_read_write8(addr, &|x| shl8(x, 1)) } +pub unsafe fn instr_D0_6_reg(r1: i32) { write_reg8(r1, shl8(read_reg8(r1), 1)); } +pub unsafe fn instr_D0_7_mem(addr: i32) { safe_read_write8(addr, &|x| sar8(x, 1)) } +pub unsafe fn instr_D0_7_reg(r1: i32) { write_reg8(r1, sar8(read_reg8(r1), 1)); } +pub unsafe fn instr16_D1_0_mem(addr: i32) { safe_read_write16(addr, &|x| rol16(x, 1)) } +pub unsafe fn instr16_D1_0_reg(r1: i32) { write_reg16(r1, rol16(read_reg16(r1), 1)); } +pub unsafe fn instr16_D1_1_mem(addr: i32) { safe_read_write16(addr, &|x| ror16(x, 1)) } +pub unsafe fn instr16_D1_1_reg(r1: i32) { write_reg16(r1, ror16(read_reg16(r1), 1)); } +pub unsafe fn instr16_D1_2_mem(addr: i32) { safe_read_write16(addr, &|x| rcl16(x, 1)) } +pub unsafe fn instr16_D1_2_reg(r1: i32) { write_reg16(r1, rcl16(read_reg16(r1), 1)); } +pub unsafe fn instr16_D1_3_mem(addr: i32) { safe_read_write16(addr, &|x| rcr16(x, 1)) } +pub unsafe fn instr16_D1_3_reg(r1: i32) { write_reg16(r1, rcr16(read_reg16(r1), 1)); } +pub unsafe fn instr16_D1_4_mem(addr: i32) { safe_read_write16(addr, &|x| shl16(x, 1)) } +pub unsafe fn instr16_D1_4_reg(r1: i32) { write_reg16(r1, shl16(read_reg16(r1), 1)); } +pub unsafe fn instr16_D1_5_mem(addr: i32) { safe_read_write16(addr, &|x| shr16(x, 1)) } +pub unsafe fn instr16_D1_5_reg(r1: i32) { write_reg16(r1, shr16(read_reg16(r1), 1)); } +pub unsafe fn instr16_D1_6_mem(addr: i32) { safe_read_write16(addr, &|x| shl16(x, 1)) } +pub unsafe fn instr16_D1_6_reg(r1: i32) { write_reg16(r1, shl16(read_reg16(r1), 1)); } +pub unsafe fn instr16_D1_7_mem(addr: i32) { safe_read_write16(addr, &|x| sar16(x, 1)) } +pub unsafe fn instr16_D1_7_reg(r1: i32) { write_reg16(r1, sar16(read_reg16(r1), 1)); } +pub unsafe fn instr32_D1_0_mem(addr: i32) { safe_read_write32(addr, &|x| rol32(x, 1)) } +pub unsafe fn instr32_D1_0_reg(r1: i32) { write_reg32(r1, rol32(read_reg32(r1), 1)); } +pub unsafe fn instr32_D1_1_mem(addr: i32) { safe_read_write32(addr, &|x| ror32(x, 1)) } +pub unsafe fn instr32_D1_1_reg(r1: i32) { write_reg32(r1, ror32(read_reg32(r1), 1)); } +pub unsafe fn instr32_D1_2_mem(addr: i32) { safe_read_write32(addr, &|x| rcl32(x, 1)) } +pub unsafe fn instr32_D1_2_reg(r1: i32) { write_reg32(r1, rcl32(read_reg32(r1), 1)); } +pub unsafe fn instr32_D1_3_mem(addr: i32) { safe_read_write32(addr, &|x| rcr32(x, 1)) } +pub unsafe fn instr32_D1_3_reg(r1: i32) { write_reg32(r1, rcr32(read_reg32(r1), 1)); } +pub unsafe fn instr32_D1_4_mem(addr: i32) { safe_read_write32(addr, &|x| shl32(x, 1)) } +pub unsafe fn instr32_D1_4_reg(r1: i32) { write_reg32(r1, shl32(read_reg32(r1), 1)); } +pub unsafe fn instr32_D1_5_mem(addr: i32) { safe_read_write32(addr, &|x| shr32(x, 1)) } +pub unsafe fn instr32_D1_5_reg(r1: i32) { write_reg32(r1, shr32(read_reg32(r1), 1)); } +pub unsafe fn instr32_D1_6_mem(addr: i32) { safe_read_write32(addr, &|x| shl32(x, 1)) } +pub unsafe fn instr32_D1_6_reg(r1: i32) { write_reg32(r1, shl32(read_reg32(r1), 1)); } +pub unsafe fn instr32_D1_7_mem(addr: i32) { safe_read_write32(addr, &|x| sar32(x, 1)) } +pub unsafe fn instr32_D1_7_reg(r1: i32) { write_reg32(r1, sar32(read_reg32(r1), 1)); } +pub unsafe fn instr_D2_0_mem(addr: i32) { safe_read_write8(addr, &|x| rol8(x, read_reg8(CL) & 31)) } +pub unsafe fn instr_D2_0_reg(r1: i32) { write_reg8(r1, rol8(read_reg8(r1), read_reg8(CL) & 31)); } +pub unsafe fn instr_D2_1_mem(addr: i32) { safe_read_write8(addr, &|x| ror8(x, read_reg8(CL) & 31)) } +pub unsafe fn instr_D2_1_reg(r1: i32) { write_reg8(r1, ror8(read_reg8(r1), read_reg8(CL) & 31)); } +pub unsafe fn instr_D2_2_mem(addr: i32) { safe_read_write8(addr, &|x| rcl8(x, read_reg8(CL) & 31)) } +pub unsafe fn instr_D2_2_reg(r1: i32) { write_reg8(r1, rcl8(read_reg8(r1), read_reg8(CL) & 31)); } +pub unsafe fn instr_D2_3_mem(addr: i32) { safe_read_write8(addr, &|x| rcr8(x, read_reg8(CL) & 31)) } +pub unsafe fn instr_D2_3_reg(r1: i32) { write_reg8(r1, rcr8(read_reg8(r1), read_reg8(CL) & 31)); } +pub unsafe fn instr_D2_4_mem(addr: i32) { safe_read_write8(addr, &|x| shl8(x, read_reg8(CL) & 31)) } +pub unsafe fn instr_D2_4_reg(r1: i32) { write_reg8(r1, shl8(read_reg8(r1), read_reg8(CL) & 31)); } +pub unsafe fn instr_D2_5_mem(addr: i32) { safe_read_write8(addr, &|x| shr8(x, read_reg8(CL) & 31)) } +pub unsafe fn instr_D2_5_reg(r1: i32) { write_reg8(r1, shr8(read_reg8(r1), read_reg8(CL) & 31)); } +pub unsafe fn instr_D2_6_mem(addr: i32) { safe_read_write8(addr, &|x| shl8(x, read_reg8(CL) & 31)) } +pub unsafe fn instr_D2_6_reg(r1: i32) { write_reg8(r1, shl8(read_reg8(r1), read_reg8(CL) & 31)); } +pub unsafe fn instr_D2_7_mem(addr: i32) { safe_read_write8(addr, &|x| sar8(x, read_reg8(CL) & 31)) } +pub unsafe fn instr_D2_7_reg(r1: i32) { write_reg8(r1, sar8(read_reg8(r1), read_reg8(CL) & 31)); } +pub unsafe fn instr16_D3_0_mem(addr: i32) { + safe_read_write16(addr, &|x| rol16(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr16_D3_0_reg(r1: i32) { + write_reg16(r1, rol16(read_reg16(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr16_D3_1_mem(addr: i32) { + safe_read_write16(addr, &|x| ror16(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr16_D3_1_reg(r1: i32) { + write_reg16(r1, ror16(read_reg16(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr16_D3_2_mem(addr: i32) { + safe_read_write16(addr, &|x| rcl16(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr16_D3_2_reg(r1: i32) { + write_reg16(r1, rcl16(read_reg16(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr16_D3_3_mem(addr: i32) { + safe_read_write16(addr, &|x| rcr16(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr16_D3_3_reg(r1: i32) { + write_reg16(r1, rcr16(read_reg16(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr16_D3_4_mem(addr: i32) { + safe_read_write16(addr, &|x| shl16(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr16_D3_4_reg(r1: i32) { + write_reg16(r1, shl16(read_reg16(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr16_D3_5_mem(addr: i32) { + safe_read_write16(addr, &|x| shr16(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr16_D3_5_reg(r1: i32) { + write_reg16(r1, shr16(read_reg16(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr16_D3_6_mem(addr: i32) { + safe_read_write16(addr, &|x| shl16(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr16_D3_6_reg(r1: i32) { + write_reg16(r1, shl16(read_reg16(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr16_D3_7_mem(addr: i32) { + safe_read_write16(addr, &|x| sar16(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr16_D3_7_reg(r1: i32) { + write_reg16(r1, sar16(read_reg16(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr32_D3_0_mem(addr: i32) { + safe_read_write32(addr, &|x| rol32(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr32_D3_0_reg(r1: i32) { + write_reg32(r1, rol32(read_reg32(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr32_D3_1_mem(addr: i32) { + safe_read_write32(addr, &|x| ror32(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr32_D3_1_reg(r1: i32) { + write_reg32(r1, ror32(read_reg32(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr32_D3_2_mem(addr: i32) { + safe_read_write32(addr, &|x| rcl32(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr32_D3_2_reg(r1: i32) { + write_reg32(r1, rcl32(read_reg32(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr32_D3_3_mem(addr: i32) { + safe_read_write32(addr, &|x| rcr32(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr32_D3_3_reg(r1: i32) { + write_reg32(r1, rcr32(read_reg32(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr32_D3_4_mem(addr: i32) { + safe_read_write32(addr, &|x| shl32(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr32_D3_4_reg(r1: i32) { + write_reg32(r1, shl32(read_reg32(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr32_D3_5_mem(addr: i32) { + safe_read_write32(addr, &|x| shr32(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr32_D3_5_reg(r1: i32) { + write_reg32(r1, shr32(read_reg32(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr32_D3_6_mem(addr: i32) { + safe_read_write32(addr, &|x| shl32(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr32_D3_6_reg(r1: i32) { + write_reg32(r1, shl32(read_reg32(r1), read_reg8(CL) & 31)); +} +pub unsafe fn instr32_D3_7_mem(addr: i32) { + safe_read_write32(addr, &|x| sar32(x, read_reg8(CL) & 31)) +} +pub unsafe fn instr32_D3_7_reg(r1: i32) { + write_reg32(r1, sar32(read_reg32(r1), read_reg8(CL) & 31)); +} + +#[no_mangle] +pub unsafe fn instr_D4(arg: i32) { bcd_aam(arg); } +#[no_mangle] +pub unsafe fn instr_D5(arg: i32) { bcd_aad(arg); } +#[no_mangle] +pub unsafe fn instr_D6() { + // salc + write_reg8(AL, -(getcf() as i32)); +} +pub unsafe fn instr_D7() { + // xlat + dbg_assert!(!in_jit); + if is_asize_32() { + write_reg8( + AL, + return_on_pagefault!(safe_read8( + return_on_pagefault!(get_seg_prefix(DS)) + read_reg32(EBX) + read_reg8(AL), + )), + ) + } + else { + write_reg8( + AL, + return_on_pagefault!(safe_read8( + return_on_pagefault!(get_seg_prefix(DS)) + + (read_reg16(BX) + read_reg8(AL) & 0xFFFF), + )), + ) + }; +} + +pub unsafe fn instr_D8_0_mem(addr: i32) { fpu_fadd(0, return_on_pagefault!(fpu_load_m32(addr))); } +pub unsafe fn instr_D8_0_reg(r: i32) { fpu_fadd(0, fpu_get_sti(r)); } +pub unsafe fn instr_D8_1_mem(addr: i32) { fpu_fmul(0, return_on_pagefault!(fpu_load_m32(addr))); } +pub unsafe fn instr_D8_1_reg(r: i32) { fpu_fmul(0, fpu_get_sti(r)); } +pub unsafe fn instr_D8_2_mem(addr: i32) { fpu_fcom(return_on_pagefault!(fpu_load_m32(addr))); } +pub unsafe fn instr_D8_2_reg(r: i32) { fpu_fcom(fpu_get_sti(r)); } +pub unsafe fn instr_D8_3_mem(addr: i32) { fpu_fcomp(return_on_pagefault!(fpu_load_m32(addr))); } +pub unsafe fn instr_D8_3_reg(r: i32) { fpu_fcomp(fpu_get_sti(r)); } +pub unsafe fn instr_D8_4_mem(addr: i32) { fpu_fsub(0, return_on_pagefault!(fpu_load_m32(addr))); } +pub unsafe fn instr_D8_4_reg(r: i32) { fpu_fsub(0, fpu_get_sti(r)); } +pub unsafe fn instr_D8_5_mem(addr: i32) { fpu_fsubr(0, return_on_pagefault!(fpu_load_m32(addr))); } +pub unsafe fn instr_D8_5_reg(r: i32) { fpu_fsubr(0, fpu_get_sti(r)); } +pub unsafe fn instr_D8_6_mem(addr: i32) { fpu_fdiv(0, return_on_pagefault!(fpu_load_m32(addr))); } +pub unsafe fn instr_D8_6_reg(r: i32) { fpu_fdiv(0, fpu_get_sti(r)); } +pub unsafe fn instr_D8_7_mem(addr: i32) { fpu_fdivr(0, return_on_pagefault!(fpu_load_m32(addr))); } +pub unsafe fn instr_D8_7_reg(r: i32) { fpu_fdivr(0, fpu_get_sti(r)); } + +pub unsafe fn instr16_D9_0_mem(addr: i32) { fpu_fldm32(addr); } +pub unsafe fn instr16_D9_0_reg(r: i32) { fpu_push(fpu_get_sti(r)); } +pub unsafe fn instr16_D9_1_mem(_addr: i32) { + dbg_log!("d9/1"); + trigger_ud(); +} +pub unsafe fn instr16_D9_1_reg(r: i32) { fpu_fxch(r); } +pub unsafe fn instr16_D9_2_mem(addr: i32) { fpu_fstm32(addr); } +pub unsafe fn instr16_D9_2_reg(r: i32) { + if r != 0 { + trigger_ud(); + }; +} +pub unsafe fn instr16_D9_3_mem(addr: i32) { fpu_fstm32p(addr); } +pub unsafe fn instr16_D9_3_reg(r: i32) { fpu_fstp(r) } +#[no_mangle] +pub unsafe fn instr16_D9_4_mem(addr: i32) { fpu_fldenv16(addr); } +pub unsafe fn instr32_D9_4_mem(addr: i32) { fpu_fldenv32(addr); } +#[no_mangle] +pub unsafe fn instr16_D9_4_reg(r: i32) { + match r { + 0 => fpu_fchs(), + 1 => fpu_fabs(), + 4 => fpu_ftst(), + 5 => fpu_fxam(), + _ => { + dbg_log!("{:x}", r); + trigger_ud(); + }, + }; +} +#[no_mangle] +pub unsafe fn instr16_D9_5_mem(addr: i32) { fpu_fldcw(addr); } +#[no_mangle] +pub unsafe fn instr16_D9_5_reg(r: i32) { + // fld1/fldl2t/fldl2e/fldpi/fldlg2/fldln2/fldz + match r { + 0 => fpu_push(F80::ONE), + 1 => fpu_push(F80::LN_10 / F80::LN_2), + 2 => fpu_push(F80::LOG2_E), + 3 => fpu_push(F80::PI), + 4 => fpu_push(F80::LN_2 / F80::LN_10), + 5 => fpu_push(F80::LN_2), + 6 => fpu_push(F80::ZERO), + 7 => { + dbg_log!("d9/5/7"); + trigger_ud(); + }, + _ => {}, + }; +} +pub unsafe fn instr16_D9_6_mem(addr: i32) { fpu_fstenv16(addr); } +pub unsafe fn instr32_D9_6_mem(addr: i32) { fpu_fstenv32(addr); } +#[no_mangle] +pub unsafe fn instr16_D9_6_reg(r: i32) { + match r { + 0 => fpu_f2xm1(), + 1 => fpu_fyl2x(), + 2 => fpu_fptan(), + 3 => fpu_fpatan(), + 4 => fpu_fxtract(), + 5 => fpu_fprem(true), // fprem1 + 6 => fpu_fdecstp(), + 7 => fpu_fincstp(), + _ => { + dbg_assert!(false); + }, + }; +} +pub unsafe fn instr16_D9_7_mem(addr: i32) { fpu_fstcw(addr); } +#[no_mangle] +pub unsafe fn instr16_D9_7_reg(r: i32) { + match r { + 0 => fpu_fprem(false), + 1 => fpu_fyl2xp1(), + 2 => fpu_fsqrt(), + 3 => fpu_fsincos(), + 4 => fpu_frndint(), + 5 => fpu_fscale(), + 6 => fpu_fsin(), + 7 => fpu_fcos(), + _ => { + dbg_assert!(false); + }, + }; +} + +pub unsafe fn instr32_D9_0_reg(r: i32) { instr16_D9_0_reg(r) } +pub unsafe fn instr32_D9_1_reg(r: i32) { instr16_D9_1_reg(r) } +pub unsafe fn instr32_D9_2_reg(r: i32) { instr16_D9_2_reg(r) } +pub unsafe fn instr32_D9_3_reg(r: i32) { instr16_D9_3_reg(r) } +pub unsafe fn instr32_D9_4_reg(r: i32) { instr16_D9_4_reg(r) } +pub unsafe fn instr32_D9_5_reg(r: i32) { instr16_D9_5_reg(r) } +pub unsafe fn instr32_D9_6_reg(r: i32) { instr16_D9_6_reg(r) } +pub unsafe fn instr32_D9_7_reg(r: i32) { instr16_D9_7_reg(r) } + +pub unsafe fn instr32_D9_0_mem(r: i32) { instr16_D9_0_mem(r) } +pub unsafe fn instr32_D9_1_mem(r: i32) { instr16_D9_1_mem(r) } +pub unsafe fn instr32_D9_2_mem(r: i32) { instr16_D9_2_mem(r) } +pub unsafe fn instr32_D9_3_mem(r: i32) { instr16_D9_3_mem(r) } +pub unsafe fn instr32_D9_5_mem(r: i32) { instr16_D9_5_mem(r) } +pub unsafe fn instr32_D9_7_mem(r: i32) { instr16_D9_7_mem(r) } + +pub unsafe fn instr_DA_0_mem(addr: i32) { fpu_fadd(0, return_on_pagefault!(fpu_load_i32(addr))); } +pub unsafe fn instr_DA_1_mem(addr: i32) { fpu_fmul(0, return_on_pagefault!(fpu_load_i32(addr))); } +pub unsafe fn instr_DA_2_mem(addr: i32) { fpu_fcom(return_on_pagefault!(fpu_load_i32(addr))); } +pub unsafe fn instr_DA_3_mem(addr: i32) { fpu_fcomp(return_on_pagefault!(fpu_load_i32(addr))); } +pub unsafe fn instr_DA_4_mem(addr: i32) { fpu_fsub(0, return_on_pagefault!(fpu_load_i32(addr))); } +pub unsafe fn instr_DA_5_mem(addr: i32) { fpu_fsubr(0, return_on_pagefault!(fpu_load_i32(addr))); } +pub unsafe fn instr_DA_6_mem(addr: i32) { fpu_fdiv(0, return_on_pagefault!(fpu_load_i32(addr))); } +pub unsafe fn instr_DA_7_mem(addr: i32) { fpu_fdivr(0, return_on_pagefault!(fpu_load_i32(addr))); } +#[no_mangle] +pub unsafe fn instr_DA_0_reg(r: i32) { fpu_fcmovcc(test_b(), r); } +#[no_mangle] +pub unsafe fn instr_DA_1_reg(r: i32) { fpu_fcmovcc(test_z(), r); } +#[no_mangle] +pub unsafe fn instr_DA_2_reg(r: i32) { fpu_fcmovcc(test_be(), r); } +#[no_mangle] +pub unsafe fn instr_DA_3_reg(r: i32) { fpu_fcmovcc(test_p(), r); } +pub unsafe fn instr_DA_4_reg(_r: i32) { trigger_ud(); } +pub unsafe fn instr_DA_5_reg(r: i32) { + if r == 1 { + fpu_fucompp(); + } + else { + trigger_ud(); + }; +} +pub unsafe fn instr_DA_6_reg(_r: i32) { trigger_ud(); } +pub unsafe fn instr_DA_7_reg(_r: i32) { trigger_ud(); } + +pub unsafe fn instr_DB_0_mem(addr: i32) { fpu_fildm32(addr); } +#[no_mangle] +pub unsafe fn instr_DB_1_mem(_addr: i32) { + dbg_log!("fisttp"); + fpu_unimpl(); +} +pub unsafe fn instr_DB_2_mem(addr: i32) { fpu_fistm32(addr); } +pub unsafe fn instr_DB_3_mem(addr: i32) { fpu_fistm32p(addr); } +#[no_mangle] +pub unsafe fn instr_DB_4_mem(_addr: i32) { trigger_ud(); } +pub unsafe fn instr_DB_5_mem(addr: i32) { fpu_fldm80(addr); } +pub unsafe fn instr_DB_6_mem(_addr: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_DB_7_mem(addr: i32) { fpu_fst80p(addr); } +#[no_mangle] +pub unsafe fn instr_DB_0_reg(r: i32) { fpu_fcmovcc(!test_b(), r); } +#[no_mangle] +pub unsafe fn instr_DB_1_reg(r: i32) { fpu_fcmovcc(!test_z(), r); } +#[no_mangle] +pub unsafe fn instr_DB_2_reg(r: i32) { fpu_fcmovcc(!test_be(), r); } +#[no_mangle] +pub unsafe fn instr_DB_3_reg(r: i32) { fpu_fcmovcc(!test_p(), r); } +#[no_mangle] +pub unsafe fn instr_DB_4_reg(r: i32) { + if r == 3 { + fpu_finit(); + } + else if r == 4 || r == 1 || r == 0 { + // fsetpm, fdisi, fneni; treated as nop + } + else if r == 2 { + fpu_fclex(); + } + else { + trigger_ud(); + }; +} +pub unsafe fn instr_DB_5_reg(r: i32) { fpu_fucomi(r); } +pub unsafe fn instr_DB_6_reg(r: i32) { fpu_fcomi(r); } +#[no_mangle] +pub unsafe fn instr_DB_7_reg(_r: i32) { trigger_ud(); } + +pub unsafe fn instr_DC_0_mem(addr: i32) { fpu_fadd(0, return_on_pagefault!(fpu_load_m64(addr))); } +pub unsafe fn instr_DC_1_mem(addr: i32) { fpu_fmul(0, return_on_pagefault!(fpu_load_m64(addr))); } +pub unsafe fn instr_DC_2_mem(addr: i32) { fpu_fcom(return_on_pagefault!(fpu_load_m64(addr))); } +pub unsafe fn instr_DC_3_mem(addr: i32) { fpu_fcomp(return_on_pagefault!(fpu_load_m64(addr))); } +pub unsafe fn instr_DC_4_mem(addr: i32) { fpu_fsub(0, return_on_pagefault!(fpu_load_m64(addr))); } +pub unsafe fn instr_DC_5_mem(addr: i32) { fpu_fsubr(0, return_on_pagefault!(fpu_load_m64(addr))); } +pub unsafe fn instr_DC_6_mem(addr: i32) { fpu_fdiv(0, return_on_pagefault!(fpu_load_m64(addr))); } +pub unsafe fn instr_DC_7_mem(addr: i32) { fpu_fdivr(0, return_on_pagefault!(fpu_load_m64(addr))); } +pub unsafe fn instr_DC_0_reg(r: i32) { fpu_fadd(r, fpu_get_sti(r)); } +pub unsafe fn instr_DC_1_reg(r: i32) { fpu_fmul(r, fpu_get_sti(r)); } +pub unsafe fn instr_DC_2_reg(r: i32) { fpu_fcom(fpu_get_sti(r)); } +pub unsafe fn instr_DC_3_reg(r: i32) { fpu_fcomp(fpu_get_sti(r)); } +pub unsafe fn instr_DC_4_reg(r: i32) { fpu_fsub(r, fpu_get_sti(r)); } +pub unsafe fn instr_DC_5_reg(r: i32) { fpu_fsubr(r, fpu_get_sti(r)); } +pub unsafe fn instr_DC_6_reg(r: i32) { fpu_fdiv(r, fpu_get_sti(r)); } +pub unsafe fn instr_DC_7_reg(r: i32) { fpu_fdivr(r, fpu_get_sti(r)); } + +pub unsafe fn instr16_DD_0_mem(addr: i32) { fpu_fldm64(addr); } +#[no_mangle] +pub unsafe fn instr16_DD_1_mem(_addr: i32) { + dbg_log!("fisttp"); + fpu_unimpl(); +} +pub unsafe fn instr16_DD_2_mem(addr: i32) { fpu_fstm64(addr); } +pub unsafe fn instr16_DD_3_mem(addr: i32) { fpu_fstm64p(addr); } +#[no_mangle] +pub unsafe fn instr16_DD_4_mem(addr: i32) { fpu_frstor16(addr); } +#[no_mangle] +pub unsafe fn instr32_DD_4_mem(addr: i32) { fpu_frstor32(addr); } +pub unsafe fn instr16_DD_5_mem(_addr: i32) { + dbg_log!("dd/5"); + trigger_ud(); +} +#[no_mangle] +pub unsafe fn instr16_DD_6_mem(addr: i32) { fpu_fsave16(addr); } +#[no_mangle] +pub unsafe fn instr32_DD_6_mem(addr: i32) { fpu_fsave32(addr); } +#[no_mangle] +pub unsafe fn instr16_DD_7_mem(addr: i32) { fpu_fnstsw_mem(addr); } +pub unsafe fn instr16_DD_0_reg(r: i32) { fpu_ffree(r); } +#[no_mangle] +pub unsafe fn instr16_DD_1_reg(r: i32) { fpu_fxch(r) } +pub unsafe fn instr16_DD_2_reg(r: i32) { fpu_fst(r); } +pub unsafe fn instr16_DD_3_reg(r: i32) { fpu_fstp(r); } +#[no_mangle] +pub unsafe fn instr16_DD_4_reg(r: i32) { fpu_fucom(r); } +pub unsafe fn instr16_DD_5_reg(r: i32) { fpu_fucomp(r); } +#[no_mangle] +pub unsafe fn instr16_DD_6_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr16_DD_7_reg(_r: i32) { trigger_ud(); } + +pub unsafe fn instr32_DD_0_reg(r: i32) { instr16_DD_0_reg(r) } +#[no_mangle] +pub unsafe fn instr32_DD_1_reg(r: i32) { instr16_DD_1_reg(r) } +pub unsafe fn instr32_DD_2_reg(r: i32) { instr16_DD_2_reg(r) } +pub unsafe fn instr32_DD_3_reg(r: i32) { instr16_DD_3_reg(r) } +#[no_mangle] +pub unsafe fn instr32_DD_4_reg(r: i32) { instr16_DD_4_reg(r) } +pub unsafe fn instr32_DD_5_reg(r: i32) { instr16_DD_5_reg(r) } +#[no_mangle] +pub unsafe fn instr32_DD_6_reg(r: i32) { instr16_DD_6_reg(r) } +#[no_mangle] +pub unsafe fn instr32_DD_7_reg(r: i32) { instr16_DD_7_reg(r) } + +pub unsafe fn instr32_DD_0_mem(r: i32) { instr16_DD_0_mem(r) } +#[no_mangle] +pub unsafe fn instr32_DD_1_mem(r: i32) { instr16_DD_1_mem(r) } +pub unsafe fn instr32_DD_2_mem(r: i32) { instr16_DD_2_mem(r) } +pub unsafe fn instr32_DD_3_mem(r: i32) { instr16_DD_3_mem(r) } +pub unsafe fn instr32_DD_5_mem(r: i32) { instr16_DD_5_mem(r) } +#[no_mangle] +pub unsafe fn instr32_DD_7_mem(r: i32) { instr16_DD_7_mem(r) } + +#[no_mangle] +pub unsafe fn instr_DE_0_mem(addr: i32) { fpu_fadd(0, return_on_pagefault!(fpu_load_i16(addr))); } +#[no_mangle] +pub unsafe fn instr_DE_1_mem(addr: i32) { fpu_fmul(0, return_on_pagefault!(fpu_load_i16(addr))); } +#[no_mangle] +pub unsafe fn instr_DE_2_mem(addr: i32) { fpu_fcom(return_on_pagefault!(fpu_load_i16(addr))); } +#[no_mangle] +pub unsafe fn instr_DE_3_mem(addr: i32) { fpu_fcomp(return_on_pagefault!(fpu_load_i16(addr))); } +#[no_mangle] +pub unsafe fn instr_DE_4_mem(addr: i32) { fpu_fsub(0, return_on_pagefault!(fpu_load_i16(addr))); } +#[no_mangle] +pub unsafe fn instr_DE_5_mem(addr: i32) { fpu_fsubr(0, return_on_pagefault!(fpu_load_i16(addr))); } +#[no_mangle] +pub unsafe fn instr_DE_6_mem(addr: i32) { fpu_fdiv(0, return_on_pagefault!(fpu_load_i16(addr))); } +#[no_mangle] +pub unsafe fn instr_DE_7_mem(addr: i32) { fpu_fdivr(0, return_on_pagefault!(fpu_load_i16(addr))); } + +#[no_mangle] +pub unsafe fn instr_DE_0_reg(r: i32) { + fpu_fadd(r, fpu_get_sti(r)); + fpu_pop(); +} +pub unsafe fn instr_DE_1_reg(r: i32) { + fpu_fmul(r, fpu_get_sti(r)); + fpu_pop(); +} +pub unsafe fn instr_DE_2_reg(r: i32) { + fpu_fcom(fpu_get_sti(r)); + fpu_pop(); +} +pub unsafe fn instr_DE_3_reg(r: i32) { + if r == 1 { + fpu_fcomp(fpu_get_sti(r)); + fpu_pop(); + } + else { + trigger_ud(); + } +} +pub unsafe fn instr_DE_4_reg(r: i32) { + fpu_fsub(r, fpu_get_sti(r)); + fpu_pop(); +} +pub unsafe fn instr_DE_5_reg(r: i32) { + fpu_fsubr(r, fpu_get_sti(r)); + fpu_pop(); +} +pub unsafe fn instr_DE_6_reg(r: i32) { + fpu_fdiv(r, fpu_get_sti(r)); + fpu_pop(); +} +pub unsafe fn instr_DE_7_reg(r: i32) { + fpu_fdivr(r, fpu_get_sti(r)); + fpu_pop(); +} + +#[no_mangle] +pub unsafe fn instr_DF_0_mem(addr: i32) { fpu_fildm16(addr) } +#[no_mangle] +pub unsafe fn instr_DF_1_mem(_addr: i32) { + dbg_log!("fisttp"); + fpu_unimpl(); +} +pub unsafe fn instr_DF_2_mem(addr: i32) { fpu_fistm16(addr); } +pub unsafe fn instr_DF_3_mem(addr: i32) { fpu_fistm16p(addr); } +pub unsafe fn instr_DF_4_mem(_addr: i32) { + dbg_log!("fbld"); + fpu_unimpl(); +} +pub unsafe fn instr_DF_5_mem(addr: i32) { fpu_fildm64(addr); } +pub unsafe fn instr_DF_6_mem(addr: i32) { fpu_fbstp(addr); } +pub unsafe fn instr_DF_7_mem(addr: i32) { fpu_fistm64p(addr); } + +#[no_mangle] +pub unsafe fn instr_DF_0_reg(r: i32) { + fpu_ffree(r); + fpu_pop(); +} +#[no_mangle] +pub unsafe fn instr_DF_1_reg(r: i32) { fpu_fxch(r) } +pub unsafe fn instr_DF_2_reg(r: i32) { fpu_fstp(r); } +pub unsafe fn instr_DF_3_reg(r: i32) { fpu_fstp(r); } +pub unsafe fn instr_DF_4_reg(r: i32) { + if r == 0 { + fpu_fnstsw_reg(); + } + else { + trigger_ud(); + }; +} +pub unsafe fn instr_DF_5_reg(r: i32) { fpu_fucomip(r); } +pub unsafe fn instr_DF_6_reg(r: i32) { fpu_fcomip(r); } +pub unsafe fn instr_DF_7_reg(_r: i32) { trigger_ud(); } + +pub unsafe fn instr16_E0(imm8s: i32) { loopne16(imm8s); } +pub unsafe fn instr16_E1(imm8s: i32) { loope16(imm8s); } +pub unsafe fn instr16_E2(imm8s: i32) { loop16(imm8s); } +pub unsafe fn instr16_E3(imm8s: i32) { jcxz16(imm8s); } +pub unsafe fn instr32_E0(imm8s: i32) { loopne32(imm8s); } +pub unsafe fn instr32_E1(imm8s: i32) { loope32(imm8s); } +pub unsafe fn instr32_E2(imm8s: i32) { loop32(imm8s); } +pub unsafe fn instr32_E3(imm8s: i32) { jcxz32(imm8s); } + +#[no_mangle] +pub unsafe fn instr_E4(port: i32) { + if test_privileges_for_io(port, 1) { + write_reg8(AL, io_port_read8(port)); + } +} +#[no_mangle] +pub unsafe fn instr16_E5(port: i32) { + if test_privileges_for_io(port, 2) { + write_reg16(AX, io_port_read16(port)); + } +} +#[no_mangle] +pub unsafe fn instr32_E5(port: i32) { + if test_privileges_for_io(port, 4) { + write_reg32(EAX, io_port_read32(port)); + } +} +#[no_mangle] +pub unsafe fn instr_E6(port: i32) { + if test_privileges_for_io(port, 1) { + io_port_write8(port, read_reg8(AL)); + } +} +#[no_mangle] +pub unsafe fn instr16_E7(port: i32) { + if test_privileges_for_io(port, 2) { + io_port_write16(port, read_reg16(AX)); + } +} +#[no_mangle] +pub unsafe fn instr32_E7(port: i32) { + if test_privileges_for_io(port, 4) { + io_port_write32(port, read_reg32(EAX)); + } +} + +pub unsafe fn instr16_E8(imm16: i32) { + // call + return_on_pagefault!(push16(get_real_eip())); + jmp_rel16(imm16); +} +pub unsafe fn instr32_E8(imm32s: i32) { + // call + return_on_pagefault!(push32(get_real_eip())); + *instruction_pointer = *instruction_pointer + imm32s; + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +pub unsafe fn instr16_E9(imm16: i32) { + // jmp + jmp_rel16(imm16); +} +pub unsafe fn instr32_E9(imm32s: i32) { + // jmp + *instruction_pointer = *instruction_pointer + imm32s; + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} + +#[no_mangle] +pub unsafe fn instr16_EA(new_ip: i32, cs: i32) { + // jmpf + far_jump(new_ip, cs, false, false); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +#[no_mangle] +pub unsafe fn instr32_EA(new_ip: i32, cs: i32) { + // jmpf + far_jump(new_ip, cs, false, true); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} + +pub unsafe fn instr16_EB(imm8: i32) { + // jmp near + jmp_rel16(imm8); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +pub unsafe fn instr32_EB(imm8: i32) { + // jmp near + *instruction_pointer = *instruction_pointer + imm8; + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} + +#[no_mangle] +pub unsafe fn instr_EC() { + let port = read_reg16(DX); + if test_privileges_for_io(port, 1) { + write_reg8(AL, io_port_read8(port)); + } +} +#[no_mangle] +pub unsafe fn instr16_ED() { + let port = read_reg16(DX); + if test_privileges_for_io(port, 2) { + write_reg16(AX, io_port_read16(port)); + } +} +#[no_mangle] +pub unsafe fn instr32_ED() { + let port = read_reg16(DX); + if test_privileges_for_io(port, 4) { + write_reg32(EAX, io_port_read32(port)); + } +} +#[no_mangle] +pub unsafe fn instr_EE() { + let port = read_reg16(DX); + if test_privileges_for_io(port, 1) { + io_port_write8(port, read_reg8(AL)); + } +} +#[no_mangle] +pub unsafe fn instr16_EF() { + let port = read_reg16(DX); + if test_privileges_for_io(port, 2) { + io_port_write16(port, read_reg16(AX)); + } +} +#[no_mangle] +pub unsafe fn instr32_EF() { + let port = read_reg16(DX); + if test_privileges_for_io(port, 4) { + io_port_write32(port, read_reg32(EAX)); + } +} + +pub unsafe fn instr_F0() { + // lock + if false { + dbg_log!("lock"); + } + // TODO + // This triggers UD when used with + // some instructions that don't write to memory + run_prefix_instruction(); +} + +#[no_mangle] +pub unsafe fn instr_F1() { + // INT1 + // https://code.google.com/p/corkami/wiki/x86oddities#IceBP + dbg_assert!(false); +} + +pub unsafe fn instr_F2() { + // repnz + dbg_assert!(*prefixes as i32 & PREFIX_MASK_REP == 0); + *prefixes = (*prefixes as i32 | PREFIX_REPNZ) as u8; + run_prefix_instruction(); + *prefixes = 0; +} +pub unsafe fn instr_F3() { + // repz + dbg_assert!(*prefixes as i32 & PREFIX_MASK_REP == 0); + *prefixes = (*prefixes as i32 | PREFIX_REPZ) as u8; + run_prefix_instruction(); + *prefixes = 0; +} + +#[no_mangle] +pub unsafe fn instr_F4() { + if 0 != *cpl { + dbg_log!("#gp hlt with cpl != 0"); + trigger_gp(0); + return; + } + + hlt_op(); +} +#[no_mangle] +pub unsafe fn instr_F5() { + // cmc + *flags = (*flags | 1) ^ getcf() as i32; + *flags_changed &= !1; +} + +pub unsafe fn instr_F6_0_mem(addr: i32, imm: i32) { + test8(return_on_pagefault!(safe_read8(addr)), imm); +} +pub unsafe fn instr_F6_0_reg(r1: i32, imm: i32) { test8(read_reg8(r1), imm); } +pub unsafe fn instr_F6_1_mem(addr: i32, imm: i32) { + test8(return_on_pagefault!(safe_read8(addr)), imm); +} +pub unsafe fn instr_F6_1_reg(r1: i32, imm: i32) { test8(read_reg8(r1), imm); } + +#[no_mangle] +pub unsafe fn instr_F6_2_mem(addr: i32) { safe_read_write8(addr, &|x| !x & 0xFF) } +#[no_mangle] +pub unsafe fn instr_F6_2_reg(r1: i32) { write_reg8(r1, !read_reg8(r1)); } +#[no_mangle] +pub unsafe fn instr_F6_3_mem(addr: i32) { safe_read_write8(addr, &|x| neg8(x)) } +#[no_mangle] +pub unsafe fn instr_F6_3_reg(r1: i32) { write_reg8(r1, neg8(read_reg8(r1))); } +#[no_mangle] +pub unsafe fn instr_F6_4_mem(addr: i32) { mul8(return_on_pagefault!(safe_read8(addr))); } +#[no_mangle] +pub unsafe fn instr_F6_4_reg(r1: i32) { mul8(read_reg8(r1)); } +#[no_mangle] +pub unsafe fn instr_F6_5_mem(addr: i32) { + imul8(return_on_pagefault!(safe_read8(addr)) << 24 >> 24); +} +#[no_mangle] +pub unsafe fn instr_F6_5_reg(r1: i32) { imul8(read_reg8(r1) << 24 >> 24); } +#[no_mangle] +pub unsafe fn instr_F6_6_mem(addr: i32) { div8(return_on_pagefault!(safe_read8(addr)) as u32); } +#[no_mangle] +pub unsafe fn instr_F6_6_reg(r1: i32) { div8(read_reg8(r1) as u32); } +#[no_mangle] +pub unsafe fn instr_F6_7_mem(addr: i32) { + idiv8(return_on_pagefault!(safe_read8(addr)) << 24 >> 24); +} +#[no_mangle] +pub unsafe fn instr_F6_7_reg(r1: i32) { idiv8(read_reg8(r1) << 24 >> 24); } + +pub unsafe fn instr16_F7_0_mem(addr: i32, imm: i32) { + test16(return_on_pagefault!(safe_read16(addr)), imm); +} +pub unsafe fn instr16_F7_0_reg(r1: i32, imm: i32) { test16(read_reg16(r1), imm); } +pub unsafe fn instr16_F7_1_mem(addr: i32, imm: i32) { + test16(return_on_pagefault!(safe_read16(addr)), imm); +} +pub unsafe fn instr16_F7_1_reg(r1: i32, imm: i32) { test16(read_reg16(r1), imm); } +pub unsafe fn instr16_F7_2_mem(addr: i32) { safe_read_write16(addr, &|x| !x & 0xFFFF) } +pub unsafe fn instr16_F7_2_reg(r1: i32) { write_reg16(r1, !read_reg16(r1)); } +pub unsafe fn instr16_F7_3_mem(addr: i32) { safe_read_write16(addr, &|x| neg16(x)) } +pub unsafe fn instr16_F7_3_reg(r1: i32) { write_reg16(r1, neg16(read_reg16(r1))); } +pub unsafe fn instr16_F7_4_mem(addr: i32) { mul16(return_on_pagefault!(safe_read16(addr)) as u32); } +pub unsafe fn instr16_F7_4_reg(r1: i32) { mul16(read_reg16(r1) as u32); } +pub unsafe fn instr16_F7_5_mem(addr: i32) { + imul16(return_on_pagefault!(safe_read16(addr)) << 16 >> 16); +} +pub unsafe fn instr16_F7_5_reg(r1: i32) { imul16(read_reg16(r1) << 16 >> 16); } +pub unsafe fn instr16_F7_6_mem(addr: i32) { div16(return_on_pagefault!(safe_read16(addr)) as u32); } +pub unsafe fn instr16_F7_6_reg(r1: i32) { div16(read_reg16(r1) as u32); } +pub unsafe fn instr16_F7_7_mem(addr: i32) { + idiv16(return_on_pagefault!(safe_read16(addr)) << 16 >> 16); +} +pub unsafe fn instr16_F7_7_reg(r1: i32) { idiv16(read_reg16(r1) << 16 >> 16); } + +pub unsafe fn instr32_F7_0_mem(addr: i32, imm: i32) { + test32(return_on_pagefault!(safe_read32s(addr)), imm); +} +pub unsafe fn instr32_F7_0_reg(r1: i32, imm: i32) { test32(read_reg32(r1), imm); } +pub unsafe fn instr32_F7_1_mem(addr: i32, imm: i32) { + test32(return_on_pagefault!(safe_read32s(addr)), imm); +} +pub unsafe fn instr32_F7_1_reg(r1: i32, imm: i32) { test32(read_reg32(r1), imm); } +pub unsafe fn instr32_F7_2_mem(addr: i32) { safe_read_write32(addr, &|x| !x) } +pub unsafe fn instr32_F7_2_reg(r1: i32) { write_reg32(r1, !read_reg32(r1)); } +pub unsafe fn instr32_F7_3_mem(addr: i32) { safe_read_write32(addr, &|x| neg32(x)) } +pub unsafe fn instr32_F7_3_reg(r1: i32) { write_reg32(r1, neg32(read_reg32(r1))); } +pub unsafe fn instr32_F7_4_mem(addr: i32) { mul32(return_on_pagefault!(safe_read32s(addr))); } +pub unsafe fn instr32_F7_4_reg(r1: i32) { mul32(read_reg32(r1)); } +pub unsafe fn instr32_F7_5_mem(addr: i32) { imul32(return_on_pagefault!(safe_read32s(addr))); } +pub unsafe fn instr32_F7_5_reg(r1: i32) { imul32(read_reg32(r1)); } +pub unsafe fn instr32_F7_6_mem(addr: i32) { + div32(return_on_pagefault!(safe_read32s(addr)) as u32); +} +pub unsafe fn instr32_F7_6_reg(r1: i32) { div32(read_reg32(r1) as u32); } +pub unsafe fn instr32_F7_7_mem(addr: i32) { idiv32(return_on_pagefault!(safe_read32s(addr))); } +pub unsafe fn instr32_F7_7_reg(r1: i32) { idiv32(read_reg32(r1)); } + +pub unsafe fn instr_F8() { + // clc + *flags &= !FLAG_CARRY; + *flags_changed &= !1; +} +pub unsafe fn instr_F9() { + // stc + *flags |= FLAG_CARRY; + *flags_changed &= !1; +} +#[no_mangle] +pub unsafe fn instr_FA_without_fault() -> bool { + // cli + if !*protected_mode + || if 0 != *flags & FLAG_VM { getiopl() == 3 } else { getiopl() >= *cpl as i32 } + { + *flags &= !FLAG_INTERRUPT; + return true; + } + else if false + && getiopl() < 3 + && if 0 != *flags & FLAG_VM { + 0 != *cr.offset(4) & CR4_VME + } + else { + *cpl == 3 && 0 != *cr.offset(4) & CR4_PVI + } + { + *flags &= !FLAG_VIF; + return true; + } + else { + dbg_log!("cli #gp"); + return false; + }; +} +pub unsafe fn instr_FA() { + if !instr_FA_without_fault() { + trigger_gp(0); + } +} + +#[no_mangle] +pub unsafe fn instr_FB_without_fault() -> bool { + // sti + if !*protected_mode + || if 0 != *flags & FLAG_VM { getiopl() == 3 } else { getiopl() >= *cpl as i32 } + { + *flags |= FLAG_INTERRUPT; + return true; + } + else if false + && getiopl() < 3 + && *flags & FLAG_VIP == 0 + && if 0 != *flags & FLAG_VM { + 0 != *cr.offset(4) & CR4_VME + } + else { + *cpl == 3 && 0 != *cr.offset(4) & CR4_PVI + } + { + *flags |= FLAG_VIF; + return true; + } + else { + dbg_log!("sti #gp"); + return false; + }; +} +pub unsafe fn instr_FB() { + if !instr_FB_without_fault() { + trigger_gp(0); + } + else { + *prefixes = 0; + *previous_ip = *instruction_pointer; + *instruction_counter += 1; + run_instruction(return_on_pagefault!(read_imm8()) | (is_osize_32() as i32) << 8); + + handle_irqs(); + } +} + +pub unsafe fn instr_FC() { + // cld + *flags &= !FLAG_DIRECTION; +} +pub unsafe fn instr_FD() { + // std + *flags |= FLAG_DIRECTION; +} + +pub unsafe fn instr_FE_0_mem(addr: i32) { safe_read_write8(addr, &|x| inc8(x)) } +pub unsafe fn instr_FE_0_reg(r1: i32) { write_reg8(r1, inc8(read_reg8(r1))); } +pub unsafe fn instr_FE_1_mem(addr: i32) { safe_read_write8(addr, &|x| dec8(x)) } +pub unsafe fn instr_FE_1_reg(r1: i32) { write_reg8(r1, dec8(read_reg8(r1))); } +pub unsafe fn instr16_FF_0_mem(addr: i32) { safe_read_write16(addr, &|x| inc16(x)) } +pub unsafe fn instr16_FF_0_reg(r1: i32) { write_reg16(r1, inc16(read_reg16(r1))); } +pub unsafe fn instr16_FF_1_mem(addr: i32) { safe_read_write16(addr, &|x| dec16(x)) } +pub unsafe fn instr16_FF_1_reg(r1: i32) { write_reg16(r1, dec16(read_reg16(r1))); } +pub unsafe fn instr16_FF_2_helper(data: i32) { + // call near + let cs = get_seg_cs(); + return_on_pagefault!(push16(get_real_eip())); + *instruction_pointer = cs + data; + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +pub unsafe fn instr16_FF_2_mem(addr: i32) { + instr16_FF_2_helper(return_on_pagefault!(safe_read16(addr))); +} +pub unsafe fn instr16_FF_2_reg(r1: i32) { instr16_FF_2_helper(read_reg16(r1)); } + +#[no_mangle] +pub unsafe fn instr16_FF_3_reg(_r: i32) { + dbg_log!("callf #ud"); + trigger_ud(); +} +#[no_mangle] +pub unsafe fn instr16_FF_3_mem(addr: i32) { + // callf + let new_ip = return_on_pagefault!(safe_read16(addr)); + let new_cs = return_on_pagefault!(safe_read16(addr + 2)); + far_jump(new_ip, new_cs, true, false); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +pub unsafe fn instr16_FF_4_helper(data: i32) { + // jmp near + *instruction_pointer = get_seg_cs() + data; + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +pub unsafe fn instr16_FF_4_mem(addr: i32) { + instr16_FF_4_helper(return_on_pagefault!(safe_read16(addr))); +} +pub unsafe fn instr16_FF_4_reg(r1: i32) { instr16_FF_4_helper(read_reg16(r1)); } + +#[no_mangle] +pub unsafe fn instr16_FF_5_reg(_r: i32) { + dbg_log!("jmpf #ud"); + trigger_ud(); +} +#[no_mangle] +pub unsafe fn instr16_FF_5_mem(addr: i32) { + // jmpf + let new_ip = return_on_pagefault!(safe_read16(addr)); + let new_cs = return_on_pagefault!(safe_read16(addr + 2)); + far_jump(new_ip, new_cs, false, false); + dbg_assert!(*is_32 || get_real_eip() < 0x10000); +} +pub unsafe fn instr16_FF_6_mem(addr: i32) { + return_on_pagefault!(push16(return_on_pagefault!(safe_read16(addr)))); +} +pub unsafe fn instr16_FF_6_reg(r1: i32) { + return_on_pagefault!(push16(read_reg16(r1))); +} + +pub unsafe fn instr32_FF_0_mem(addr: i32) { safe_read_write32(addr, &|x| inc32(x)) } +pub unsafe fn instr32_FF_0_reg(r1: i32) { write_reg32(r1, inc32(read_reg32(r1))); } +pub unsafe fn instr32_FF_1_mem(addr: i32) { safe_read_write32(addr, &|x| dec32(x)) } +pub unsafe fn instr32_FF_1_reg(r1: i32) { write_reg32(r1, dec32(read_reg32(r1))); } + +pub unsafe fn instr32_FF_2_helper(data: i32) { + // call near + let cs = get_seg_cs(); + return_on_pagefault!(push32(get_real_eip())); + dbg_assert!(*is_32 || data < 0x10000); + *instruction_pointer = cs + data; +} +pub unsafe fn instr32_FF_2_mem(addr: i32) { + instr32_FF_2_helper(return_on_pagefault!(safe_read32s(addr))); +} +pub unsafe fn instr32_FF_2_reg(r1: i32) { instr32_FF_2_helper(read_reg32(r1)); } +#[no_mangle] +pub unsafe fn instr32_FF_3_reg(_r: i32) { + dbg_log!("callf #ud"); + trigger_ud(); +} +#[no_mangle] +pub unsafe fn instr32_FF_3_mem(addr: i32) { + // callf + let new_ip = return_on_pagefault!(safe_read32s(addr)); + let new_cs = return_on_pagefault!(safe_read16(addr + 4)); + if !*protected_mode || vm86_mode() { + if 0 != new_ip as u32 & 0xFFFF0000 { + dbg_assert!(false); + } + } + far_jump(new_ip, new_cs, true, true); + dbg_assert!(*is_32 || new_ip < 0x10000); +} + +pub unsafe fn instr32_FF_4_helper(data: i32) { + // jmp near + dbg_assert!(*is_32 || data < 0x10000); + *instruction_pointer = get_seg_cs() + data; +} +pub unsafe fn instr32_FF_4_mem(addr: i32) { + instr32_FF_4_helper(return_on_pagefault!(safe_read32s(addr))); +} +pub unsafe fn instr32_FF_4_reg(r1: i32) { instr32_FF_4_helper(read_reg32(r1)); } + +#[no_mangle] +pub unsafe fn instr32_FF_5_reg(_r: i32) { + dbg_log!("jmpf #ud"); + trigger_ud(); +} +#[no_mangle] +pub unsafe fn instr32_FF_5_mem(addr: i32) { + // jmpf + let new_ip = return_on_pagefault!(safe_read32s(addr)); + let new_cs = return_on_pagefault!(safe_read16(addr + 4)); + if !*protected_mode || vm86_mode() { + if 0 != new_ip as u32 & 0xFFFF0000 { + dbg_assert!(false); + } + } + far_jump(new_ip, new_cs, false, true); + dbg_assert!(*is_32 || new_ip < 0x10000); +} +pub unsafe fn instr32_FF_6_mem(addr: i32) { + return_on_pagefault!(push32(return_on_pagefault!(safe_read32s(addr)))); +} +pub unsafe fn instr32_FF_6_reg(r1: i32) { + return_on_pagefault!(push32(read_reg32(r1))); +} diff --git a/src/rust/cpu/instructions_0f.rs b/src/rust/cpu/instructions_0f.rs new file mode 100644 index 0000000..3b1755e --- /dev/null +++ b/src/rust/cpu/instructions_0f.rs @@ -0,0 +1,5147 @@ +#![allow(non_snake_case)] + +extern "C" { + fn get_rand_int() -> i32; +} + +unsafe fn undefined_instruction() { + dbg_assert!(false, "Undefined instructions"); + trigger_ud() +} +unsafe fn unimplemented_sse() { + dbg_assert!(false, "Unimplemented SSE instruction"); + trigger_ud() +} + +use cpu::arith::{ + bsf16, bsf32, bsr16, bsr32, bt_mem, bt_reg, btc_mem, btc_reg, btr_mem, btr_reg, bts_mem, + bts_reg, cmpxchg8, cmpxchg16, cmpxchg32, popcnt, shld16, shld32, shrd16, shrd32, xadd8, xadd16, + xadd32, +}; +use cpu::arith::{ + imul_reg16, imul_reg32, saturate_sd_to_sb, saturate_sd_to_sw, saturate_sd_to_ub, + saturate_sw_to_sb, saturate_sw_to_ub, saturate_ud_to_ub, saturate_uw, +}; +use cpu::cpu::*; +use cpu::fpu::fpu_set_tag_word; +use cpu::global_pointers::*; +use cpu::misc_instr::{ + adjust_stack_reg, bswap, cmovcc16, cmovcc32, fxrstor, fxsave, get_stack_pointer, jmpcc16, + jmpcc32, push16, push32_sreg, setcc_mem, setcc_reg, test_b, test_be, test_l, test_le, test_o, + test_p, test_s, test_z, +}; +use cpu::misc_instr::{lar, lsl, verr, verw}; +use cpu::misc_instr::{lss16, lss32}; +use cpu::sse_instr::*; + +#[no_mangle] +pub unsafe fn instr16_0F00_0_mem(addr: i32) { + // sldt + if !*protected_mode || vm86_mode() { + trigger_ud(); + return; + } + return_on_pagefault!(safe_write16(addr, *sreg.offset(LDTR as isize) as i32)); +} +#[no_mangle] +pub unsafe fn instr32_0F00_0_mem(addr: i32) { instr16_0F00_0_mem(addr) } +#[no_mangle] +pub unsafe fn instr16_0F00_0_reg(r: i32) { + if !*protected_mode || vm86_mode() { + trigger_ud(); + return; + } + write_reg16(r, *sreg.offset(LDTR as isize) as i32); +} +#[no_mangle] +pub unsafe fn instr32_0F00_0_reg(r: i32) { + if !*protected_mode || vm86_mode() { + trigger_ud(); + return; + } + write_reg32(r, *sreg.offset(LDTR as isize) as i32); +} + +#[no_mangle] +pub unsafe fn instr16_0F00_1_mem(addr: i32) { + // str + if !*protected_mode || vm86_mode() { + trigger_ud(); + return; + } + return_on_pagefault!(safe_write16(addr, *sreg.offset(TR as isize) as i32)); +} +#[no_mangle] +pub unsafe fn instr32_0F00_1_mem(addr: i32) { instr16_0F00_1_mem(addr) } +#[no_mangle] +pub unsafe fn instr16_0F00_1_reg(r: i32) { + if !*protected_mode || vm86_mode() { + trigger_ud(); + return; + } + write_reg16(r, *sreg.offset(TR as isize) as i32); +} +#[no_mangle] +pub unsafe fn instr32_0F00_1_reg(r: i32) { + if !*protected_mode || vm86_mode() { + trigger_ud(); + return; + } + write_reg32(r, *sreg.offset(TR as isize) as i32); +} + +#[no_mangle] +pub unsafe fn instr16_0F00_2_mem(addr: i32) { + // lldt + if !*protected_mode || vm86_mode() { + trigger_ud(); + } + else if 0 != *cpl { + trigger_gp(0); + } + else { + return_on_pagefault!(load_ldt(return_on_pagefault!(safe_read16(addr)))); + }; +} +#[no_mangle] +pub unsafe fn instr32_0F00_2_mem(addr: i32) { instr16_0F00_2_mem(addr) } +#[no_mangle] +pub unsafe fn instr16_0F00_2_reg(r: i32) { + if !*protected_mode || vm86_mode() { + trigger_ud(); + } + else if 0 != *cpl { + trigger_gp(0); + } + else { + return_on_pagefault!(load_ldt(read_reg16(r))); + }; +} +#[no_mangle] +pub unsafe fn instr32_0F00_2_reg(r: i32) { instr16_0F00_2_reg(r) } + +#[no_mangle] +pub unsafe fn instr16_0F00_3_mem(addr: i32) { + // ltr + if !*protected_mode || vm86_mode() { + trigger_ud(); + } + else if 0 != *cpl { + trigger_gp(0); + } + else { + load_tr(return_on_pagefault!(safe_read16(addr))); + }; +} +#[no_mangle] +pub unsafe fn instr32_0F00_3_mem(addr: i32) { instr16_0F00_3_mem(addr); } +#[no_mangle] +pub unsafe fn instr16_0F00_3_reg(r: i32) { + if !*protected_mode || vm86_mode() { + trigger_ud(); + } + else if 0 != *cpl { + trigger_gp(0); + } + else { + load_tr(read_reg16(r)); + }; +} +#[no_mangle] +pub unsafe fn instr32_0F00_3_reg(r: i32) { instr16_0F00_3_reg(r) } + +#[no_mangle] +pub unsafe fn instr16_0F00_4_mem(addr: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("verr #ud"); + trigger_ud(); + return; + } + verr(return_on_pagefault!(safe_read16(addr))); +} +#[no_mangle] +pub unsafe fn instr32_0F00_4_mem(addr: i32) { instr16_0F00_4_mem(addr) } +#[no_mangle] +pub unsafe fn instr16_0F00_4_reg(r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("verr #ud"); + trigger_ud(); + return; + } + verr(read_reg16(r)); +} +#[no_mangle] +pub unsafe fn instr32_0F00_4_reg(r: i32) { instr16_0F00_4_reg(r) } +#[no_mangle] +pub unsafe fn instr16_0F00_5_mem(addr: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("verw #ud"); + trigger_ud(); + return; + } + verw(return_on_pagefault!(safe_read16(addr))); +} +#[no_mangle] +pub unsafe fn instr32_0F00_5_mem(addr: i32) { instr16_0F00_5_mem(addr) } +#[no_mangle] +pub unsafe fn instr16_0F00_5_reg(r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("verw #ud"); + trigger_ud(); + return; + } + verw(read_reg16(r)); +} +#[no_mangle] +pub unsafe fn instr32_0F00_5_reg(r: i32) { instr16_0F00_5_reg(r) } + +#[no_mangle] +pub unsafe fn instr16_0F01_0_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0F01_0_reg(_r: i32) { trigger_ud(); } + +unsafe fn sgdt(addr: i32, mask: i32) { + return_on_pagefault!(writable_or_pagefault(addr, 6)); + safe_write16(addr, *gdtr_size).unwrap(); + safe_write32(addr + 2, *gdtr_offset & mask).unwrap(); +} +#[no_mangle] +pub unsafe fn instr16_0F01_0_mem(addr: i32) { sgdt(addr, 0xFFFFFF) } +#[no_mangle] +pub unsafe fn instr32_0F01_0_mem(addr: i32) { sgdt(addr, -1) } + +#[no_mangle] +pub unsafe fn instr16_0F01_1_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0F01_1_reg(_r: i32) { trigger_ud(); } + +unsafe fn sidt(addr: i32, mask: i32) { + return_on_pagefault!(writable_or_pagefault(addr, 6)); + safe_write16(addr, *idtr_size).unwrap(); + safe_write32(addr + 2, *idtr_offset & mask).unwrap(); +} +#[no_mangle] +pub unsafe fn instr16_0F01_1_mem(addr: i32) { sidt(addr, 0xFFFFFF) } +#[no_mangle] +pub unsafe fn instr32_0F01_1_mem(addr: i32) { sidt(addr, -1) } + +#[no_mangle] +pub unsafe fn instr16_0F01_2_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0F01_2_reg(_r: i32) { trigger_ud(); } + +unsafe fn lgdt(addr: i32, mask: i32) { + if 0 != *cpl { + trigger_gp(0); + return; + } + let size = return_on_pagefault!(safe_read16(addr)); + let offset = return_on_pagefault!(safe_read32s(addr + 2)); + *gdtr_size = size; + *gdtr_offset = offset & mask; +} +#[no_mangle] +pub unsafe fn instr16_0F01_2_mem(addr: i32) { lgdt(addr, 0xFFFFFF); } +#[no_mangle] +pub unsafe fn instr32_0F01_2_mem(addr: i32) { lgdt(addr, -1); } + +#[no_mangle] +pub unsafe fn instr16_0F01_3_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0F01_3_reg(_r: i32) { trigger_ud(); } + +unsafe fn lidt(addr: i32, mask: i32) { + if 0 != *cpl { + trigger_gp(0); + return; + } + let size = return_on_pagefault!(safe_read16(addr)); + let offset = return_on_pagefault!(safe_read32s(addr + 2)); + *idtr_size = size; + *idtr_offset = offset & mask; +} +#[no_mangle] +pub unsafe fn instr16_0F01_3_mem(addr: i32) { lidt(addr, 0xFFFFFF); } +#[no_mangle] +pub unsafe fn instr32_0F01_3_mem(addr: i32) { lidt(addr, -1); } + +#[no_mangle] +pub unsafe fn instr16_0F01_4_reg(r: i32) { + // smsw + write_reg16(r, *cr); +} +#[no_mangle] +pub unsafe fn instr32_0F01_4_reg(r: i32) { write_reg32(r, *cr); } +#[no_mangle] +pub unsafe fn instr16_0F01_4_mem(addr: i32) { + return_on_pagefault!(safe_write16(addr, *cr)); +} +#[no_mangle] +pub unsafe fn instr32_0F01_4_mem(addr: i32) { + return_on_pagefault!(safe_write16(addr, *cr)); +} + +#[no_mangle] +pub unsafe fn lmsw(mut new_cr0: i32) { + new_cr0 = *cr & !15 | new_cr0 & 15; + if *protected_mode { + // lmsw cannot be used to switch back + new_cr0 |= CR0_PE + } + set_cr0(new_cr0); +} +#[no_mangle] +pub unsafe fn instr16_0F01_6_reg(r: i32) { + if 0 != *cpl { + trigger_gp(0); + return; + } + lmsw(read_reg16(r)); +} +#[no_mangle] +pub unsafe fn instr32_0F01_6_reg(r: i32) { instr16_0F01_6_reg(r); } +#[no_mangle] +pub unsafe fn instr16_0F01_6_mem(addr: i32) { + if 0 != *cpl { + trigger_gp(0); + return; + } + lmsw(return_on_pagefault!(safe_read16(addr))); +} +#[no_mangle] +pub unsafe fn instr32_0F01_6_mem(addr: i32) { instr16_0F01_6_mem(addr) } + +#[no_mangle] +pub unsafe fn instr16_0F01_7_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0F01_7_reg(_r: i32) { trigger_ud(); } + +#[no_mangle] +pub unsafe fn instr16_0F01_7_mem(addr: i32) { + // invlpg + if 0 != *cpl { + trigger_gp(0); + return; + } + invlpg(addr); +} +#[no_mangle] +pub unsafe fn instr32_0F01_7_mem(addr: i32) { instr16_0F01_7_mem(addr) } + +#[no_mangle] +pub unsafe fn instr16_0F02_mem(addr: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("lar #ud"); + trigger_ud(); + return; + } + write_reg16( + r, + lar(return_on_pagefault!(safe_read16(addr)), read_reg16(r)), + ); +} +#[no_mangle] +pub unsafe fn instr16_0F02_reg(r1: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("lar #ud"); + trigger_ud(); + return; + } + write_reg16(r, lar(read_reg16(r1), read_reg16(r))); +} +#[no_mangle] +pub unsafe fn instr32_0F02_mem(addr: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("lar #ud"); + trigger_ud(); + return; + } + write_reg32( + r, + lar(return_on_pagefault!(safe_read16(addr)), read_reg32(r)), + ); +} +#[no_mangle] +pub unsafe fn instr32_0F02_reg(r1: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("lar #ud"); + trigger_ud(); + return; + } + write_reg32(r, lar(read_reg16(r1), read_reg32(r))); +} +#[no_mangle] +pub unsafe fn instr16_0F03_mem(addr: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("lsl #ud"); + trigger_ud(); + return; + } + write_reg16( + r, + lsl(return_on_pagefault!(safe_read16(addr)), read_reg16(r)), + ); +} +#[no_mangle] +pub unsafe fn instr16_0F03_reg(r1: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("lsl #ud"); + trigger_ud(); + return; + } + write_reg16(r, lsl(read_reg16(r1), read_reg16(r))); +} +#[no_mangle] +pub unsafe fn instr32_0F03_mem(addr: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("lsl #ud"); + trigger_ud(); + return; + } + write_reg32( + r, + lsl(return_on_pagefault!(safe_read16(addr)), read_reg32(r)), + ); +} +#[no_mangle] +pub unsafe fn instr32_0F03_reg(r1: i32, r: i32) { + if !*protected_mode || vm86_mode() { + dbg_log!("lsl #ud"); + trigger_ud(); + return; + } + write_reg32(r, lsl(read_reg16(r1), read_reg32(r))); +} +#[no_mangle] +pub unsafe fn instr_0F04() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F05() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F06() { + // clts + if 0 != *cpl { + dbg_log!("clts #gp"); + trigger_gp(0); + } + else { + if false { + dbg_log!("clts"); + } + *cr &= !CR0_TS; + }; +} +#[no_mangle] +pub unsafe fn instr_0F07() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F08() { + // invd + undefined_instruction(); +} +#[no_mangle] +pub unsafe fn instr_0F09() { + if 0 != *cpl { + dbg_log!("wbinvd #gp"); + trigger_gp(0); + } + else { + // wbinvd + }; +} +#[no_mangle] +pub unsafe fn instr_0F0A() { undefined_instruction(); } +pub unsafe fn instr_0F0B() { + // UD2 + trigger_ud(); +} +#[no_mangle] +pub unsafe fn instr_0F0C() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F0D() { + // nop + undefined_instruction(); +} +#[no_mangle] +pub unsafe fn instr_0F0E() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F0F() { undefined_instruction(); } + +pub unsafe fn instr_0F10(source: reg128, r: i32) { + // movups xmm, xmm/m128 + mov_rm_r128(source, r); +} +pub unsafe fn instr_0F10_reg(r1: i32, r2: i32) { instr_0F10(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F10_mem(addr: i32, r: i32) { + instr_0F10(return_on_pagefault!(safe_read128s(addr)), r); +} +pub unsafe fn instr_F30F10_reg(r1: i32, r2: i32) { + // movss xmm, xmm/m32 + let data = read_xmm128s(r1); + write_xmm32(r2, data.u32[0] as i32); +} +pub unsafe fn instr_F30F10_mem(addr: i32, r: i32) { + // movss xmm, xmm/m32 + let data = return_on_pagefault!(safe_read32s(addr)); + write_xmm128(r, data, 0, 0, 0); +} +pub unsafe fn instr_660F10(source: reg128, r: i32) { + // movupd xmm, xmm/m128 + mov_rm_r128(source, r); +} +pub unsafe fn instr_660F10_reg(r1: i32, r2: i32) { instr_660F10(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F10_mem(addr: i32, r: i32) { + instr_660F10(return_on_pagefault!(safe_read128s(addr)), r); +} +pub unsafe fn instr_F20F10_reg(r1: i32, r2: i32) { + // movsd xmm, xmm/m64 + let data = read_xmm128s(r1); + write_xmm64(r2, data.u64[0]); +} +pub unsafe fn instr_F20F10_mem(addr: i32, r: i32) { + // movsd xmm, xmm/m64 + let data = return_on_pagefault!(safe_read64s(addr)); + write_xmm128_2(r, data, 0); +} +pub unsafe fn instr_0F11_reg(r1: i32, r2: i32) { + // movups xmm/m128, xmm + mov_r_r128(r1, r2); +} +pub unsafe fn instr_0F11_mem(addr: i32, r: i32) { + // movups xmm/m128, xmm + mov_r_m128(addr, r); +} +pub unsafe fn instr_F30F11_reg(rm_dest: i32, reg_src: i32) { + // movss xmm/m32, xmm + let data = read_xmm128s(reg_src); + write_xmm32(rm_dest, data.u32[0] as i32); +} +pub unsafe fn instr_F30F11_mem(addr: i32, r: i32) { + // movss xmm/m32, xmm + let data = read_xmm128s(r); + return_on_pagefault!(safe_write32(addr, data.u32[0] as i32)); +} +pub unsafe fn instr_660F11_reg(r1: i32, r2: i32) { + // movupd xmm/m128, xmm + mov_r_r128(r1, r2); +} +pub unsafe fn instr_660F11_mem(addr: i32, r: i32) { + // movupd xmm/m128, xmm + mov_r_m128(addr, r); +} +pub unsafe fn instr_F20F11_reg(r1: i32, r2: i32) { + // movsd xmm/m64, xmm + let data = read_xmm128s(r2); + write_xmm64(r1, data.u64[0]); +} +pub unsafe fn instr_F20F11_mem(addr: i32, r: i32) { + // movsd xmm/m64, xmm + let data = read_xmm64s(r); + return_on_pagefault!(safe_write64(addr, data)); +} +pub unsafe fn instr_0F12_mem(addr: i32, r: i32) { + // movlps xmm, m64 + let data = return_on_pagefault!(safe_read64s(addr)); + write_xmm64(r, data); +} +pub unsafe fn instr_0F12_reg(r1: i32, r2: i32) { + // movhlps xmm, xmm + let data = read_xmm128s(r1); + write_xmm64(r2, data.u64[1]); +} +pub unsafe fn instr_660F12_reg(_r1: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_660F12_mem(addr: i32, r: i32) { + // movlpd xmm, m64 + let data = return_on_pagefault!(safe_read64s(addr)); + write_xmm64(r, data); +} +#[no_mangle] +pub unsafe fn instr_F20F12_mem(_addr: i32, _r: i32) { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_F20F12_reg(_r1: i32, _r2: i32) { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_F30F12_mem(_addr: i32, _r: i32) { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_F30F12_reg(_r1: i32, _r2: i32) { unimplemented_sse(); } + +pub unsafe fn instr_0F13_mem(addr: i32, r: i32) { + // movlps m64, xmm + movl_r128_m64(addr, r); +} +pub unsafe fn instr_0F13_reg(_r1: i32, _r2: i32) { trigger_ud(); } +pub unsafe fn instr_660F13_reg(_r1: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_660F13_mem(addr: i32, r: i32) { + // movlpd xmm/m64, xmm + movl_r128_m64(addr, r); +} + +#[no_mangle] +pub unsafe fn instr_0F14(source: u64, r: i32) { + // unpcklps xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm64s(r); + write_xmm128( + r, + destination as i32, + source as i32, + (destination >> 32) as i32, + (source >> 32) as i32, + ); +} +pub unsafe fn instr_0F14_reg(r1: i32, r2: i32) { instr_0F14(read_xmm64s(r1), r2); } +pub unsafe fn instr_0F14_mem(addr: i32, r: i32) { + instr_0F14(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F14(source: u64, r: i32) { + // unpcklpd xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm64s(r); + write_xmm128( + r, + destination as i32, + (destination >> 32) as i32, + source as i32, + (source >> 32) as i32, + ); +} +pub unsafe fn instr_660F14_reg(r1: i32, r2: i32) { instr_660F14(read_xmm64s(r1), r2); } +pub unsafe fn instr_660F14_mem(addr: i32, r: i32) { + instr_660F14(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F15(source: reg128, r: i32) { + // unpckhps xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + write_xmm128( + r, + destination.u32[2] as i32, + source.u32[2] as i32, + destination.u32[3] as i32, + source.u32[3] as i32, + ); +} +pub unsafe fn instr_0F15_reg(r1: i32, r2: i32) { instr_0F15(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F15_mem(addr: i32, r: i32) { + instr_0F15(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F15(source: reg128, r: i32) { + // unpckhpd xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + write_xmm128( + r, + destination.u32[2] as i32, + destination.u32[3] as i32, + source.u32[2] as i32, + source.u32[3] as i32, + ); +} +pub unsafe fn instr_660F15_reg(r1: i32, r2: i32) { instr_660F15(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F15_mem(addr: i32, r: i32) { + instr_660F15(return_on_pagefault!(safe_read128s(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F16(source: u64, r: i32) { (*reg_xmm.offset(r as isize)).u64[1] = source; } +pub unsafe fn instr_0F16_mem(addr: i32, r: i32) { + // movhps xmm, m64 + instr_0F16(return_on_pagefault!(safe_read64s(addr)), r); +} +pub unsafe fn instr_0F16_reg(r1: i32, r2: i32) { + // movlhps xmm, xmm + instr_0F16(read_xmm64s(r1), r2); +} +pub unsafe fn instr_660F16_mem(addr: i32, r: i32) { + // movhpd xmm, m64 + instr_0F16(return_on_pagefault!(safe_read64s(addr)), r); +} +pub unsafe fn instr_660F16_reg(_r1: i32, _r2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_F30F16_reg(_r1: i32, _r2: i32) { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_F30F16_mem(_addr: i32, _r: i32) { unimplemented_sse(); } + +pub unsafe fn instr_0F17_mem(addr: i32, r: i32) { + // movhps m64, xmm + movh_r128_m64(addr, r); +} +pub unsafe fn instr_0F17_reg(_r1: i32, _r2: i32) { trigger_ud(); } +pub unsafe fn instr_660F17_mem(addr: i32, r: i32) { + // movhpd m64, xmm + movh_r128_m64(addr, r); +} +pub unsafe fn instr_660F17_reg(_r1: i32, _r2: i32) { trigger_ud(); } + +pub unsafe fn instr_0F18_reg(_r1: i32, _r2: i32) { + // reserved nop +} +pub unsafe fn instr_0F18_mem(_addr: i32, _r: i32) { + // prefetch + // nop for us +} + +pub unsafe fn instr_0F19_reg(_r1: i32, _r2: i32) {} +pub unsafe fn instr_0F19_mem(_addr: i32, _r: i32) {} + +#[no_mangle] +pub unsafe fn instr_0F1A() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F1B() { undefined_instruction(); } + +pub unsafe fn instr_0F1C_reg(_r1: i32, _r2: i32) {} +pub unsafe fn instr_0F1C_mem(_addr: i32, _r: i32) {} +pub unsafe fn instr_0F1D_reg(_r1: i32, _r2: i32) {} +pub unsafe fn instr_0F1D_mem(_addr: i32, _r: i32) {} +pub unsafe fn instr_0F1E_reg(_r1: i32, _r2: i32) {} +pub unsafe fn instr_0F1E_mem(_addr: i32, _r: i32) {} +pub unsafe fn instr_0F1F_reg(_r1: i32, _r2: i32) {} +pub unsafe fn instr_0F1F_mem(_addr: i32, _r: i32) {} + +#[no_mangle] +pub unsafe fn instr_0F20(r: i32, creg: i32) { + if 0 != *cpl { + trigger_gp(0); + return; + } + + match creg { + 0 => { + write_reg32(r, *cr); + }, + 2 => { + write_reg32(r, *cr.offset(2)); + }, + 3 => { + write_reg32(r, *cr.offset(3)); + }, + 4 => { + write_reg32(r, *cr.offset(4)); + }, + _ => { + dbg_log!("{}", creg); + undefined_instruction(); + }, + } +} +#[no_mangle] +pub unsafe fn instr_0F21(r: i32, mut dreg_index: i32) { + if 0 != *cpl { + trigger_gp(0); + return; + } + + if dreg_index == 4 || dreg_index == 5 { + if 0 != *cr.offset(4) & CR4_DE { + dbg_log!("#ud mov dreg 4/5 with cr4.DE set"); + trigger_ud(); + return; + } + else { + // DR4 and DR5 refer to DR6 and DR7 respectively + dreg_index += 2 + } + } + write_reg32(r, *dreg.offset(dreg_index as isize)); + + if false { + dbg_log!( + "read dr{}: {:x}", + dreg_index, + *dreg.offset(dreg_index as isize) + ); + } +} +#[no_mangle] +pub unsafe fn instr_0F22(r: i32, creg: i32) { + if 0 != *cpl { + trigger_gp(0); + return; + } + + let data = read_reg32(r); + // mov cr, addr + match creg { + 0 => { + if false { + dbg_log!("cr0 <- {:x}", data); + } + set_cr0(data); + }, + 2 => { + dbg_log!("cr2 <- {:x}", data); + *cr.offset(2) = data + }, + 3 => set_cr3(data), + 4 => { + dbg_log!("cr4 <- {:x}", data); + if 0 != data as u32 + & ((1 << 11 | 1 << 12 | 1 << 15 | 1 << 16 | 1 << 19) as u32 | 0xFFC00000) + { + dbg_log!("trigger_gp: Invalid cr4 bit"); + trigger_gp(0); + return; + } + else { + if 0 != (*cr.offset(4) ^ data) & (CR4_PGE | CR4_PSE | CR4_PAE) { + full_clear_tlb(); + } + if data & CR4_PAE != 0 + && 0 != (*cr.offset(4) ^ data) & (CR4_PGE | CR4_PSE | CR4_SMEP) + { + load_pdpte(*cr.offset(3)); + } + *cr.offset(4) = data; + } + }, + _ => { + dbg_log!("{}", creg); + undefined_instruction(); + }, + } +} +#[no_mangle] +pub unsafe fn instr_0F23(r: i32, mut dreg_index: i32) { + if 0 != *cpl { + trigger_gp(0); + return; + } + + if dreg_index == 4 || dreg_index == 5 { + if 0 != *cr.offset(4) & CR4_DE { + dbg_log!("#ud mov dreg 4/5 with cr4.DE set"); + trigger_ud(); + return; + } + else { + // DR4 and DR5 refer to DR6 and DR7 respectively + dreg_index += 2 + } + } + *dreg.offset(dreg_index as isize) = read_reg32(r); + if false { + dbg_log!( + "write dr{}: {:x}", + dreg_index, + *dreg.offset(dreg_index as isize) + ); + } +} +#[no_mangle] +pub unsafe fn instr_0F24() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F25() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F26() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F27() { undefined_instruction(); } + +pub unsafe fn instr_0F28(source: reg128, r: i32) { + // movaps xmm, xmm/m128 + // XXX: Aligned read or #gp + mov_rm_r128(source, r); +} +pub unsafe fn instr_0F28_reg(r1: i32, r2: i32) { instr_0F28(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F28_mem(addr: i32, r: i32) { + instr_0F28(return_on_pagefault!(safe_read128s(addr)), r); +} +pub unsafe fn instr_660F28(source: reg128, r: i32) { + // movapd xmm, xmm/m128 + // XXX: Aligned read or #gp + // Note: Same as movdqa (660F6F) + mov_rm_r128(source, r); +} +pub unsafe fn instr_660F28_reg(r1: i32, r2: i32) { instr_660F28(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F28_mem(addr: i32, r: i32) { + instr_660F28(return_on_pagefault!(safe_read128s(addr)), r); +} +pub unsafe fn instr_0F29_mem(addr: i32, r: i32) { + // movaps m128, xmm + let data = read_xmm128s(r); + // XXX: Aligned write or #gp + return_on_pagefault!(safe_write128(addr, data)); +} +pub unsafe fn instr_0F29_reg(r1: i32, r2: i32) { + // movaps xmm, xmm + mov_r_r128(r1, r2); +} +pub unsafe fn instr_660F29_mem(addr: i32, r: i32) { + // movapd m128, xmm + let data = read_xmm128s(r); + // XXX: Aligned write or #gp + return_on_pagefault!(safe_write128(addr, data)); +} +pub unsafe fn instr_660F29_reg(r1: i32, r2: i32) { + // movapd xmm, xmm + mov_r_r128(r1, r2); +} + +#[no_mangle] +pub unsafe fn instr_0F2A(source: u64, r: i32) { + // cvtpi2ps xmm, mm/m64 + // Note: Casts here can fail + // XXX: Should round according to round control + let source: [i32; 2] = std::mem::transmute(source); + let result = [source[0] as f32, source[1] as f32]; + write_xmm64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F2A_reg(r1: i32, r2: i32) { instr_0F2A(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F2A_mem(addr: i32, r: i32) { + instr_0F2A(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F2A(source: u64, r: i32) { + // cvtpi2pd xmm, xmm/m64 + // These casts can't fail + let source: [i32; 2] = std::mem::transmute(source); + let result = reg128 { + f64: [source[0] as f64, source[1] as f64], + }; + write_xmm_reg128(r, result); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_660F2A_reg(r1: i32, r2: i32) { instr_660F2A(read_mmx64s(r1), r2); } +pub unsafe fn instr_660F2A_mem(addr: i32, r: i32) { + instr_660F2A(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F20F2A(source: i32, r: i32) { + // cvtsi2sd xmm, r32/m32 + // This cast can't fail + write_xmm_f64(r, source as f64); +} +pub unsafe fn instr_F20F2A_reg(r1: i32, r2: i32) { instr_F20F2A(read_reg32(r1), r2); } +pub unsafe fn instr_F20F2A_mem(addr: i32, r: i32) { + instr_F20F2A(return_on_pagefault!(safe_read32s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F2A(source: i32, r: i32) { + // cvtsi2ss xmm, r/m32 + // Note: This cast can fail + // XXX: Should round according to round control + let result = source as f32; + write_xmm_f32(r, result); +} +pub unsafe fn instr_F30F2A_reg(r1: i32, r2: i32) { instr_F30F2A(read_reg32(r1), r2); } +pub unsafe fn instr_F30F2A_mem(addr: i32, r: i32) { + instr_F30F2A(return_on_pagefault!(safe_read32s(addr)), r); +} + +pub unsafe fn instr_0F2B_reg(_r1: i32, _r2: i32) { trigger_ud(); } +pub unsafe fn instr_0F2B_mem(addr: i32, r: i32) { + // movntps m128, xmm + // XXX: Aligned write or #gp + mov_r_m128(addr, r); +} +pub unsafe fn instr_660F2B_reg(_r1: i32, _r2: i32) { trigger_ud(); } +pub unsafe fn instr_660F2B_mem(addr: i32, r: i32) { + // movntpd m128, xmm + // XXX: Aligned write or #gp + mov_r_m128(addr, r); +} + +pub unsafe fn instr_0F2C(source: u64, r: i32) { + // cvttps2pi mm, xmm/m64 + let low = f32::from_bits(source as u32); + let high = f32::from_bits((source >> 32) as u32); + write_mmx_reg64( + r, + sse_convert_with_truncation_f32_to_i32(low) as u32 as u64 + | (sse_convert_with_truncation_f32_to_i32(high) as u32 as u64) << 32, + ); + transition_fpu_to_mmx(); +} +#[no_mangle] +pub unsafe fn instr_0F2C_mem(addr: i32, r: i32) { + instr_0F2C(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F2C_reg(r1: i32, r2: i32) { instr_0F2C(read_xmm64s(r1), r2); } + +pub unsafe fn instr_660F2C(source: reg128, r: i32) { + // cvttpd2pi mm, xmm/m128 + write_mmx_reg64( + r, + sse_convert_with_truncation_f64_to_i32(source.f64[0]) as u32 as u64 + | (sse_convert_with_truncation_f64_to_i32(source.f64[1]) as u32 as u64) << 32, + ); + transition_fpu_to_mmx(); +} +#[no_mangle] +pub unsafe fn instr_660F2C_mem(addr: i32, r: i32) { + instr_660F2C(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F2C_reg(r1: i32, r2: i32) { instr_660F2C(read_xmm128s(r1), r2); } + +pub unsafe fn instr_F20F2C(source: u64, r: i32) { + // cvttsd2si r32, xmm/m64 + let source = f64::from_bits(source); + write_reg32(r, sse_convert_with_truncation_f64_to_i32(source)); +} +#[no_mangle] +pub unsafe fn instr_F20F2C_reg(r1: i32, r2: i32) { instr_F20F2C(read_xmm64s(r1), r2); } +#[no_mangle] +pub unsafe fn instr_F20F2C_mem(addr: i32, r: i32) { + instr_F20F2C(return_on_pagefault!(safe_read64s(addr)), r); +} + +pub unsafe fn instr_F30F2C(source: f32, r: i32) { + // cvttss2si + write_reg32(r, sse_convert_with_truncation_f32_to_i32(source)); +} +#[no_mangle] +pub unsafe fn instr_F30F2C_mem(addr: i32, r: i32) { + instr_F30F2C(return_on_pagefault!(safe_read_f32(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F2C_reg(r1: i32, r2: i32) { instr_F30F2C(read_xmm_f32(r1), r2); } + +pub unsafe fn instr_0F2D(source: u64, r: i32) { + // cvtps2pi mm, xmm/m64 + let source: [f32; 2] = std::mem::transmute(source); + let result = [ + sse_convert_f32_to_i32(source[0]), + sse_convert_f32_to_i32(source[1]), + ]; + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +#[no_mangle] +pub unsafe fn instr_0F2D_reg(r1: i32, r2: i32) { instr_0F2D(read_xmm64s(r1), r2); } +#[no_mangle] +pub unsafe fn instr_0F2D_mem(addr: i32, r: i32) { + instr_0F2D(return_on_pagefault!(safe_read64s(addr)), r); +} + +pub unsafe fn instr_660F2D(source: reg128, r: i32) { + // cvtpd2pi mm, xmm/m128 + let result = [ + sse_convert_f64_to_i32(source.f64[0]), + sse_convert_f64_to_i32(source.f64[1]), + ]; + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +#[no_mangle] +pub unsafe fn instr_660F2D_reg(r1: i32, r2: i32) { instr_660F2D(read_xmm128s(r1), r2); } +#[no_mangle] +pub unsafe fn instr_660F2D_mem(addr: i32, r: i32) { + instr_660F2D(return_on_pagefault!(safe_read128s(addr)), r); +} +pub unsafe fn instr_F20F2D(source: u64, r: i32) { + // cvtsd2si r32, xmm/m64 + write_reg32(r, sse_convert_f64_to_i32(f64::from_bits(source))); +} +pub unsafe fn instr_F20F2D_reg(r1: i32, r2: i32) { instr_F20F2D(read_xmm64s(r1), r2); } +pub unsafe fn instr_F20F2D_mem(addr: i32, r: i32) { + instr_F20F2D(return_on_pagefault!(safe_read64s(addr)), r); +} +pub unsafe fn instr_F30F2D(source: f32, r: i32) { + // cvtss2si r32, xmm1/m32 + write_reg32(r, sse_convert_f32_to_i32(source)); +} +pub unsafe fn instr_F30F2D_reg(r1: i32, r2: i32) { instr_F30F2D(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F2D_mem(addr: i32, r: i32) { + instr_F30F2D(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F2E(source: f32, r: i32) { + // ucomiss xmm1, xmm2/m32 + let destination = read_xmm_f32(r); + *flags_changed = 0; + *flags &= !FLAGS_ALL; + if destination == source { + *flags |= FLAG_ZERO + } + else if destination < source { + *flags |= FLAG_CARRY + } + else if destination > source { + // all flags cleared + } + else { + // TODO: Signal on SNaN + *flags |= FLAG_ZERO | FLAG_PARITY | FLAG_CARRY + } +} +pub unsafe fn instr_0F2E_reg(r1: i32, r2: i32) { instr_0F2E(read_xmm_f32(r1), r2) } +pub unsafe fn instr_0F2E_mem(addr: i32, r: i32) { + instr_0F2E(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_660F2E(source: u64, r: i32) { + // ucomisd xmm1, xmm2/m64 + let destination = f64::from_bits(read_xmm64s(r)); + let source = f64::from_bits(source); + *flags_changed = 0; + *flags &= !FLAGS_ALL; + if destination == source { + *flags |= FLAG_ZERO + } + else if destination < source { + *flags |= FLAG_CARRY + } + else if destination > source { + // all flags cleared + } + else { + // TODO: Signal on SNaN + *flags |= FLAG_ZERO | FLAG_PARITY | FLAG_CARRY + } +} +pub unsafe fn instr_660F2E_reg(r1: i32, r: i32) { instr_660F2E(read_xmm64s(r1), r); } +pub unsafe fn instr_660F2E_mem(addr: i32, r: i32) { + instr_660F2E(return_on_pagefault!(safe_read64s(addr)), r) +} + +#[no_mangle] +pub unsafe fn instr_0F2F(source: f32, r: i32) { + // comiss xmm1, xmm2/m32 + let destination = read_xmm_f32(r); + *flags_changed = 0; + *flags &= !FLAGS_ALL; + if destination == source { + *flags |= FLAG_ZERO + } + else if destination < source { + *flags |= FLAG_CARRY + } + else if destination > source { + // all flags cleared + } + else { + // TODO: Signal on SNaN or QNaN + *flags |= FLAG_ZERO | FLAG_PARITY | FLAG_CARRY + } +} +pub unsafe fn instr_0F2F_reg(r1: i32, r2: i32) { instr_0F2F(read_xmm_f32(r1), r2) } +pub unsafe fn instr_0F2F_mem(addr: i32, r: i32) { + instr_0F2F(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_660F2F(source: u64, r: i32) { + // comisd xmm1, xmm2/m64 + let destination = f64::from_bits(read_xmm64s(r)); + let source = f64::from_bits(source); + *flags_changed = 0; + *flags &= !FLAGS_ALL; + if destination == source { + *flags |= FLAG_ZERO + } + else if destination < source { + *flags |= FLAG_CARRY + } + else if destination > source { + // all flags cleared + } + else { + // TODO: Signal on SNaN or QNaN + *flags |= FLAG_ZERO | FLAG_PARITY | FLAG_CARRY + } +} +pub unsafe fn instr_660F2F_reg(r1: i32, r: i32) { instr_660F2F(read_xmm64s(r1), r); } +pub unsafe fn instr_660F2F_mem(addr: i32, r: i32) { + instr_660F2F(return_on_pagefault!(safe_read64s(addr)), r) +} + +#[no_mangle] +pub unsafe fn instr_0F30() { + // wrmsr - write maschine specific register + if 0 != *cpl { + trigger_gp(0); + return; + } + + let index = read_reg32(ECX); + let low = read_reg32(EAX); + let high = read_reg32(EDX); + + if index != IA32_SYSENTER_ESP { + dbg_log!("wrmsr ecx={:x} data={:x}:{:x}", index, high, low); + } + + match index { + IA32_SYSENTER_CS => *sysenter_cs = low & 0xFFFF, + IA32_SYSENTER_EIP => *sysenter_eip = low, + IA32_SYSENTER_ESP => *sysenter_esp = low, + IA32_FEAT_CTL => {}, // linux 5.x + MSR_TEST_CTRL => {}, // linux 5.x + IA32_APIC_BASE => { + dbg_assert!( + high == 0, + ("Changing APIC address (high 32 bits) not supported") + ); + let address = low & !(IA32_APIC_BASE_BSP | IA32_APIC_BASE_EXTD | IA32_APIC_BASE_EN); + dbg_assert!( + address == APIC_ADDRESS, + ("Changing APIC address not supported") + ); + dbg_assert!(low & IA32_APIC_BASE_EXTD == 0, "x2apic not supported"); + *apic_enabled = low & IA32_APIC_BASE_EN == IA32_APIC_BASE_EN + }, + IA32_TIME_STAMP_COUNTER => set_tsc(low as u32, high as u32), + IA32_BIOS_SIGN_ID => {}, + MISC_FEATURE_ENABLES => { + // Linux 4, see: https://patchwork.kernel.org/patch/9528279/ + }, + IA32_MISC_ENABLE => { + // Enable Misc. Processor Features + }, + IA32_MCG_CAP => {}, // netbsd + IA32_KERNEL_GS_BASE => { + // Only used in 64 bit mode (by SWAPGS), but set by kvm-unit-test + dbg_log!("GS Base written"); + }, + IA32_PAT => {}, + IA32_SPEC_CTRL => {}, // linux 5.19 + IA32_TSX_CTRL => {}, // linux 5.19 + MSR_TSX_FORCE_ABORT => {}, // linux 5.19 + IA32_MCU_OPT_CTRL => {}, // linux 5.19 + _ => { + dbg_log!("Unknown msr: {:x}", index); + dbg_assert!(false); + }, + } +} + +pub unsafe fn instr_0F31() { + // rdtsc - read timestamp counter + if 0 == *cpl || 0 == *cr.offset(4) & CR4_TSD { + let tsc = read_tsc(); + write_reg32(EAX, tsc as i32); + write_reg32(EDX, (tsc >> 32) as i32); + if false { + dbg_log!("rdtsc edx:eax={:x}:{:x}", read_reg32(EDX), read_reg32(EAX)); + } + } + else { + trigger_gp(0); + }; +} + +#[no_mangle] +pub unsafe fn instr_0F32() { + // rdmsr - read maschine specific register + if 0 != *cpl { + trigger_gp(0); + return; + } + + let index = read_reg32(ECX); + dbg_log!("rdmsr ecx={:x}", index); + + let mut low: i32 = 0; + let mut high: i32 = 0; + + match index { + IA32_SYSENTER_CS => low = *sysenter_cs, + IA32_SYSENTER_EIP => low = *sysenter_eip, + IA32_SYSENTER_ESP => low = *sysenter_esp, + IA32_TIME_STAMP_COUNTER => { + let tsc = read_tsc(); + low = tsc as i32; + high = (tsc >> 32) as i32 + }, + IA32_FEAT_CTL => {}, // linux 5.x + MSR_TEST_CTRL => {}, // linux 5.x + IA32_PLATFORM_ID => {}, + IA32_APIC_BASE => { + if *acpi_enabled { + low = APIC_ADDRESS; + if *apic_enabled { + low |= IA32_APIC_BASE_EN + } + } + }, + IA32_BIOS_SIGN_ID => {}, + MSR_PLATFORM_INFO => low = 1 << 8, + MISC_FEATURE_ENABLES => {}, + IA32_MISC_ENABLE => { + // Enable Misc. Processor Features + low = 1 << 0; // fast string + }, + IA32_RTIT_CTL => { + // linux4 + }, + MSR_SMI_COUNT => {}, + IA32_MCG_CAP => { + // netbsd + }, + IA32_PAT => {}, + MSR_PKG_C2_RESIDENCY => {}, + IA32_SPEC_CTRL => {}, // linux 5.19 + IA32_TSX_CTRL => {}, // linux 5.19 + MSR_TSX_FORCE_ABORT => {}, // linux 5.19 + IA32_MCU_OPT_CTRL => {}, // linux 5.19 + MSR_AMD64_LS_CFG => {}, // linux 5.19 + _ => { + dbg_log!("Unknown msr: {:x}", index); + dbg_assert!(false); + }, + } + + write_reg32(EAX, low); + write_reg32(EDX, high); +} +#[no_mangle] +pub unsafe fn instr_0F33() { + // rdpmc + undefined_instruction(); +} +#[no_mangle] +pub unsafe fn instr_0F34() { + // sysenter + let seg = *sysenter_cs & 0xFFFC; + if !*protected_mode || seg == 0 { + trigger_gp(0); + return; + } + else { + *flags &= !FLAG_VM & !FLAG_INTERRUPT; + *instruction_pointer = *sysenter_eip; + write_reg32(ESP, *sysenter_esp); + *sreg.offset(CS as isize) = seg as u16; + *segment_is_null.offset(CS as isize) = false; + *segment_limits.offset(CS as isize) = -1i32 as u32; + *segment_offsets.offset(CS as isize) = 0; + update_cs_size(true); + *cpl = 0; + cpl_changed(); + *sreg.offset(SS as isize) = (seg + 8) as u16; + *segment_is_null.offset(SS as isize) = false; + *segment_limits.offset(SS as isize) = -1i32 as u32; + *segment_offsets.offset(SS as isize) = 0; + *stack_size_32 = true; + update_state_flags(); + return; + }; +} +#[no_mangle] +pub unsafe fn instr_0F35() { + // sysexit + let seg = *sysenter_cs & 0xFFFC; + if !*protected_mode || 0 != *cpl || seg == 0 { + trigger_gp(0); + return; + } + else { + *instruction_pointer = read_reg32(EDX); + write_reg32(ESP, read_reg32(ECX)); + *sreg.offset(CS as isize) = (seg + 16 | 3) as u16; + *segment_is_null.offset(CS as isize) = false; + *segment_limits.offset(CS as isize) = -1i32 as u32; + *segment_offsets.offset(CS as isize) = 0; + update_cs_size(true); + *cpl = 3; + cpl_changed(); + *sreg.offset(SS as isize) = (seg + 24 | 3) as u16; + *segment_is_null.offset(SS as isize) = false; + *segment_limits.offset(SS as isize) = -1i32 as u32; + *segment_offsets.offset(SS as isize) = 0; + *stack_size_32 = true; + update_state_flags(); + return; + }; +} +#[no_mangle] +pub unsafe fn instr_0F36() { undefined_instruction(); } +#[no_mangle] +pub unsafe fn instr_0F37() { + // getsec + undefined_instruction(); +} +#[no_mangle] +pub unsafe fn instr_0F38() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F39() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F3A() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F3B() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F3C() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F3D() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F3E() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F3F() { unimplemented_sse(); } + +pub unsafe fn instr16_0F40_mem(addr: i32, r: i32) { + cmovcc16(test_o(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F40_reg(r1: i32, r: i32) { cmovcc16(test_o(), read_reg16(r1), r); } +pub unsafe fn instr32_0F40_mem(addr: i32, r: i32) { + cmovcc32(test_o(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F40_reg(r1: i32, r: i32) { cmovcc32(test_o(), read_reg32(r1), r); } +pub unsafe fn instr16_0F41_mem(addr: i32, r: i32) { + cmovcc16(!test_o(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F41_reg(r1: i32, r: i32) { cmovcc16(!test_o(), read_reg16(r1), r); } +pub unsafe fn instr32_0F41_mem(addr: i32, r: i32) { + cmovcc32(!test_o(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F41_reg(r1: i32, r: i32) { cmovcc32(!test_o(), read_reg32(r1), r); } +pub unsafe fn instr16_0F42_mem(addr: i32, r: i32) { + cmovcc16(test_b(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F42_reg(r1: i32, r: i32) { cmovcc16(test_b(), read_reg16(r1), r); } +pub unsafe fn instr32_0F42_mem(addr: i32, r: i32) { + cmovcc32(test_b(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F42_reg(r1: i32, r: i32) { cmovcc32(test_b(), read_reg32(r1), r); } +pub unsafe fn instr16_0F43_mem(addr: i32, r: i32) { + cmovcc16(!test_b(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F43_reg(r1: i32, r: i32) { cmovcc16(!test_b(), read_reg16(r1), r); } +pub unsafe fn instr32_0F43_mem(addr: i32, r: i32) { + cmovcc32(!test_b(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F43_reg(r1: i32, r: i32) { cmovcc32(!test_b(), read_reg32(r1), r); } +pub unsafe fn instr16_0F44_mem(addr: i32, r: i32) { + cmovcc16(test_z(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F44_reg(r1: i32, r: i32) { cmovcc16(test_z(), read_reg16(r1), r); } +pub unsafe fn instr32_0F44_mem(addr: i32, r: i32) { + cmovcc32(test_z(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F44_reg(r1: i32, r: i32) { cmovcc32(test_z(), read_reg32(r1), r); } +pub unsafe fn instr16_0F45_mem(addr: i32, r: i32) { + cmovcc16(!test_z(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F45_reg(r1: i32, r: i32) { cmovcc16(!test_z(), read_reg16(r1), r); } +pub unsafe fn instr32_0F45_mem(addr: i32, r: i32) { + cmovcc32(!test_z(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F45_reg(r1: i32, r: i32) { cmovcc32(!test_z(), read_reg32(r1), r); } +pub unsafe fn instr16_0F46_mem(addr: i32, r: i32) { + cmovcc16(test_be(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F46_reg(r1: i32, r: i32) { cmovcc16(test_be(), read_reg16(r1), r); } +pub unsafe fn instr32_0F46_mem(addr: i32, r: i32) { + cmovcc32(test_be(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F46_reg(r1: i32, r: i32) { cmovcc32(test_be(), read_reg32(r1), r); } +pub unsafe fn instr16_0F47_mem(addr: i32, r: i32) { + cmovcc16(!test_be(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F47_reg(r1: i32, r: i32) { cmovcc16(!test_be(), read_reg16(r1), r); } +pub unsafe fn instr32_0F47_mem(addr: i32, r: i32) { + cmovcc32(!test_be(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F47_reg(r1: i32, r: i32) { cmovcc32(!test_be(), read_reg32(r1), r); } +pub unsafe fn instr16_0F48_mem(addr: i32, r: i32) { + cmovcc16(test_s(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F48_reg(r1: i32, r: i32) { cmovcc16(test_s(), read_reg16(r1), r); } +pub unsafe fn instr32_0F48_mem(addr: i32, r: i32) { + cmovcc32(test_s(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F48_reg(r1: i32, r: i32) { cmovcc32(test_s(), read_reg32(r1), r); } +pub unsafe fn instr16_0F49_mem(addr: i32, r: i32) { + cmovcc16(!test_s(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F49_reg(r1: i32, r: i32) { cmovcc16(!test_s(), read_reg16(r1), r); } +pub unsafe fn instr32_0F49_mem(addr: i32, r: i32) { + cmovcc32(!test_s(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F49_reg(r1: i32, r: i32) { cmovcc32(!test_s(), read_reg32(r1), r); } +pub unsafe fn instr16_0F4A_mem(addr: i32, r: i32) { + cmovcc16(test_p(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F4A_reg(r1: i32, r: i32) { cmovcc16(test_p(), read_reg16(r1), r); } +pub unsafe fn instr32_0F4A_mem(addr: i32, r: i32) { + cmovcc32(test_p(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F4A_reg(r1: i32, r: i32) { cmovcc32(test_p(), read_reg32(r1), r); } +pub unsafe fn instr16_0F4B_mem(addr: i32, r: i32) { + cmovcc16(!test_p(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F4B_reg(r1: i32, r: i32) { cmovcc16(!test_p(), read_reg16(r1), r); } +pub unsafe fn instr32_0F4B_mem(addr: i32, r: i32) { + cmovcc32(!test_p(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F4B_reg(r1: i32, r: i32) { cmovcc32(!test_p(), read_reg32(r1), r); } +pub unsafe fn instr16_0F4C_mem(addr: i32, r: i32) { + cmovcc16(test_l(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F4C_reg(r1: i32, r: i32) { cmovcc16(test_l(), read_reg16(r1), r); } +pub unsafe fn instr32_0F4C_mem(addr: i32, r: i32) { + cmovcc32(test_l(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F4C_reg(r1: i32, r: i32) { cmovcc32(test_l(), read_reg32(r1), r); } +pub unsafe fn instr16_0F4D_mem(addr: i32, r: i32) { + cmovcc16(!test_l(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F4D_reg(r1: i32, r: i32) { cmovcc16(!test_l(), read_reg16(r1), r); } +pub unsafe fn instr32_0F4D_mem(addr: i32, r: i32) { + cmovcc32(!test_l(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F4D_reg(r1: i32, r: i32) { cmovcc32(!test_l(), read_reg32(r1), r); } +pub unsafe fn instr16_0F4E_mem(addr: i32, r: i32) { + cmovcc16(test_le(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F4E_reg(r1: i32, r: i32) { cmovcc16(test_le(), read_reg16(r1), r); } +pub unsafe fn instr32_0F4E_mem(addr: i32, r: i32) { + cmovcc32(test_le(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F4E_reg(r1: i32, r: i32) { cmovcc32(test_le(), read_reg32(r1), r); } +pub unsafe fn instr16_0F4F_mem(addr: i32, r: i32) { + cmovcc16(!test_le(), return_on_pagefault!(safe_read16(addr)), r); +} +pub unsafe fn instr16_0F4F_reg(r1: i32, r: i32) { cmovcc16(!test_le(), read_reg16(r1), r); } +pub unsafe fn instr32_0F4F_mem(addr: i32, r: i32) { + cmovcc32(!test_le(), return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr32_0F4F_reg(r1: i32, r: i32) { cmovcc32(!test_le(), read_reg32(r1), r); } + +#[no_mangle] +pub unsafe fn instr_0F50_reg(r1: i32, r2: i32) { + // movmskps r, xmm + let source = read_xmm128s(r1); + let data = (source.u32[0] >> 31 + | source.u32[1] >> 31 << 1 + | source.u32[2] >> 31 << 2 + | source.u32[3] >> 31 << 3) as i32; + write_reg32(r2, data); +} +#[no_mangle] +pub unsafe fn instr_0F50_mem(_addr: i32, _r1: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_660F50_reg(r1: i32, r2: i32) { + // movmskpd r, xmm + let source = read_xmm128s(r1); + let data = (source.u32[1] >> 31 | source.u32[3] >> 31 << 1) as i32; + write_reg32(r2, data); +} +#[no_mangle] +pub unsafe fn instr_660F50_mem(_addr: i32, _r1: i32) { trigger_ud(); } + +#[no_mangle] +pub unsafe fn instr_0F51(source: reg128, r: i32) { + // sqrtps xmm, xmm/mem128 + // XXX: Should round according to round control + let result = reg128 { + f32: [ + source.f32[0].sqrt(), + source.f32[1].sqrt(), + source.f32[2].sqrt(), + source.f32[3].sqrt(), + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F51_reg(r1: i32, r2: i32) { instr_0F51(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F51_mem(addr: i32, r: i32) { + instr_0F51(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F51(source: reg128, r: i32) { + // sqrtpd xmm, xmm/mem128 + // XXX: Should round according to round control + let result = reg128 { + f64: [source.f64[0].sqrt(), source.f64[1].sqrt()], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F51_reg(r1: i32, r2: i32) { instr_660F51(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F51_mem(addr: i32, r: i32) { + instr_660F51(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F20F51(source: u64, r: i32) { + // sqrtsd xmm, xmm/mem64 + // XXX: Should round according to round control + write_xmm_f64(r, f64::from_bits(source).sqrt()); +} +pub unsafe fn instr_F20F51_reg(r1: i32, r2: i32) { instr_F20F51(read_xmm64s(r1), r2); } +pub unsafe fn instr_F20F51_mem(addr: i32, r: i32) { + instr_F20F51(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F51(source: f32, r: i32) { + // sqrtss xmm, xmm/mem32 + // XXX: Should round according to round control + write_xmm_f32(r, source.sqrt()); +} +pub unsafe fn instr_F30F51_reg(r1: i32, r2: i32) { instr_F30F51(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F51_mem(addr: i32, r: i32) { + instr_F30F51(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F52(source: reg128, r: i32) { + // rcpps xmm1, xmm2/m128 + let result = reg128 { + f32: [ + 1.0 / source.f32[0].sqrt(), + 1.0 / source.f32[1].sqrt(), + 1.0 / source.f32[2].sqrt(), + 1.0 / source.f32[3].sqrt(), + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F52_reg(r1: i32, r2: i32) { instr_0F52(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F52_mem(addr: i32, r: i32) { + instr_0F52(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F52(source: f32, r: i32) { + // rsqrtss xmm1, xmm2/m32 + write_xmm_f32(r, 1.0 / source.sqrt()); +} +pub unsafe fn instr_F30F52_reg(r1: i32, r2: i32) { instr_F30F52(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F52_mem(addr: i32, r: i32) { + instr_F30F52(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F53(source: reg128, r: i32) { + // rcpps xmm, xmm/m128 + let result = reg128 { + f32: [ + 1.0 / source.f32[0], + 1.0 / source.f32[1], + 1.0 / source.f32[2], + 1.0 / source.f32[3], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F53_reg(r1: i32, r2: i32) { instr_0F53(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F53_mem(addr: i32, r: i32) { + instr_0F53(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F53(source: f32, r: i32) { + // rcpss xmm, xmm/m32 + write_xmm_f32(r, 1.0 / source); +} +pub unsafe fn instr_F30F53_reg(r1: i32, r2: i32) { instr_F30F53(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F53_mem(addr: i32, r: i32) { + instr_F30F53(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F54(source: reg128, r: i32) { + // andps xmm, xmm/mem128 + // XXX: Aligned access or #gp + pand_r128(source, r); +} +pub unsafe fn instr_0F54_reg(r1: i32, r2: i32) { instr_0F54(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F54_mem(addr: i32, r: i32) { + instr_0F54(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F54(source: reg128, r: i32) { + // andpd xmm, xmm/mem128 + // XXX: Aligned access or #gp + pand_r128(source, r); +} +pub unsafe fn instr_660F54_reg(r1: i32, r2: i32) { instr_660F54(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F54_mem(addr: i32, r: i32) { + instr_660F54(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F55(source: reg128, r: i32) { + // andnps xmm, xmm/mem128 + // XXX: Aligned access or #gp + pandn_r128(source, r); +} +pub unsafe fn instr_0F55_reg(r1: i32, r2: i32) { instr_0F55(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F55_mem(addr: i32, r: i32) { + instr_0F55(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F55(source: reg128, r: i32) { + // andnpd xmm, xmm/mem128 + // XXX: Aligned access or #gp + pandn_r128(source, r); +} +pub unsafe fn instr_660F55_reg(r1: i32, r2: i32) { instr_660F55(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F55_mem(addr: i32, r: i32) { + instr_660F55(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F56(source: reg128, r: i32) { + // orps xmm, xmm/mem128 + // XXX: Aligned access or #gp + por_r128(source, r); +} +pub unsafe fn instr_0F56_reg(r1: i32, r2: i32) { instr_0F56(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F56_mem(addr: i32, r: i32) { + instr_0F56(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F56(source: reg128, r: i32) { + // orpd xmm, xmm/mem128 + // XXX: Aligned access or #gp + por_r128(source, r); +} +pub unsafe fn instr_660F56_reg(r1: i32, r2: i32) { instr_660F56(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F56_mem(addr: i32, r: i32) { + instr_660F56(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F57(source: reg128, r: i32) { + // xorps xmm, xmm/mem128 + // XXX: Aligned access or #gp + pxor_r128(source, r); +} +pub unsafe fn instr_0F57_reg(r1: i32, r2: i32) { instr_0F57(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F57_mem(addr: i32, r: i32) { + instr_0F57(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F57(source: reg128, r: i32) { + // xorpd xmm, xmm/mem128 + // XXX: Aligned access or #gp + pxor_r128(source, r); +} +pub unsafe fn instr_660F57_reg(r1: i32, r2: i32) { instr_660F57(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F57_mem(addr: i32, r: i32) { + instr_660F57(return_on_pagefault!(safe_read128s(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F58(source: reg128, r: i32) { + // addps xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f32: [ + source.f32[0] + destination.f32[0], + source.f32[1] + destination.f32[1], + source.f32[2] + destination.f32[2], + source.f32[3] + destination.f32[3], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F58_reg(r1: i32, r2: i32) { instr_0F58(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F58_mem(addr: i32, r: i32) { + instr_0F58(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F58(source: reg128, r: i32) { + // addpd xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f64: [ + source.f64[0] + destination.f64[0], + source.f64[1] + destination.f64[1], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F58_reg(r1: i32, r2: i32) { instr_660F58(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F58_mem(addr: i32, r: i32) { + instr_660F58(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F20F58(source: u64, r: i32) { + // addsd xmm, xmm/mem64 + let destination = read_xmm64s(r); + write_xmm_f64(r, f64::from_bits(source) + f64::from_bits(destination)); +} +pub unsafe fn instr_F20F58_reg(r1: i32, r2: i32) { instr_F20F58(read_xmm64s(r1), r2); } +pub unsafe fn instr_F20F58_mem(addr: i32, r: i32) { + instr_F20F58(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F58(source: f32, r: i32) { + // addss xmm, xmm/mem32 + let destination = read_xmm_f32(r); + let result = source + destination; + write_xmm_f32(r, result); +} +pub unsafe fn instr_F30F58_reg(r1: i32, r2: i32) { instr_F30F58(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F58_mem(addr: i32, r: i32) { + instr_F30F58(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F59(source: reg128, r: i32) { + // mulps xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f32: [ + source.f32[0] * destination.f32[0], + source.f32[1] * destination.f32[1], + source.f32[2] * destination.f32[2], + source.f32[3] * destination.f32[3], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F59_reg(r1: i32, r2: i32) { instr_0F59(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F59_mem(addr: i32, r: i32) { + instr_0F59(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F59(source: reg128, r: i32) { + // mulpd xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f64: [ + source.f64[0] * destination.f64[0], + source.f64[1] * destination.f64[1], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F59_reg(r1: i32, r2: i32) { instr_660F59(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F59_mem(addr: i32, r: i32) { + instr_660F59(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F20F59(source: u64, r: i32) { + // mulsd xmm, xmm/mem64 + let destination = read_xmm64s(r); + write_xmm_f64(r, f64::from_bits(source) * f64::from_bits(destination)); +} +pub unsafe fn instr_F20F59_reg(r1: i32, r2: i32) { instr_F20F59(read_xmm64s(r1), r2); } +pub unsafe fn instr_F20F59_mem(addr: i32, r: i32) { + instr_F20F59(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F59(source: f32, r: i32) { + // mulss xmm, xmm/mem32 + let destination = read_xmm_f32(r); + let result = source * destination; + write_xmm_f32(r, result); +} +pub unsafe fn instr_F30F59_reg(r1: i32, r2: i32) { instr_F30F59(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F59_mem(addr: i32, r: i32) { + instr_F30F59(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F5A(source: u64, r: i32) { + // cvtps2pd xmm1, xmm2/m64 + let source: [f32; 2] = std::mem::transmute(source); + let result = reg128 { + f64: [source[0] as f64, source[1] as f64], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F5A_reg(r1: i32, r2: i32) { instr_0F5A(read_xmm64s(r1), r2); } +pub unsafe fn instr_0F5A_mem(addr: i32, r: i32) { + instr_0F5A(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F5A(source: reg128, r: i32) { + // cvtpd2ps xmm1, xmm2/m128 + let result = reg128 { + // XXX: These conversions are lossy and should round according to the round control + f32: [source.f64[0] as f32, source.f64[1] as f32, 0., 0.], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F5A_reg(r1: i32, r2: i32) { instr_660F5A(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F5A_mem(addr: i32, r: i32) { + instr_660F5A(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F20F5A(source: u64, r: i32) { + // cvtsd2ss xmm1, xmm2/m64 + // XXX: This conversions is lossy and should round according to the round control + write_xmm_f32(r, f64::from_bits(source) as f32); +} +pub unsafe fn instr_F20F5A_reg(r1: i32, r2: i32) { instr_F20F5A(read_xmm64s(r1), r2); } +pub unsafe fn instr_F20F5A_mem(addr: i32, r: i32) { + instr_F20F5A(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F5A(source: f32, r: i32) { + // cvtss2sd xmm1, xmm2/m32 + write_xmm_f64(r, source as f64); +} +pub unsafe fn instr_F30F5A_reg(r1: i32, r2: i32) { instr_F30F5A(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F5A_mem(addr: i32, r: i32) { + instr_F30F5A(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F5B(source: reg128, r: i32) { + // cvtdq2ps xmm1, xmm2/m128 + // XXX: Should round according to round control + let result = reg128 { + f32: [ + // XXX: Precision exception + source.i32[0] as f32, + source.i32[1] as f32, + source.i32[2] as f32, + source.i32[3] as f32, + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F5B_reg(r1: i32, r2: i32) { instr_0F5B(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F5B_mem(addr: i32, r: i32) { + instr_0F5B(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F5B(source: reg128, r: i32) { + // cvtps2dq xmm1, xmm2/m128 + let result = reg128 { + i32: [ + // XXX: Precision exception + sse_convert_f32_to_i32(source.f32[0]), + sse_convert_f32_to_i32(source.f32[1]), + sse_convert_f32_to_i32(source.f32[2]), + sse_convert_f32_to_i32(source.f32[3]), + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F5B_reg(r1: i32, r2: i32) { instr_660F5B(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F5B_mem(addr: i32, r: i32) { + instr_660F5B(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F5B(source: reg128, r: i32) { + // cvttps2dq xmm1, xmm2/m128 + let result = reg128 { + i32: [ + sse_convert_with_truncation_f32_to_i32(source.f32[0]), + sse_convert_with_truncation_f32_to_i32(source.f32[1]), + sse_convert_with_truncation_f32_to_i32(source.f32[2]), + sse_convert_with_truncation_f32_to_i32(source.f32[3]), + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_F30F5B_reg(r1: i32, r2: i32) { instr_F30F5B(read_xmm128s(r1), r2); } +pub unsafe fn instr_F30F5B_mem(addr: i32, r: i32) { + instr_F30F5B(return_on_pagefault!(safe_read128s(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F5C(source: reg128, r: i32) { + // subps xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f32: [ + destination.f32[0] - source.f32[0], + destination.f32[1] - source.f32[1], + destination.f32[2] - source.f32[2], + destination.f32[3] - source.f32[3], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F5C_reg(r1: i32, r2: i32) { instr_0F5C(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F5C_mem(addr: i32, r: i32) { + instr_0F5C(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F5C(source: reg128, r: i32) { + // subpd xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f64: [ + destination.f64[0] - source.f64[0], + destination.f64[1] - source.f64[1], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F5C_reg(r1: i32, r2: i32) { instr_660F5C(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F5C_mem(addr: i32, r: i32) { + instr_660F5C(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F20F5C(source: u64, r: i32) { + // subsd xmm, xmm/mem64 + let destination = read_xmm64s(r); + write_xmm_f64(r, f64::from_bits(destination) - f64::from_bits(source)); +} +pub unsafe fn instr_F20F5C_reg(r1: i32, r2: i32) { instr_F20F5C(read_xmm64s(r1), r2); } +pub unsafe fn instr_F20F5C_mem(addr: i32, r: i32) { + instr_F20F5C(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F5C(source: f32, r: i32) { + // subss xmm, xmm/mem32 + let destination = read_xmm_f32(r); + let result = destination - source; + write_xmm_f32(r, result); +} +pub unsafe fn instr_F30F5C_reg(r1: i32, r2: i32) { instr_F30F5C(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F5C_mem(addr: i32, r: i32) { + instr_F30F5C(return_on_pagefault!(safe_read_f32(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F5D(source: reg128, r: i32) { + // minps xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f32: [ + sse_min(destination.f32[0] as f64, source.f32[0] as f64) as f32, + sse_min(destination.f32[1] as f64, source.f32[1] as f64) as f32, + sse_min(destination.f32[2] as f64, source.f32[2] as f64) as f32, + sse_min(destination.f32[3] as f64, source.f32[3] as f64) as f32, + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F5D_reg(r1: i32, r2: i32) { instr_0F5D(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F5D_mem(addr: i32, r: i32) { + instr_0F5D(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F5D(source: reg128, r: i32) { + // minpd xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f64: [ + sse_min(destination.f64[0], source.f64[0]), + sse_min(destination.f64[1], source.f64[1]), + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F5D_reg(r1: i32, r2: i32) { instr_660F5D(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F5D_mem(addr: i32, r: i32) { + instr_660F5D(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F20F5D(source: u64, r: i32) { + // minsd xmm, xmm/mem64 + let destination = read_xmm64s(r); + write_xmm_f64( + r, + sse_min(f64::from_bits(destination), f64::from_bits(source)), + ); +} +pub unsafe fn instr_F20F5D_reg(r1: i32, r2: i32) { instr_F20F5D(read_xmm64s(r1), r2); } +pub unsafe fn instr_F20F5D_mem(addr: i32, r: i32) { + instr_F20F5D(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F5D(source: f32, r: i32) { + // minss xmm, xmm/mem32 + let destination = read_xmm_f32(r); + let result = sse_min(destination as f64, source as f64) as f32; + write_xmm_f32(r, result); +} +pub unsafe fn instr_F30F5D_reg(r1: i32, r2: i32) { instr_F30F5D(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F5D_mem(addr: i32, r: i32) { + instr_F30F5D(return_on_pagefault!(safe_read_f32(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F5E(source: reg128, r: i32) { + // divps xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f32: [ + destination.f32[0] / source.f32[0], + destination.f32[1] / source.f32[1], + destination.f32[2] / source.f32[2], + destination.f32[3] / source.f32[3], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F5E_reg(r1: i32, r2: i32) { instr_0F5E(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F5E_mem(addr: i32, r: i32) { + instr_0F5E(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F5E(source: reg128, r: i32) { + // divpd xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f64: [ + destination.f64[0] / source.f64[0], + destination.f64[1] / source.f64[1], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F5E_reg(r1: i32, r2: i32) { instr_660F5E(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F5E_mem(addr: i32, r: i32) { + instr_660F5E(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F20F5E(source: u64, r: i32) { + // divsd xmm, xmm/mem64 + let destination = read_xmm64s(r); + write_xmm_f64(r, f64::from_bits(destination) / f64::from_bits(source)); +} +pub unsafe fn instr_F20F5E_reg(r1: i32, r2: i32) { instr_F20F5E(read_xmm64s(r1), r2); } +pub unsafe fn instr_F20F5E_mem(addr: i32, r: i32) { + instr_F20F5E(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F5E(source: f32, r: i32) { + // divss xmm, xmm/mem32 + let destination = read_xmm_f32(r); + let result = destination / source; + write_xmm_f32(r, result); +} +pub unsafe fn instr_F30F5E_reg(r1: i32, r2: i32) { instr_F30F5E(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F5E_mem(addr: i32, r: i32) { + instr_F30F5E(return_on_pagefault!(safe_read_f32(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F5F(source: reg128, r: i32) { + // maxps xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f32: [ + sse_max(destination.f32[0] as f64, source.f32[0] as f64) as f32, + sse_max(destination.f32[1] as f64, source.f32[1] as f64) as f32, + sse_max(destination.f32[2] as f64, source.f32[2] as f64) as f32, + sse_max(destination.f32[3] as f64, source.f32[3] as f64) as f32, + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0F5F_reg(r1: i32, r2: i32) { instr_0F5F(read_xmm128s(r1), r2); } +pub unsafe fn instr_0F5F_mem(addr: i32, r: i32) { + instr_0F5F(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F5F(source: reg128, r: i32) { + // maxpd xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + f64: [ + sse_max(destination.f64[0], source.f64[0]), + sse_max(destination.f64[1], source.f64[1]), + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F5F_reg(r1: i32, r2: i32) { instr_660F5F(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F5F_mem(addr: i32, r: i32) { + instr_660F5F(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F20F5F(source: u64, r: i32) { + // maxsd xmm, xmm/mem64 + let destination = read_xmm64s(r); + write_xmm_f64( + r, + sse_max(f64::from_bits(destination), f64::from_bits(source)), + ); +} +pub unsafe fn instr_F20F5F_reg(r1: i32, r2: i32) { instr_F20F5F(read_xmm64s(r1), r2); } +pub unsafe fn instr_F20F5F_mem(addr: i32, r: i32) { + instr_F20F5F(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_F30F5F(source: f32, r: i32) { + // maxss xmm, xmm/mem32 + let destination = read_xmm_f32(r); + let result = sse_max(destination as f64, source as f64) as f32; + write_xmm_f32(r, result); +} +pub unsafe fn instr_F30F5F_reg(r1: i32, r2: i32) { instr_F30F5F(read_xmm_f32(r1), r2); } +pub unsafe fn instr_F30F5F_mem(addr: i32, r: i32) { + instr_F30F5F(return_on_pagefault!(safe_read_f32(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F60(source: i32, r: i32) { + // punpcklbw mm, mm/m32 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 4] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..4 { + result[2 * i + 0] = destination[i]; + result[2 * i + 1] = source[i]; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F60_reg(r1: i32, r2: i32) { instr_0F60(read_mmx32s(r1), r2); } +pub unsafe fn instr_0F60_mem(addr: i32, r: i32) { + instr_0F60(return_on_pagefault!(safe_read32s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F60(source: reg128, r: i32) { + // punpcklbw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination: [u8; 8] = std::mem::transmute(read_xmm64s(r)); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u8[2 * i + 0] = destination[i]; + result.u8[2 * i + 1] = source.u8[i]; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F60_reg(r1: i32, r2: i32) { instr_660F60(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F60_mem(addr: i32, r: i32) { + instr_660F60(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F61(source: i32, r: i32) { + // punpcklwd mm, mm/m32 + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [u16; 2] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..2 { + result[2 * i + 0] = destination[i]; + result[2 * i + 1] = source[i]; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F61_reg(r1: i32, r2: i32) { instr_0F61(read_mmx32s(r1), r2); } +pub unsafe fn instr_0F61_mem(addr: i32, r: i32) { + instr_0F61(return_on_pagefault!(safe_read32s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F61(source: reg128, r: i32) { + // punpcklwd xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination: [u16; 4] = std::mem::transmute(read_xmm64s(r)); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..4 { + result.u16[2 * i + 0] = destination[i]; + result.u16[2 * i + 1] = source.u16[i]; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F61_reg(r1: i32, r2: i32) { instr_660F61(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F61_mem(addr: i32, r: i32) { + instr_660F61(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F62(source: i32, r: i32) { + // punpckldq mm, mm/m32 + let destination = read_mmx64s(r); + write_mmx_reg64( + r, + (destination & 0xFFFF_FFFF) | (source as u32 as u64) << 32, + ); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F62_reg(r1: i32, r2: i32) { instr_0F62(read_mmx32s(r1), r2); } +pub unsafe fn instr_0F62_mem(addr: i32, r: i32) { + instr_0F62(return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr_660F62(source: reg128, r: i32) { + // punpckldq xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + write_xmm128( + r, + destination.u32[0] as i32, + source.u32[0] as i32, + destination.u32[1] as i32, + source.u32[1] as i32, + ); +} +pub unsafe fn instr_660F62_reg(r1: i32, r2: i32) { instr_660F62(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F62_mem(addr: i32, r: i32) { + instr_660F62(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F63(source: u64, r: i32) { + // packsswb mm, mm/m64 + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [u16; 4] = std::mem::transmute(source); + let mut result: [u8; 8] = [0; 8]; + for i in 0..4 { + result[i + 0] = saturate_sw_to_sb(destination[i] as i32); + result[i + 4] = saturate_sw_to_sb(source[i] as i32); + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F63_reg(r1: i32, r2: i32) { instr_0F63(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F63_mem(addr: i32, r: i32) { + instr_0F63(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F63(source: reg128, r: i32) { + // packsswb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u8[i + 0] = saturate_sw_to_sb(destination.u16[i] as i32); + result.u8[i + 8] = saturate_sw_to_sb(source.u16[i] as i32); + } + write_xmm_reg128(r, result) +} +pub unsafe fn instr_660F63_reg(r1: i32, r2: i32) { instr_660F63(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F63_mem(addr: i32, r: i32) { + instr_660F63(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F64(source: u64, r: i32) { + // pcmpgtb mm, mm/m64 + let destination: [i8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [i8; 8] = std::mem::transmute(source); + let mut result: [u8; 8] = [0; 8]; + for i in 0..8 { + result[i] = if destination[i] > source[i] { 255 } else { 0 }; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F64_reg(r1: i32, r2: i32) { instr_0F64(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F64_mem(addr: i32, r: i32) { + instr_0F64(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F64(source: reg128, r: i32) { + // pcmpgtb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.u8[i] = if destination.i8[i] as i32 > source.i8[i] as i32 { 255 } else { 0 }; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F64_reg(r1: i32, r2: i32) { instr_660F64(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F64_mem(addr: i32, r: i32) { + instr_660F64(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F65(source: u64, r: i32) { + // pcmpgtw mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mut result: [u16; 4] = [0; 4]; + for i in 0..4 { + result[i] = if destination[i] > source[i] { 0xFFFF } else { 0 } + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F65_reg(r1: i32, r2: i32) { instr_0F65(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F65_mem(addr: i32, r: i32) { + instr_0F65(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F65(source: reg128, r: i32) { + // pcmpgtw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = if destination.i16[i] > source.i16[i] { 0xFFFF } else { 0 }; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F65_reg(r1: i32, r2: i32) { instr_660F65(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F65_mem(addr: i32, r: i32) { + instr_660F65(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F66(source: u64, r: i32) { + // pcmpgtd mm, mm/m64 + let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r)); + let source: [i32; 2] = std::mem::transmute(source); + let mut result = [0; 2]; + for i in 0..2 { + result[i] = if destination[i] > source[i] { -1 } else { 0 } + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F66_reg(r1: i32, r2: i32) { instr_0F66(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F66_mem(addr: i32, r: i32) { + instr_0F66(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F66(source: reg128, r: i32) { + // pcmpgtd xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + write_xmm128( + r, + if destination.i32[0] > source.i32[0] { -1 } else { 0 }, + if destination.i32[1] > source.i32[1] { -1 } else { 0 }, + if destination.i32[2] > source.i32[2] { -1 } else { 0 }, + if destination.i32[3] > source.i32[3] { -1 } else { 0 }, + ); +} +pub unsafe fn instr_660F66_reg(r1: i32, r2: i32) { instr_660F66(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F66_mem(addr: i32, r: i32) { + instr_660F66(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F67(source: u64, r: i32) { + // packuswb mm, mm/m64 + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [u16; 4] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..4 { + result[i + 0] = saturate_sw_to_ub(destination[i]); + result[i + 4] = saturate_sw_to_ub(source[i]); + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F67_reg(r1: i32, r2: i32) { instr_0F67(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F67_mem(addr: i32, r: i32) { + instr_0F67(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F67(source: reg128, r: i32) { + // packuswb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u8[i + 0] = saturate_sw_to_ub(destination.u16[i]); + result.u8[i + 8] = saturate_sw_to_ub(source.u16[i]); + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F67_reg(r1: i32, r2: i32) { instr_660F67(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F67_mem(addr: i32, r: i32) { + instr_660F67(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F68(source: u64, r: i32) { + // punpckhbw mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut result: [u8; 8] = [0; 8]; + for i in 0..4 { + result[2 * i + 0] = destination[i + 4]; + result[2 * i + 1] = source[i + 4]; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F68_reg(r1: i32, r2: i32) { instr_0F68(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F68_mem(addr: i32, r: i32) { + instr_0F68(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F68(source: reg128, r: i32) { + // punpckhbw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u8[2 * i + 0] = destination.u8[i + 8]; + result.u8[2 * i + 1] = source.u8[i + 8]; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F68_reg(r1: i32, r2: i32) { instr_660F68(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F68_mem(addr: i32, r: i32) { + instr_660F68(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F69(source: u64, r: i32) { + // punpckhwd mm, mm/m64 + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [u16; 4] = std::mem::transmute(source); + let result = [destination[2], source[2], destination[3], source[3]]; + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F69_reg(r1: i32, r2: i32) { instr_0F69(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F69_mem(addr: i32, r: i32) { + instr_0F69(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F69(source: reg128, r: i32) { + // punpckhwd xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..4 { + result.u16[2 * i + 0] = destination.u16[i + 4]; + result.u16[2 * i + 1] = source.u16[i + 4]; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F69_reg(r1: i32, r2: i32) { instr_660F69(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F69_mem(addr: i32, r: i32) { + instr_660F69(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F6A(source: u64, r: i32) { + // punpckhdq mm, mm/m64 + let destination = read_mmx64s(r); + write_mmx_reg64(r, (destination >> 32) | (source >> 32 << 32)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F6A_reg(r1: i32, r2: i32) { instr_0F6A(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F6A_mem(addr: i32, r: i32) { + instr_0F6A(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F6A(source: reg128, r: i32) { + // punpckhdq xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + write_xmm128( + r, + destination.u32[2] as i32, + source.u32[2] as i32, + destination.u32[3] as i32, + source.u32[3] as i32, + ); +} +pub unsafe fn instr_660F6A_reg(r1: i32, r2: i32) { instr_660F6A(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F6A_mem(addr: i32, r: i32) { + instr_660F6A(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F6B(source: u64, r: i32) { + // packssdw mm, mm/m64 + let destination: [u32; 2] = std::mem::transmute(read_mmx64s(r)); + let source: [u32; 2] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..2 { + result[i + 0] = saturate_sd_to_sw(destination[i]); + result[i + 2] = saturate_sd_to_sw(source[i]); + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F6B_reg(r1: i32, r2: i32) { instr_0F6B(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F6B_mem(addr: i32, r: i32) { + instr_0F6B(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F6B(source: reg128, r: i32) { + // packssdw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..4 { + result.u16[i + 0] = saturate_sd_to_sw(destination.u32[i]); + result.u16[i + 4] = saturate_sd_to_sw(source.u32[i]); + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F6B_reg(r1: i32, r2: i32) { instr_660F6B(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F6B_mem(addr: i32, r: i32) { + instr_660F6B(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F6C_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0F6C_reg(_r1: i32, _r2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_660F6C(source: reg128, r: i32) { + // punpcklqdq xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + write_xmm128( + r, + destination.u32[0] as i32, + destination.u32[1] as i32, + source.u32[0] as i32, + source.u32[1] as i32, + ); +} +pub unsafe fn instr_660F6C_reg(r1: i32, r2: i32) { instr_660F6C(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F6C_mem(addr: i32, r: i32) { + instr_660F6C(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F6D_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0F6D_reg(_r1: i32, _r2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_660F6D(source: reg128, r: i32) { + // punpckhqdq xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + write_xmm128( + r, + destination.u32[2] as i32, + destination.u32[3] as i32, + source.u32[2] as i32, + source.u32[3] as i32, + ); +} +pub unsafe fn instr_660F6D_reg(r1: i32, r2: i32) { instr_660F6D(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F6D_mem(addr: i32, r: i32) { + instr_660F6D(return_on_pagefault!(safe_read128s(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0F6E(source: i32, r: i32) { + // movd mm, r/m32 + write_mmx_reg64(r, source as u32 as u64); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F6E_reg(r1: i32, r2: i32) { instr_0F6E(read_reg32(r1), r2); } +pub unsafe fn instr_0F6E_mem(addr: i32, r: i32) { + instr_0F6E(return_on_pagefault!(safe_read32s(addr)), r); +} +pub unsafe fn instr_660F6E(source: i32, r: i32) { + // movd mm, r/m32 + write_xmm128(r, source, 0, 0, 0); +} +pub unsafe fn instr_660F6E_reg(r1: i32, r2: i32) { instr_660F6E(read_reg32(r1), r2); } +pub unsafe fn instr_660F6E_mem(addr: i32, r: i32) { + instr_660F6E(return_on_pagefault!(safe_read32s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F6F(source: u64, r: i32) { + // movq mm, mm/m64 + write_mmx_reg64(r, source); + transition_fpu_to_mmx(); +} +#[no_mangle] +pub unsafe fn instr_0F6F_reg(r1: i32, r2: i32) { instr_0F6F(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F6F_mem(addr: i32, r: i32) { + instr_0F6F(return_on_pagefault!(safe_read64s(addr)), r); +} +pub unsafe fn instr_660F6F(source: reg128, r: i32) { + // movdqa xmm, xmm/mem128 + // XXX: Aligned access or #gp + mov_rm_r128(source, r); +} +pub unsafe fn instr_660F6F_reg(r1: i32, r2: i32) { instr_660F6F(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F6F_mem(addr: i32, r: i32) { + instr_660F6F(return_on_pagefault!(safe_read128s(addr)), r); +} +pub unsafe fn instr_F30F6F(source: reg128, r: i32) { + // movdqu xmm, xmm/m128 + mov_rm_r128(source, r); +} +pub unsafe fn instr_F30F6F_reg(r1: i32, r2: i32) { instr_F30F6F(read_xmm128s(r1), r2); } +pub unsafe fn instr_F30F6F_mem(addr: i32, r: i32) { + instr_F30F6F(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F70(source: u64, r: i32, imm8: i32) { + // pshufw mm1, mm2/m64, imm8 + let source: [u16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = source[(imm8 >> (2 * i) & 3) as usize] + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F70_reg(r1: i32, r2: i32, imm: i32) { instr_0F70(read_mmx64s(r1), r2, imm); } +pub unsafe fn instr_0F70_mem(addr: i32, r: i32, imm: i32) { + instr_0F70(return_on_pagefault!(safe_read64s(addr)), r, imm); +} +pub unsafe fn instr_660F70(source: reg128, r: i32, imm8: i32) { + // pshufd xmm, xmm/mem128, imm8 + // XXX: Aligned access or #gp + write_xmm128( + r, + source.u32[(imm8 & 3) as usize] as i32, + source.u32[(imm8 >> 2 & 3) as usize] as i32, + source.u32[(imm8 >> 4 & 3) as usize] as i32, + source.u32[(imm8 >> 6 & 3) as usize] as i32, + ); +} +pub unsafe fn instr_660F70_reg(r1: i32, r2: i32, imm: i32) { + instr_660F70(read_xmm128s(r1), r2, imm); +} +pub unsafe fn instr_660F70_mem(addr: i32, r: i32, imm: i32) { + instr_660F70(return_on_pagefault!(safe_read128s(addr)), r, imm); +} + +#[no_mangle] +pub unsafe fn instr_F20F70(source: reg128, r: i32, imm8: i32) { + // pshuflw xmm, xmm/m128, imm8 + // XXX: Aligned access or #gp + write_xmm128( + r, + source.u16[(imm8 & 3) as usize] as i32 + | (source.u16[(imm8 >> 2 & 3) as usize] as i32) << 16, + source.u16[(imm8 >> 4 & 3) as usize] as i32 + | (source.u16[(imm8 >> 6 & 3) as usize] as i32) << 16, + source.u32[2] as i32, + source.u32[3] as i32, + ); +} +pub unsafe fn instr_F20F70_reg(r1: i32, r2: i32, imm: i32) { + instr_F20F70(read_xmm128s(r1), r2, imm); +} +pub unsafe fn instr_F20F70_mem(addr: i32, r: i32, imm: i32) { + instr_F20F70(return_on_pagefault!(safe_read128s(addr)), r, imm); +} +#[no_mangle] +pub unsafe fn instr_F30F70(source: reg128, r: i32, imm8: i32) { + // pshufhw xmm, xmm/m128, imm8 + // XXX: Aligned access or #gp + write_xmm128( + r, + source.u32[0] as i32, + source.u32[1] as i32, + source.u16[(imm8 & 3 | 4) as usize] as i32 + | (source.u16[(imm8 >> 2 & 3 | 4) as usize] as i32) << 16, + source.u16[(imm8 >> 4 & 3 | 4) as usize] as i32 + | (source.u16[(imm8 >> 6 & 3 | 4) as usize] as i32) << 16, + ); +} +pub unsafe fn instr_F30F70_reg(r1: i32, r2: i32, imm: i32) { + instr_F30F70(read_xmm128s(r1), r2, imm); +} +pub unsafe fn instr_F30F70_mem(addr: i32, r: i32, imm: i32) { + instr_F30F70(return_on_pagefault!(safe_read128s(addr)), r, imm); +} +pub unsafe fn instr_0F71_2_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_0F71_4_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_0F71_6_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0F71_2_reg(r: i32, imm8: i32) { + // psrlw mm, imm8 + psrlw_r64(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_0F71_4_reg(r: i32, imm8: i32) { + // psraw mm, imm8 + psraw_r64(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_0F71_6_reg(r: i32, imm8: i32) { + // psllw mm, imm8 + psllw_r64(r, imm8 as u64); +} +pub unsafe fn instr_660F71_2_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_660F71_4_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_660F71_6_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_660F71_2_reg(r: i32, imm8: i32) { + // psrlw xmm, imm8 + psrlw_r128(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_660F71_4_reg(r: i32, imm8: i32) { + // psraw xmm, imm8 + psraw_r128(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_660F71_6_reg(r: i32, imm8: i32) { + // psllw xmm, imm8 + psllw_r128(r, imm8 as u64); +} +pub unsafe fn instr_0F72_2_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_0F72_4_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_0F72_6_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0F72_2_reg(r: i32, imm8: i32) { + // psrld mm, imm8 + psrld_r64(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_0F72_4_reg(r: i32, imm8: i32) { + // psrad mm, imm8 + psrad_r64(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_0F72_6_reg(r: i32, imm8: i32) { + // pslld mm, imm8 + pslld_r64(r, imm8 as u64); +} +pub unsafe fn instr_660F72_2_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_660F72_4_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_660F72_6_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_660F72_2_reg(r: i32, imm8: i32) { + // psrld xmm, imm8 + psrld_r128(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_660F72_4_reg(r: i32, imm8: i32) { + // psrad xmm, imm8 + psrad_r128(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_660F72_6_reg(r: i32, imm8: i32) { + // pslld xmm, imm8 + pslld_r128(r, imm8 as u64); +} +pub unsafe fn instr_0F73_2_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_0F73_6_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0F73_2_reg(r: i32, imm8: i32) { + // psrlq mm, imm8 + psrlq_r64(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_0F73_6_reg(r: i32, imm8: i32) { + // psllq mm, imm8 + psllq_r64(r, imm8 as u64); +} +pub unsafe fn instr_660F73_2_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_660F73_3_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_660F73_6_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr_660F73_7_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_660F73_2_reg(r: i32, imm8: i32) { + // psrlq xmm, imm8 + psrlq_r128(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_660F73_3_reg(r: i32, imm8: i32) { + // psrldq xmm, imm8 + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + if imm8 == 0 { + return; + } + let shift = (if imm8 > 15 { 128 } else { imm8 << 3 }) as u32; + if shift <= 63 { + result.u64[0] = destination.u64[0] >> shift | destination.u64[1] << (64 - shift); + result.u64[1] = destination.u64[1] >> shift + } + else if shift <= 127 { + result.u64[0] = destination.u64[1] >> (shift - 64); + result.u64[1] = 0 + } + write_xmm_reg128(r, result); +} +#[no_mangle] +pub unsafe fn instr_660F73_6_reg(r: i32, imm8: i32) { + // psllq xmm, imm8 + psllq_r128(r, imm8 as u64); +} +#[no_mangle] +pub unsafe fn instr_660F73_7_reg(r: i32, imm8: i32) { + // pslldq xmm, imm8 + if imm8 == 0 { + return; + } + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + let shift = (if imm8 > 15 { 128 } else { imm8 << 3 }) as u32; + if shift <= 63 { + result.u64[0] = destination.u64[0] << shift; + result.u64[1] = destination.u64[1] << shift | destination.u64[0] >> (64 - shift) + } + else if shift <= 127 { + result.u64[0] = 0; + result.u64[1] = destination.u64[0] << (shift - 64) + } + write_xmm_reg128(r, result); +} + +#[no_mangle] +pub unsafe fn instr_0F74(source: u64, r: i32) { + // pcmpeqb mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut result: [u8; 8] = [0; 8]; + for i in 0..8 { + result[i] = if destination[i] == source[i] { 255 } else { 0 }; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F74_reg(r1: i32, r2: i32) { instr_0F74(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F74_mem(addr: i32, r: i32) { + instr_0F74(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F74(source: reg128, r: i32) { + // pcmpeqb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.u8[i] = if source.u8[i] == destination.u8[i] { 255 } else { 0 } + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F74_reg(r1: i32, r2: i32) { instr_660F74(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F74_mem(addr: i32, r: i32) { + instr_660F74(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F75(source: u64, r: i32) { + // pcmpeqw mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mut result: [u16; 4] = [0; 4]; + for i in 0..4 { + result[i] = if destination[i] == source[i] { 0xFFFF } else { 0 }; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F75_reg(r1: i32, r2: i32) { instr_0F75(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F75_mem(addr: i32, r: i32) { + instr_0F75(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F75(source: reg128, r: i32) { + // pcmpeqw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = + (if source.u16[i] as i32 == destination.u16[i] as i32 { 0xFFFF } else { 0 }) as u16; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F75_reg(r1: i32, r2: i32) { instr_660F75(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F75_mem(addr: i32, r: i32) { + instr_660F75(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F76(source: u64, r: i32) { + // pcmpeqd mm, mm/m64 + let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r)); + let source: [i32; 2] = std::mem::transmute(source); + let mut result = [0; 2]; + for i in 0..2 { + result[i] = if destination[i] == source[i] { -1 } else { 0 } + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0F76_reg(r1: i32, r2: i32) { instr_0F76(read_mmx64s(r1), r2); } +pub unsafe fn instr_0F76_mem(addr: i32, r: i32) { + instr_0F76(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660F76(source: reg128, r: i32) { + // pcmpeqd xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..4 { + result.i32[i] = if source.u32[i] == destination.u32[i] { -1 } else { 0 } + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660F76_reg(r1: i32, r2: i32) { instr_660F76(read_xmm128s(r1), r2); } +pub unsafe fn instr_660F76_mem(addr: i32, r: i32) { + instr_660F76(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0F77() { + // emms + fpu_set_tag_word(0xFFFF); +} +#[no_mangle] +pub unsafe fn instr_0F78() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F79() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F7A() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F7B() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F7C() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0F7D() { unimplemented_sse(); } + +#[no_mangle] +pub unsafe fn instr_0F7E(r: i32) -> i32 { + // movd r/m32, mm + let data = read_mmx64s(r); + transition_fpu_to_mmx(); + return data as i32; +} +pub unsafe fn instr_0F7E_reg(r1: i32, r2: i32) { write_reg32(r1, instr_0F7E(r2)); } +pub unsafe fn instr_0F7E_mem(addr: i32, r: i32) { + return_on_pagefault!(safe_write32(addr, instr_0F7E(r))); +} +pub unsafe fn instr_660F7E(r: i32) -> i32 { + // movd r/m32, xmm + let data = read_xmm64s(r); + return data as i32; +} +pub unsafe fn instr_660F7E_reg(r1: i32, r2: i32) { write_reg32(r1, instr_660F7E(r2)); } +pub unsafe fn instr_660F7E_mem(addr: i32, r: i32) { + return_on_pagefault!(safe_write32(addr, instr_660F7E(r))); +} +pub unsafe fn instr_F30F7E_mem(addr: i32, r: i32) { + // movq xmm, xmm/mem64 + let data = return_on_pagefault!(safe_read64s(addr)); + write_xmm128_2(r, data, 0); +} +pub unsafe fn instr_F30F7E_reg(r1: i32, r2: i32) { + // movq xmm, xmm/mem64 + write_xmm128_2(r2, read_xmm64s(r1), 0); +} + +#[no_mangle] +pub unsafe fn instr_0F7F(r: i32) -> u64 { + // movq mm/m64, mm + transition_fpu_to_mmx(); + read_mmx64s(r) +} +pub unsafe fn instr_0F7F_mem(addr: i32, r: i32) { + // movq mm/m64, mm + mov_r_m64(addr, r); +} +#[no_mangle] +pub unsafe fn instr_0F7F_reg(r1: i32, r2: i32) { + // movq mm/m64, mm + write_mmx_reg64(r1, read_mmx64s(r2)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_660F7F_mem(addr: i32, r: i32) { + // movdqa xmm/m128, xmm + // XXX: Aligned write or #gp + mov_r_m128(addr, r); +} +pub unsafe fn instr_660F7F_reg(r1: i32, r2: i32) { + // movdqa xmm/m128, xmm + // XXX: Aligned access or #gp + mov_r_r128(r1, r2); +} +pub unsafe fn instr_F30F7F_mem(addr: i32, r: i32) { + // movdqu xmm/m128, xmm + mov_r_m128(addr, r); +} +pub unsafe fn instr_F30F7F_reg(r1: i32, r2: i32) { + // movdqu xmm/m128, xmm + mov_r_r128(r1, r2); +} + +pub unsafe fn instr16_0F80(imm: i32) { jmpcc16(test_o(), imm); } +pub unsafe fn instr32_0F80(imm: i32) { jmpcc32(test_o(), imm); } +pub unsafe fn instr16_0F81(imm: i32) { jmpcc16(!test_o(), imm); } +pub unsafe fn instr32_0F81(imm: i32) { jmpcc32(!test_o(), imm); } +pub unsafe fn instr16_0F82(imm: i32) { jmpcc16(test_b(), imm); } +pub unsafe fn instr32_0F82(imm: i32) { jmpcc32(test_b(), imm); } +pub unsafe fn instr16_0F83(imm: i32) { jmpcc16(!test_b(), imm); } +pub unsafe fn instr32_0F83(imm: i32) { jmpcc32(!test_b(), imm); } +pub unsafe fn instr16_0F84(imm: i32) { jmpcc16(test_z(), imm); } +pub unsafe fn instr32_0F84(imm: i32) { jmpcc32(test_z(), imm); } +pub unsafe fn instr16_0F85(imm: i32) { jmpcc16(!test_z(), imm); } +pub unsafe fn instr32_0F85(imm: i32) { jmpcc32(!test_z(), imm); } +pub unsafe fn instr16_0F86(imm: i32) { jmpcc16(test_be(), imm); } +pub unsafe fn instr32_0F86(imm: i32) { jmpcc32(test_be(), imm); } +pub unsafe fn instr16_0F87(imm: i32) { jmpcc16(!test_be(), imm); } +pub unsafe fn instr32_0F87(imm: i32) { jmpcc32(!test_be(), imm); } +pub unsafe fn instr16_0F88(imm: i32) { jmpcc16(test_s(), imm); } +pub unsafe fn instr32_0F88(imm: i32) { jmpcc32(test_s(), imm); } +pub unsafe fn instr16_0F89(imm: i32) { jmpcc16(!test_s(), imm); } +pub unsafe fn instr32_0F89(imm: i32) { jmpcc32(!test_s(), imm); } +pub unsafe fn instr16_0F8A(imm: i32) { jmpcc16(test_p(), imm); } +pub unsafe fn instr32_0F8A(imm: i32) { jmpcc32(test_p(), imm); } +pub unsafe fn instr16_0F8B(imm: i32) { jmpcc16(!test_p(), imm); } +pub unsafe fn instr32_0F8B(imm: i32) { jmpcc32(!test_p(), imm); } +pub unsafe fn instr16_0F8C(imm: i32) { jmpcc16(test_l(), imm); } +pub unsafe fn instr32_0F8C(imm: i32) { jmpcc32(test_l(), imm); } +pub unsafe fn instr16_0F8D(imm: i32) { jmpcc16(!test_l(), imm); } +pub unsafe fn instr32_0F8D(imm: i32) { jmpcc32(!test_l(), imm); } +pub unsafe fn instr16_0F8E(imm: i32) { jmpcc16(test_le(), imm); } +pub unsafe fn instr32_0F8E(imm: i32) { jmpcc32(test_le(), imm); } +pub unsafe fn instr16_0F8F(imm: i32) { jmpcc16(!test_le(), imm); } +pub unsafe fn instr32_0F8F(imm: i32) { jmpcc32(!test_le(), imm); } + +pub unsafe fn instr_0F90_reg(r: i32, _: i32) { setcc_reg(test_o(), r); } +pub unsafe fn instr_0F91_reg(r: i32, _: i32) { setcc_reg(!test_o(), r); } +pub unsafe fn instr_0F92_reg(r: i32, _: i32) { setcc_reg(test_b(), r); } +pub unsafe fn instr_0F93_reg(r: i32, _: i32) { setcc_reg(!test_b(), r); } +pub unsafe fn instr_0F94_reg(r: i32, _: i32) { setcc_reg(test_z(), r); } +pub unsafe fn instr_0F95_reg(r: i32, _: i32) { setcc_reg(!test_z(), r); } +pub unsafe fn instr_0F96_reg(r: i32, _: i32) { setcc_reg(test_be(), r); } +pub unsafe fn instr_0F97_reg(r: i32, _: i32) { setcc_reg(!test_be(), r); } +pub unsafe fn instr_0F98_reg(r: i32, _: i32) { setcc_reg(test_s(), r); } +pub unsafe fn instr_0F99_reg(r: i32, _: i32) { setcc_reg(!test_s(), r); } +pub unsafe fn instr_0F9A_reg(r: i32, _: i32) { setcc_reg(test_p(), r); } +pub unsafe fn instr_0F9B_reg(r: i32, _: i32) { setcc_reg(!test_p(), r); } +pub unsafe fn instr_0F9C_reg(r: i32, _: i32) { setcc_reg(test_l(), r); } +pub unsafe fn instr_0F9D_reg(r: i32, _: i32) { setcc_reg(!test_l(), r); } +pub unsafe fn instr_0F9E_reg(r: i32, _: i32) { setcc_reg(test_le(), r); } +pub unsafe fn instr_0F9F_reg(r: i32, _: i32) { setcc_reg(!test_le(), r); } +pub unsafe fn instr_0F90_mem(addr: i32, _: i32) { setcc_mem(test_o(), addr); } +pub unsafe fn instr_0F91_mem(addr: i32, _: i32) { setcc_mem(!test_o(), addr); } +pub unsafe fn instr_0F92_mem(addr: i32, _: i32) { setcc_mem(test_b(), addr); } +pub unsafe fn instr_0F93_mem(addr: i32, _: i32) { setcc_mem(!test_b(), addr); } +pub unsafe fn instr_0F94_mem(addr: i32, _: i32) { setcc_mem(test_z(), addr); } +pub unsafe fn instr_0F95_mem(addr: i32, _: i32) { setcc_mem(!test_z(), addr); } +pub unsafe fn instr_0F96_mem(addr: i32, _: i32) { setcc_mem(test_be(), addr); } +pub unsafe fn instr_0F97_mem(addr: i32, _: i32) { setcc_mem(!test_be(), addr); } +pub unsafe fn instr_0F98_mem(addr: i32, _: i32) { setcc_mem(test_s(), addr); } +pub unsafe fn instr_0F99_mem(addr: i32, _: i32) { setcc_mem(!test_s(), addr); } +pub unsafe fn instr_0F9A_mem(addr: i32, _: i32) { setcc_mem(test_p(), addr); } +pub unsafe fn instr_0F9B_mem(addr: i32, _: i32) { setcc_mem(!test_p(), addr); } +pub unsafe fn instr_0F9C_mem(addr: i32, _: i32) { setcc_mem(test_l(), addr); } +pub unsafe fn instr_0F9D_mem(addr: i32, _: i32) { setcc_mem(!test_l(), addr); } +pub unsafe fn instr_0F9E_mem(addr: i32, _: i32) { setcc_mem(test_le(), addr); } +pub unsafe fn instr_0F9F_mem(addr: i32, _: i32) { setcc_mem(!test_le(), addr); } + +pub unsafe fn instr16_0FA0() { + return_on_pagefault!(push16(*sreg.offset(FS as isize) as i32)); +} +pub unsafe fn instr32_0FA0() { return_on_pagefault!(push32_sreg(FS)) } +#[no_mangle] +pub unsafe fn instr16_0FA1() { + if !switch_seg(FS, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) { + return; + } + else { + adjust_stack_reg(2); + return; + }; +} +#[no_mangle] +pub unsafe fn instr32_0FA1() { + if !switch_seg( + FS, + return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF, + ) { + return; + } + else { + adjust_stack_reg(4); + return; + }; +} +#[no_mangle] +pub unsafe fn instr_0FA2() { + // cpuid + // TODO: Fill in with less bogus values + + // http://lxr.linux.no/linux+%2a/arch/x86/include/asm/cpufeature.h + // http://www.sandpile.org/x86/cpuid.htm + let mut eax = 0; + let mut ecx = 0; + let mut edx = 0; + let mut ebx = 0; + + let level = read_reg32(EAX) as u32; + + match level { + 0 => { + // maximum supported level (default 0x16, overwritten to 2 as a workaround for Windows NT) + eax = cpuid_level as i32; + + ebx = 0x756E6547 | 0; // Genu + edx = 0x49656E69 | 0; // ineI + ecx = 0x6C65746E | 0; // ntel + }, + + 1 => { + // pentium + eax = 3 | 6 << 4 | 15 << 8; + ebx = 1 << 16 | 8 << 8; // cpu count, clflush size + ecx = 1 << 23 | 1 << 30; // popcnt, rdrand + let vme = 0 << 1; + if ::config::VMWARE_HYPERVISOR_PORT { + ecx |= 1 << 31 + }; // hypervisor + edx = (if true /* have fpu */ { 1 } else { 0 }) | // fpu + vme | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 6 | // vme, pse, tsc, msr, pae + 1 << 8 | 1 << 11 | 1 << 13 | 1 << 15 | // cx8, sep, pge, cmov + 1 << 23 | 1 << 24 | 1 << 25 | 1 << 26; // mmx, fxsr, sse1, sse2 + + if *acpi_enabled + //&& this.apic_enabled[0]) + { + edx |= 1 << 9; // apic + } + }, + + 2 => { + // Taken from http://siyobik.info.gf/main/reference/instruction/CPUID + eax = 0x665B5001; + ebx = 0; + ecx = 0; + edx = 0x007A7000; + }, + + 4 => { + // from my local machine + match read_reg32(ECX) { + 0 => { + eax = 0x00000121; + ebx = 0x01c0003f; + ecx = 0x0000003f; + edx = 0x00000001; + }, + 1 => { + eax = 0x00000122; + ebx = 0x01c0003f; + ecx = 0x0000003f; + edx = 0x00000001; + }, + 2 => { + eax = 0x00000143; + ebx = 0x05c0003f; + ecx = 0x00000fff; + edx = 0x00000001; + }, + _ => {}, + } + }, + + 5 => { + // from my local machine + eax = 0x40; + ebx = 0x40; + ecx = 3; + edx = 0x00142120; + }, + + 7 => { + if read_reg32(ECX) == 0 { + eax = 0; // maximum supported sub-level + ebx = 1 << 9; // enhanced REP MOVSB/STOSB + ecx = 0; + edx = 0; + } + }, + + 0x80000000 => { + // maximum supported extended level + eax = 5; + // other registers are reserved + }, + + 0x40000000 => { + // hypervisor + if ::config::VMWARE_HYPERVISOR_PORT { + // h("Ware".split("").reduce((a, c, i) => a | c.charCodeAt(0) << i * 8, 0)) + ebx = 0x61774D56 | 0; // VMwa + ecx = 0x4D566572 | 0; // reVM + edx = 0x65726177 | 0; // ware + } + }, + + 0x15 => { + eax = 1; // denominator + ebx = 1; // numerator + ecx = (TSC_RATE * 1000.0) as u32 as i32; // core crystal clock frequency in Hz + dbg_assert!(ecx > 0); + // (TSC frequency = core crystal clock frequency * EBX/EAX) + }, + + 0x16 => { + eax = (TSC_RATE / 1000.0).floor() as u32 as i32; // core base frequency in MHz + ebx = (TSC_RATE / 1000.0).floor() as u32 as i32; // core maximum frequency in MHz + ecx = 10; // bus (reference) frequency in MHz + + // 16-bit values + dbg_assert!(eax < 0x10000); + dbg_assert!(ebx < 0x10000); + dbg_assert!(ecx < 0x10000); + }, + + x => { + dbg_log!("cpuid: unimplemented eax: {:x}", x); + }, + } + + if level == 4 || level == 7 { + dbg_log!( + "cpuid: eax={:08x} ecx={:02x}", + read_reg32(EAX), + read_reg32(ECX), + ); + } + else if level != 0 && level != 2 && level != 0x80000000 { + dbg_log!("cpuid: eax={:08x}", read_reg32(EAX)); + } + + write_reg32(EAX, eax); + write_reg32(ECX, ecx); + write_reg32(EDX, edx); + write_reg32(EBX, ebx); +} +pub unsafe fn instr16_0FA3_reg(r1: i32, r2: i32) { bt_reg(read_reg16(r1), read_reg16(r2) & 15); } +pub unsafe fn instr16_0FA3_mem(addr: i32, r: i32) { bt_mem(addr, read_reg16(r) << 16 >> 16); } +pub unsafe fn instr32_0FA3_reg(r1: i32, r2: i32) { bt_reg(read_reg32(r1), read_reg32(r2) & 31); } +pub unsafe fn instr32_0FA3_mem(addr: i32, r: i32) { bt_mem(addr, read_reg32(r)); } +pub unsafe fn instr16_0FA4_mem(addr: i32, r: i32, imm: i32) { + safe_read_write16(addr, &|x| shld16(x, read_reg16(r), imm & 31)) +} +pub unsafe fn instr16_0FA4_reg(r1: i32, r: i32, imm: i32) { + write_reg16(r1, shld16(read_reg16(r1), read_reg16(r), imm & 31)); +} +pub unsafe fn instr32_0FA4_mem(addr: i32, r: i32, imm: i32) { + safe_read_write32(addr, &|x| shld32(x, read_reg32(r), imm & 31)) +} +pub unsafe fn instr32_0FA4_reg(r1: i32, r: i32, imm: i32) { + write_reg32(r1, shld32(read_reg32(r1), read_reg32(r), imm & 31)); +} +pub unsafe fn instr16_0FA5_mem(addr: i32, r: i32) { + safe_read_write16(addr, &|x| shld16(x, read_reg16(r), read_reg8(CL) & 31)) +} +pub unsafe fn instr16_0FA5_reg(r1: i32, r: i32) { + write_reg16( + r1, + shld16(read_reg16(r1), read_reg16(r), read_reg8(CL) & 31), + ); +} +pub unsafe fn instr32_0FA5_mem(addr: i32, r: i32) { + safe_read_write32(addr, &|x| shld32(x, read_reg32(r), read_reg8(CL) & 31)) +} +pub unsafe fn instr32_0FA5_reg(r1: i32, r: i32) { + write_reg32( + r1, + shld32(read_reg32(r1), read_reg32(r), read_reg8(CL) & 31), + ); +} +#[no_mangle] +pub unsafe fn instr_0FA6() { + // obsolete cmpxchg (os/2) + trigger_ud(); +} +#[no_mangle] +pub unsafe fn instr_0FA7() { undefined_instruction(); } +pub unsafe fn instr16_0FA8() { + return_on_pagefault!(push16(*sreg.offset(GS as isize) as i32)); +} +pub unsafe fn instr32_0FA8() { return_on_pagefault!(push32_sreg(GS)) } +#[no_mangle] +pub unsafe fn instr16_0FA9() { + if !switch_seg(GS, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) { + return; + } + else { + adjust_stack_reg(2); + return; + }; +} +#[no_mangle] +pub unsafe fn instr32_0FA9() { + if !switch_seg( + GS, + return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF, + ) { + return; + } + else { + adjust_stack_reg(4); + return; + }; +} +#[no_mangle] +pub unsafe fn instr_0FAA() { + // rsm + undefined_instruction(); +} +#[no_mangle] +pub unsafe fn instr16_0FAB_reg(r1: i32, r2: i32) { + write_reg16(r1, bts_reg(read_reg16(r1), read_reg16(r2) & 15)); +} +#[no_mangle] +pub unsafe fn instr16_0FAB_mem(addr: i32, r: i32) { bts_mem(addr, read_reg16(r) << 16 >> 16); } +#[no_mangle] +pub unsafe fn instr32_0FAB_reg(r1: i32, r2: i32) { + write_reg32(r1, bts_reg(read_reg32(r1), read_reg32(r2) & 31)); +} +#[no_mangle] +pub unsafe fn instr32_0FAB_mem(addr: i32, r: i32) { bts_mem(addr, read_reg32(r)); } +pub unsafe fn instr16_0FAC_mem(addr: i32, r: i32, imm: i32) { + safe_read_write16(addr, &|x| shrd16(x, read_reg16(r), imm & 31)) +} +pub unsafe fn instr16_0FAC_reg(r1: i32, r: i32, imm: i32) { + write_reg16(r1, shrd16(read_reg16(r1), read_reg16(r), imm & 31)); +} +pub unsafe fn instr32_0FAC_mem(addr: i32, r: i32, imm: i32) { + safe_read_write32(addr, &|x| shrd32(x, read_reg32(r), imm & 31)) +} +pub unsafe fn instr32_0FAC_reg(r1: i32, r: i32, imm: i32) { + write_reg32(r1, shrd32(read_reg32(r1), read_reg32(r), imm & 31)); +} +pub unsafe fn instr16_0FAD_mem(addr: i32, r: i32) { + safe_read_write16(addr, &|x| shrd16(x, read_reg16(r), read_reg8(CL) & 31)) +} +pub unsafe fn instr16_0FAD_reg(r1: i32, r: i32) { + write_reg16( + r1, + shrd16(read_reg16(r1), read_reg16(r), read_reg8(CL) & 31), + ); +} +pub unsafe fn instr32_0FAD_mem(addr: i32, r: i32) { + safe_read_write32(addr, &|x| shrd32(x, read_reg32(r), read_reg8(CL) & 31)) +} +pub unsafe fn instr32_0FAD_reg(r1: i32, r: i32) { + write_reg32( + r1, + shrd32(read_reg32(r1), read_reg32(r), read_reg8(CL) & 31), + ); +} +#[no_mangle] +pub unsafe fn instr_0FAE_0_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0FAE_0_mem(addr: i32) { fxsave(addr); } +#[no_mangle] +pub unsafe fn instr_0FAE_1_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0FAE_1_mem(addr: i32) { fxrstor(addr); } +#[no_mangle] +pub unsafe fn instr_0FAE_2_reg(_r: i32) { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0FAE_2_mem(addr: i32) { + // ldmxcsr + let new_mxcsr = return_on_pagefault!(safe_read32s(addr)); + if 0 != new_mxcsr & !MXCSR_MASK { + dbg_log!("Invalid mxcsr bits: {:x}", new_mxcsr & !MXCSR_MASK); + trigger_gp(0); + return; + } + else { + set_mxcsr(new_mxcsr); + return; + }; +} +#[no_mangle] +pub unsafe fn instr_0FAE_3_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0FAE_3_mem(addr: i32) { + // stmxcsr + return_on_pagefault!(safe_write32(addr, *mxcsr)); +} +#[no_mangle] +pub unsafe fn instr_0FAE_4_reg(_r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0FAE_4_mem(_addr: i32) { + // xsave + undefined_instruction(); +} +pub unsafe fn instr_0FAE_5_reg(_r: i32) { + // lfence +} +pub unsafe fn instr_0FAE_5_mem(_addr: i32) { + // xrstor + undefined_instruction(); +} +#[no_mangle] +pub unsafe fn instr_0FAE_6_reg(_r: i32) { + // mfence +} +#[no_mangle] +pub unsafe fn instr_0FAE_6_mem(_addr: i32) { + // xsaveopt + undefined_instruction(); +} +#[no_mangle] +pub unsafe fn instr_0FAE_7_reg(_r: i32) { + // sfence +} +#[no_mangle] +pub unsafe fn instr_0FAE_7_mem(_addr: i32) { + // clflush + undefined_instruction(); +} +pub unsafe fn instr16_0FAF_mem(addr: i32, r: i32) { + write_reg16( + r, + imul_reg16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_0FAF_reg(r1: i32, r: i32) { + write_reg16(r, imul_reg16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_0FAF_mem(addr: i32, r: i32) { + write_reg32( + r, + imul_reg32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_0FAF_reg(r1: i32, r: i32) { + write_reg32(r, imul_reg32(read_reg32(r), read_reg32(r1))); +} + +#[no_mangle] +pub unsafe fn instr_0FB0_reg(r1: i32, r2: i32) { write_reg8(r1, cmpxchg8(read_reg8(r1), r2)); } +#[no_mangle] +pub unsafe fn instr_0FB0_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| cmpxchg8(x, r)) } +pub unsafe fn instr16_0FB1_reg(r1: i32, r2: i32) { write_reg16(r1, cmpxchg16(read_reg16(r1), r2)); } +pub unsafe fn instr16_0FB1_mem(addr: i32, r: i32) { safe_read_write16(addr, &|x| cmpxchg16(x, r)) } +pub unsafe fn instr32_0FB1_reg(r1: i32, r2: i32) { write_reg32(r1, cmpxchg32(read_reg32(r1), r2)); } +pub unsafe fn instr32_0FB1_mem(addr: i32, r: i32) { safe_read_write32(addr, &|x| cmpxchg32(x, r)) } + +#[no_mangle] +pub unsafe fn instr16_0FB2_reg(_unused: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr16_0FB2_mem(addr: i32, r: i32) { lss16(addr, r, SS); } +#[no_mangle] +pub unsafe fn instr32_0FB2_reg(_unused: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0FB2_mem(addr: i32, r: i32) { lss32(addr, r, SS); } +#[no_mangle] +pub unsafe fn instr16_0FB3_reg(r1: i32, r2: i32) { + write_reg16(r1, btr_reg(read_reg16(r1), read_reg16(r2) & 15)); +} +#[no_mangle] +pub unsafe fn instr16_0FB3_mem(addr: i32, r: i32) { btr_mem(addr, read_reg16(r) << 16 >> 16); } +#[no_mangle] +pub unsafe fn instr32_0FB3_reg(r1: i32, r2: i32) { + write_reg32(r1, btr_reg(read_reg32(r1), read_reg32(r2) & 31)); +} +#[no_mangle] +pub unsafe fn instr32_0FB3_mem(addr: i32, r: i32) { btr_mem(addr, read_reg32(r)); } +#[no_mangle] +pub unsafe fn instr16_0FB4_reg(_unused: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr16_0FB4_mem(addr: i32, r: i32) { lss16(addr, r, FS); } +#[no_mangle] +pub unsafe fn instr32_0FB4_reg(_unused: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0FB4_mem(addr: i32, r: i32) { lss32(addr, r, FS); } +#[no_mangle] +pub unsafe fn instr16_0FB5_reg(_unused: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr16_0FB5_mem(addr: i32, r: i32) { lss16(addr, r, GS); } +#[no_mangle] +pub unsafe fn instr32_0FB5_reg(_unused: i32, _unused2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0FB5_mem(addr: i32, r: i32) { lss32(addr, r, GS); } +pub unsafe fn instr16_0FB6_mem(addr: i32, r: i32) { + write_reg16(r, return_on_pagefault!(safe_read8(addr))); +} +pub unsafe fn instr16_0FB6_reg(r1: i32, r: i32) { write_reg16(r, read_reg8(r1)); } +pub unsafe fn instr32_0FB6_mem(addr: i32, r: i32) { + write_reg32(r, return_on_pagefault!(safe_read8(addr))); +} +pub unsafe fn instr32_0FB6_reg(r1: i32, r: i32) { write_reg32(r, read_reg8(r1)); } +pub unsafe fn instr16_0FB7_mem(addr: i32, r: i32) { + write_reg16(r, return_on_pagefault!(safe_read16(addr))); +} +pub unsafe fn instr16_0FB7_reg(r1: i32, r: i32) { write_reg16(r, read_reg16(r1)); } +pub unsafe fn instr32_0FB7_mem(addr: i32, r: i32) { + write_reg32(r, return_on_pagefault!(safe_read16(addr))); +} +pub unsafe fn instr32_0FB7_reg(r1: i32, r: i32) { write_reg32(r, read_reg16(r1)); } +#[no_mangle] +pub unsafe fn instr16_0FB8_reg(_r1: i32, _r2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr16_0FB8_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr16_F30FB8_mem(addr: i32, r: i32) { + write_reg16(r, popcnt(return_on_pagefault!(safe_read16(addr)))); +} +pub unsafe fn instr16_F30FB8_reg(r1: i32, r: i32) { write_reg16(r, popcnt(read_reg16(r1))); } +#[no_mangle] +pub unsafe fn instr32_0FB8_reg(_r1: i32, _r2: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0FB8_mem(_addr: i32, _r: i32) { trigger_ud(); } +pub unsafe fn instr32_F30FB8_mem(addr: i32, r: i32) { + write_reg32(r, popcnt(return_on_pagefault!(safe_read32s(addr)))); +} +pub unsafe fn instr32_F30FB8_reg(r1: i32, r: i32) { write_reg32(r, popcnt(read_reg32(r1))); } +#[no_mangle] +pub unsafe fn instr_0FB9() { + // UD2 + trigger_ud(); +} +pub unsafe fn instr16_0FBA_4_reg(r: i32, imm: i32) { bt_reg(read_reg16(r), imm & 15); } +pub unsafe fn instr16_0FBA_4_mem(addr: i32, imm: i32) { bt_mem(addr, imm & 15); } +#[no_mangle] +pub unsafe fn instr16_0FBA_5_reg(r: i32, imm: i32) { + write_reg16(r, bts_reg(read_reg16(r), imm & 15)); +} +#[no_mangle] +pub unsafe fn instr16_0FBA_5_mem(addr: i32, imm: i32) { bts_mem(addr, imm & 15); } +#[no_mangle] +pub unsafe fn instr16_0FBA_6_reg(r: i32, imm: i32) { + write_reg16(r, btr_reg(read_reg16(r), imm & 15)); +} +#[no_mangle] +pub unsafe fn instr16_0FBA_6_mem(addr: i32, imm: i32) { btr_mem(addr, imm & 15); } +#[no_mangle] +pub unsafe fn instr16_0FBA_7_reg(r: i32, imm: i32) { + write_reg16(r, btc_reg(read_reg16(r), imm & 15)); +} +#[no_mangle] +pub unsafe fn instr16_0FBA_7_mem(addr: i32, imm: i32) { btc_mem(addr, imm & 15); } +pub unsafe fn instr32_0FBA_4_reg(r: i32, imm: i32) { bt_reg(read_reg32(r), imm & 31); } +pub unsafe fn instr32_0FBA_4_mem(addr: i32, imm: i32) { bt_mem(addr, imm & 31); } +#[no_mangle] +pub unsafe fn instr32_0FBA_5_reg(r: i32, imm: i32) { + write_reg32(r, bts_reg(read_reg32(r), imm & 31)); +} +#[no_mangle] +pub unsafe fn instr32_0FBA_5_mem(addr: i32, imm: i32) { bts_mem(addr, imm & 31); } +#[no_mangle] +pub unsafe fn instr32_0FBA_6_reg(r: i32, imm: i32) { + write_reg32(r, btr_reg(read_reg32(r), imm & 31)); +} +#[no_mangle] +pub unsafe fn instr32_0FBA_6_mem(addr: i32, imm: i32) { btr_mem(addr, imm & 31); } +#[no_mangle] +pub unsafe fn instr32_0FBA_7_reg(r: i32, imm: i32) { + write_reg32(r, btc_reg(read_reg32(r), imm & 31)); +} +#[no_mangle] +pub unsafe fn instr32_0FBA_7_mem(addr: i32, imm: i32) { btc_mem(addr, imm & 31); } +#[no_mangle] +pub unsafe fn instr16_0FBB_reg(r1: i32, r2: i32) { + write_reg16(r1, btc_reg(read_reg16(r1), read_reg16(r2) & 15)); +} +#[no_mangle] +pub unsafe fn instr16_0FBB_mem(addr: i32, r: i32) { btc_mem(addr, read_reg16(r) << 16 >> 16); } +#[no_mangle] +pub unsafe fn instr32_0FBB_reg(r1: i32, r2: i32) { + write_reg32(r1, btc_reg(read_reg32(r1), read_reg32(r2) & 31)); +} +#[no_mangle] +pub unsafe fn instr32_0FBB_mem(addr: i32, r: i32) { btc_mem(addr, read_reg32(r)); } +pub unsafe fn instr16_0FBC_mem(addr: i32, r: i32) { + write_reg16( + r, + bsf16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_0FBC_reg(r1: i32, r: i32) { + write_reg16(r, bsf16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_0FBC_mem(addr: i32, r: i32) { + write_reg32( + r, + bsf32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_0FBC_reg(r1: i32, r: i32) { + write_reg32(r, bsf32(read_reg32(r), read_reg32(r1))); +} +pub unsafe fn instr16_0FBD_mem(addr: i32, r: i32) { + write_reg16( + r, + bsr16(read_reg16(r), return_on_pagefault!(safe_read16(addr))), + ); +} +pub unsafe fn instr16_0FBD_reg(r1: i32, r: i32) { + write_reg16(r, bsr16(read_reg16(r), read_reg16(r1))); +} +pub unsafe fn instr32_0FBD_mem(addr: i32, r: i32) { + write_reg32( + r, + bsr32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))), + ); +} +pub unsafe fn instr32_0FBD_reg(r1: i32, r: i32) { + write_reg32(r, bsr32(read_reg32(r), read_reg32(r1))); +} +pub unsafe fn instr16_0FBE_mem(addr: i32, r: i32) { + write_reg16(r, return_on_pagefault!(safe_read8(addr)) << 24 >> 24); +} +pub unsafe fn instr16_0FBE_reg(r1: i32, r: i32) { write_reg16(r, read_reg8(r1) << 24 >> 24); } +pub unsafe fn instr32_0FBE_mem(addr: i32, r: i32) { + write_reg32(r, return_on_pagefault!(safe_read8(addr)) << 24 >> 24); +} +pub unsafe fn instr32_0FBE_reg(r1: i32, r: i32) { write_reg32(r, read_reg8(r1) << 24 >> 24); } +pub unsafe fn instr16_0FBF_mem(addr: i32, r: i32) { + write_reg16(r, return_on_pagefault!(safe_read16(addr)) << 16 >> 16); +} +pub unsafe fn instr16_0FBF_reg(r1: i32, r: i32) { write_reg16(r, read_reg16(r1) << 16 >> 16); } +pub unsafe fn instr32_0FBF_mem(addr: i32, r: i32) { + write_reg32(r, return_on_pagefault!(safe_read16(addr)) << 16 >> 16); +} +pub unsafe fn instr32_0FBF_reg(r1: i32, r: i32) { write_reg32(r, read_reg16(r1) << 16 >> 16); } +#[no_mangle] +pub unsafe fn instr_0FC0_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| xadd8(x, r)) } +#[no_mangle] +pub unsafe fn instr_0FC0_reg(r1: i32, r: i32) { write_reg8(r1, xadd8(read_reg8(r1), r)); } +pub unsafe fn instr16_0FC1_mem(addr: i32, r: i32) { safe_read_write16(addr, &|x| xadd16(x, r)) } +pub unsafe fn instr16_0FC1_reg(r1: i32, r: i32) { write_reg16(r1, xadd16(read_reg16(r1), r)); } +pub unsafe fn instr32_0FC1_mem(addr: i32, r: i32) { safe_read_write32(addr, &|x| xadd32(x, r)) } +pub unsafe fn instr32_0FC1_reg(r1: i32, r: i32) { write_reg32(r1, xadd32(read_reg32(r1), r)); } + +#[no_mangle] +pub unsafe fn instr_0FC2(source: reg128, r: i32, imm8: i32) { + // cmpps xmm, xmm/m128 + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..4 { + result.i32[i] = if sse_comparison(imm8, destination.f32[i] as f64, source.f32[i] as f64) { + -1 + } + else { + 0 + }; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_0FC2_reg(r1: i32, r2: i32, imm: i32) { instr_0FC2(read_xmm128s(r1), r2, imm); } +pub unsafe fn instr_0FC2_mem(addr: i32, r: i32, imm: i32) { + instr_0FC2(return_on_pagefault!(safe_read128s(addr)), r, imm); +} +#[no_mangle] +pub unsafe fn instr_660FC2(source: reg128, r: i32, imm8: i32) { + // cmppd xmm, xmm/m128 + let destination = read_xmm128s(r); + let result = reg128 { + i64: [ + (if sse_comparison(imm8, destination.f64[0], source.f64[0]) { -1 } else { 0 }) as i64, + (if sse_comparison(imm8, destination.f64[1], source.f64[1]) { -1 } else { 0 }) as i64, + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FC2_reg(r1: i32, r2: i32, imm: i32) { + instr_660FC2(read_xmm128s(r1), r2, imm); +} +pub unsafe fn instr_660FC2_mem(addr: i32, r: i32, imm: i32) { + instr_660FC2(return_on_pagefault!(safe_read128s(addr)), r, imm); +} +#[no_mangle] +pub unsafe fn instr_F20FC2(source: u64, r: i32, imm8: i32) { + // cmpsd xmm, xmm/m64 + let destination = read_xmm64s(r); + write_xmm64( + r, + if sse_comparison(imm8, f64::from_bits(destination), f64::from_bits(source)) { + (-1i32) as u64 + } + else { + 0 + }, + ); +} +pub unsafe fn instr_F20FC2_reg(r1: i32, r2: i32, imm: i32) { + instr_F20FC2(read_xmm64s(r1), r2, imm); +} +pub unsafe fn instr_F20FC2_mem(addr: i32, r: i32, imm: i32) { + instr_F20FC2(return_on_pagefault!(safe_read64s(addr)), r, imm); +} +#[no_mangle] +pub unsafe fn instr_F30FC2(source: i32, r: i32, imm8: i32) { + // cmpss xmm, xmm/m32 + let destination = read_xmm_f32(r); + let source: f32 = std::mem::transmute(source); + let result = if sse_comparison(imm8, destination as f64, source as f64) { -1 } else { 0 }; + write_xmm32(r, result); +} +pub unsafe fn instr_F30FC2_reg(r1: i32, r2: i32, imm: i32) { + instr_F30FC2(read_xmm64s(r1) as i32, r2, imm); +} +pub unsafe fn instr_F30FC2_mem(addr: i32, r: i32, imm: i32) { + instr_F30FC2(return_on_pagefault!(safe_read32s(addr)), r, imm); +} + +pub unsafe fn instr_0FC3_reg(_r1: i32, _r2: i32) { trigger_ud(); } +pub unsafe fn instr_0FC3_mem(addr: i32, r: i32) { + // movnti + return_on_pagefault!(safe_write32(addr, read_reg32(r))); +} + +#[no_mangle] +pub unsafe fn instr_0FC4(source: i32, r: i32, imm8: i32) { + // pinsrw mm, r32/m16, imm8 + let mut destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + destination[(imm8 & 3) as usize] = source as u16; + write_mmx_reg64(r, std::mem::transmute(destination)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FC4_reg(r1: i32, r2: i32, imm: i32) { instr_0FC4(read_reg32(r1), r2, imm); } +pub unsafe fn instr_0FC4_mem(addr: i32, r: i32, imm: i32) { + instr_0FC4(return_on_pagefault!(safe_read16(addr)), r, imm); +} +pub unsafe fn instr_660FC4(source: i32, r: i32, imm8: i32) { + // pinsrw xmm, r32/m16, imm8 + let mut destination = read_xmm128s(r); + let index = (imm8 & 7) as u32; + destination.u16[index as usize] = (source & 0xFFFF) as u16; + write_xmm_reg128(r, destination); +} +pub unsafe fn instr_660FC4_reg(r1: i32, r2: i32, imm: i32) { + instr_660FC4(read_reg32(r1), r2, imm); +} +pub unsafe fn instr_660FC4_mem(addr: i32, r: i32, imm: i32) { + instr_660FC4(return_on_pagefault!(safe_read16(addr)), r, imm); +} +pub unsafe fn instr_0FC5_mem(_addr: i32, _r: i32, _imm8: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0FC5_reg(r1: i32, r2: i32, imm8: i32) { + // pextrw r32, mm, imm8 + let data: [u16; 4] = std::mem::transmute(read_mmx64s(r1)); + write_reg32(r2, data[(imm8 & 3) as usize] as i32); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_660FC5_mem(_addr: i32, _r: i32, _imm8: i32) { trigger_ud(); } +pub unsafe fn instr_660FC5_reg(r1: i32, r2: i32, imm8: i32) { + // pextrw r32, xmm, imm8 + let data = read_xmm128s(r1); + let index = (imm8 & 7) as u32; + let result = data.u16[index as usize] as u32; + write_reg32(r2, result as i32); +} + +#[no_mangle] +pub unsafe fn instr_0FC6(source: reg128, r: i32, imm8: i32) { + // shufps xmm, xmm/mem128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + write_xmm128( + r, + destination.u32[(imm8 & 3) as usize] as i32, + destination.u32[(imm8 >> 2 & 3) as usize] as i32, + source.u32[(imm8 >> 4 & 3) as usize] as i32, + source.u32[(imm8 >> 6 & 3) as usize] as i32, + ); +} +pub unsafe fn instr_0FC6_reg(r1: i32, r2: i32, imm: i32) { instr_0FC6(read_xmm128s(r1), r2, imm); } +pub unsafe fn instr_0FC6_mem(addr: i32, r: i32, imm: i32) { + instr_0FC6(return_on_pagefault!(safe_read128s(addr)), r, imm); +} + +#[no_mangle] +pub unsafe fn instr_660FC6(source: reg128, r: i32, imm8: i32) { + // shufpd xmm, xmm/mem128 + let destination = read_xmm128s(r); + let result = reg128 { + i64: [ + destination.i64[imm8 as usize & 1], + source.i64[imm8 as usize >> 1 & 1], + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FC6_reg(r1: i32, r2: i32, imm: i32) { + instr_660FC6(read_xmm128s(r1), r2, imm); +} +pub unsafe fn instr_660FC6_mem(addr: i32, r: i32, imm: i32) { + instr_660FC6(return_on_pagefault!(safe_read128s(addr)), r, imm); +} + +pub unsafe fn instr16_0FC7_1_reg(_r: i32) { trigger_ud(); } +pub unsafe fn instr32_0FC7_1_reg(_r: i32) { trigger_ud(); } +pub unsafe fn instr16_0FC7_1_mem(addr: i32) { + // cmpxchg8b + return_on_pagefault!(writable_or_pagefault(addr, 8)); + let m64 = safe_read64s(addr).unwrap(); + let m64_low = m64 as i32; + let m64_high = (m64 >> 32) as i32; + if read_reg32(EAX) == m64_low && read_reg32(EDX) == m64_high { + *flags |= FLAG_ZERO; + safe_write64( + addr, + read_reg32(EBX) as u32 as u64 | (read_reg32(ECX) as u32 as u64) << 32, + ) + .unwrap(); + } + else { + *flags &= !FLAG_ZERO; + write_reg32(EAX, m64_low); + write_reg32(EDX, m64_high); + } + *flags_changed &= !FLAG_ZERO; +} +pub unsafe fn instr32_0FC7_1_mem(addr: i32) { instr16_0FC7_1_mem(addr) } + +#[no_mangle] +pub unsafe fn instr16_0FC7_6_reg(r: i32) { + // rdrand + let rand = get_rand_int(); + write_reg16(r, rand); + *flags &= !FLAGS_ALL; + *flags |= 1; + *flags_changed = 0; +} +#[no_mangle] +pub unsafe fn instr32_0FC7_6_reg(r: i32) { + // rdrand + let rand = get_rand_int(); + write_reg32(r, rand); + *flags &= !FLAGS_ALL; + *flags |= 1; + *flags_changed = 0; +} + +#[no_mangle] +pub unsafe fn instr16_0FC7_6_mem(_addr: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr32_0FC7_6_mem(_addr: i32) { trigger_ud(); } + +#[no_mangle] +pub unsafe fn instr_0FC8() { bswap(EAX); } +#[no_mangle] +pub unsafe fn instr_0FC9() { bswap(ECX); } +#[no_mangle] +pub unsafe fn instr_0FCA() { bswap(EDX); } +#[no_mangle] +pub unsafe fn instr_0FCB() { bswap(EBX); } +#[no_mangle] +pub unsafe fn instr_0FCC() { bswap(ESP); } +#[no_mangle] +pub unsafe fn instr_0FCD() { bswap(EBP); } +#[no_mangle] +pub unsafe fn instr_0FCE() { bswap(ESI); } +#[no_mangle] +pub unsafe fn instr_0FCF() { bswap(EDI); } +#[no_mangle] +pub unsafe fn instr_0FD0() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0FD1(source: u64, r: i32) { + // psrlw mm, mm/m64 + psrlw_r64(r, source); +} +pub unsafe fn instr_0FD1_reg(r1: i32, r2: i32) { instr_0FD1(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FD1_mem(addr: i32, r: i32) { + instr_0FD1(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FD1(source: reg128, r: i32) { + // psrlw xmm, xmm/m128 + // XXX: Aligned access or #gp + psrlw_r128(r, source.u64[0]); +} +pub unsafe fn instr_660FD1_reg(r1: i32, r2: i32) { instr_660FD1(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FD1_mem(addr: i32, r: i32) { + instr_660FD1(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FD2(source: u64, r: i32) { + // psrld mm, mm/m64 + psrld_r64(r, source); +} +pub unsafe fn instr_0FD2_reg(r1: i32, r2: i32) { instr_0FD2(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FD2_mem(addr: i32, r: i32) { + instr_0FD2(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FD2(source: reg128, r: i32) { + // psrld xmm, xmm/m128 + // XXX: Aligned access or #gp + psrld_r128(r, source.u64[0]); +} +pub unsafe fn instr_660FD2_reg(r1: i32, r2: i32) { instr_660FD2(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FD2_mem(addr: i32, r: i32) { + instr_660FD2(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FD3(source: u64, r: i32) { + // psrlq mm, mm/m64 + psrlq_r64(r, source); +} +pub unsafe fn instr_0FD3_reg(r1: i32, r2: i32) { instr_0FD3(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FD3_mem(addr: i32, r: i32) { + instr_0FD3(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FD3(source: reg128, r: i32) { + // psrlq xmm, mm/m64 + psrlq_r128(r, source.u64[0]); +} +pub unsafe fn instr_660FD3_reg(r1: i32, r2: i32) { instr_660FD3(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FD3_mem(addr: i32, r: i32) { + instr_660FD3(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FD4(source: u64, r: i32) { + // paddq mm, mm/m64 + let destination = read_mmx64s(r); + write_mmx_reg64(r, source + destination); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FD4_reg(r1: i32, r2: i32) { instr_0FD4(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FD4_mem(addr: i32, r: i32) { + instr_0FD4(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FD4(source: reg128, r: i32) { + // paddq xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + result.u64[0] = destination.u64[0] + source.u64[0]; + result.u64[1] = destination.u64[1] + source.u64[1]; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FD4_reg(r1: i32, r2: i32) { instr_660FD4(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FD4_mem(addr: i32, r: i32) { + instr_660FD4(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FD5(source: u64, r: i32) { + // pmullw mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = destination[i] * source[i]; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FD5_reg(r1: i32, r2: i32) { instr_0FD5(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FD5_mem(addr: i32, r: i32) { + instr_0FD5(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FD5(source: reg128, r: i32) { + // pmullw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = destination.u16[i] * source.u16[i] + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FD5_reg(r1: i32, r2: i32) { instr_660FD5(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FD5_mem(addr: i32, r: i32) { + instr_660FD5(return_on_pagefault!(safe_read128s(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0FD6_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0FD6_reg(_r1: i32, _r2: i32) { trigger_ud(); } +pub unsafe fn instr_660FD6_mem(addr: i32, r: i32) { + // movq xmm/m64, xmm + movl_r128_m64(addr, r); +} +pub unsafe fn instr_660FD6_reg(r1: i32, r2: i32) { + // movq xmm/m64, xmm + write_xmm128_2(r1, read_xmm64s(r2), 0); +} + +#[no_mangle] +pub unsafe fn instr_F20FD6_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_F20FD6_reg(r1: i32, r2: i32) { + // movdq2q mm, xmm + write_mmx_reg64(r2, read_xmm128s(r1).u64[0]); + transition_fpu_to_mmx(); +} +#[no_mangle] +pub unsafe fn instr_F30FD6_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_F30FD6_reg(r1: i32, r2: i32) { + // movq2dq xmm, mm + let source = read_mmx64s(r1); + write_xmm_reg128(r2, reg128 { u64: [source, 0] }); + transition_fpu_to_mmx(); +} + +pub unsafe fn instr_0FD7_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0FD7(r1: i32) -> i32 { + // pmovmskb r, mm + let x: [u8; 8] = std::mem::transmute(read_mmx64s(r1)); + let mut result = 0; + for i in 0..8 { + result |= x[i] as i32 >> 7 << i + } + transition_fpu_to_mmx(); + result +} +pub unsafe fn instr_0FD7_reg(r1: i32, r2: i32) { write_reg32(r2, instr_0FD7(r1)); } +pub unsafe fn instr_660FD7_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_660FD7(r1: i32) -> i32 { + // pmovmskb reg, xmm + let x = read_xmm128s(r1); + let mut result = 0; + for i in 0..16 { + result |= x.u8[i] as i32 >> 7 << i + } + result +} +pub unsafe fn instr_660FD7_reg(r1: i32, r2: i32) { write_reg32(r2, instr_660FD7(r1)) } +#[no_mangle] +pub unsafe fn instr_0FD8(source: u64, r: i32) { + // psubusb mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..8 { + result[i] = saturate_sd_to_ub(destination[i] as i32 - source[i] as i32) as u8; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FD8_reg(r1: i32, r2: i32) { instr_0FD8(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FD8_mem(addr: i32, r: i32) { + instr_0FD8(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FD8(source: reg128, r: i32) { + // psubusb xmm, xmm/m128 + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.u8[i] = saturate_sd_to_ub(destination.u8[i] as i32 - source.u8[i] as i32) as u8; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FD8_reg(r1: i32, r2: i32) { instr_660FD8(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FD8_mem(addr: i32, r: i32) { + instr_660FD8(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FD9(source: u64, r: i32) { + // psubusw mm, mm/m64 + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [u16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = saturate_uw(destination[i] as u32 - source[i] as u32) + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FD9_reg(r1: i32, r2: i32) { instr_0FD9(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FD9_mem(addr: i32, r: i32) { + instr_0FD9(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FD9(source: reg128, r: i32) { + // psubusw xmm, xmm/m128 + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = saturate_uw(destination.u16[i] as u32 - source.u16[i] as u32) + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FD9_reg(r1: i32, r2: i32) { instr_660FD9(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FD9_mem(addr: i32, r: i32) { + instr_660FD9(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FDA(source: u64, r: i32) { + // pminub mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..8 { + result[i] = u8::min(source[i], destination[i]) + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FDA_reg(r1: i32, r2: i32) { instr_0FDA(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FDA_mem(addr: i32, r: i32) { + instr_0FDA(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FDA(source: reg128, r: i32) { + // pminub xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { u8: [0; 16] }; + for i in 0..16 { + result.u8[i] = u8::min(source.u8[i], destination.u8[i]); + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FDA_reg(r1: i32, r2: i32) { instr_660FDA(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FDA_mem(addr: i32, r: i32) { + instr_660FDA(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FDB(source: u64, r: i32) { + // pand mm, mm/m64 + let destination = read_mmx64s(r); + write_mmx_reg64(r, source & destination); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FDB_reg(r1: i32, r2: i32) { instr_0FDB(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FDB_mem(addr: i32, r: i32) { + instr_0FDB(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FDB(source: reg128, r: i32) { + // pand xmm, xmm/m128 + // XXX: Aligned access or #gp + pand_r128(source, r); +} +pub unsafe fn instr_660FDB_reg(r1: i32, r2: i32) { instr_660FDB(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FDB_mem(addr: i32, r: i32) { + instr_660FDB(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FDC(source: u64, r: i32) { + // paddusb mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..8 { + result[i] = saturate_ud_to_ub(destination[i] as u32 + source[i] as u32); + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FDC_reg(r1: i32, r2: i32) { instr_0FDC(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FDC_mem(addr: i32, r: i32) { + instr_0FDC(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FDC(source: reg128, r: i32) { + // paddusb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.u8[i] = saturate_ud_to_ub(source.u8[i] as u32 + destination.u8[i] as u32); + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FDC_reg(r1: i32, r2: i32) { instr_660FDC(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FDC_mem(addr: i32, r: i32) { + instr_660FDC(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FDD(source: u64, r: i32) { + // paddusw mm, mm/m64 + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [u16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = saturate_uw(destination[i] as u32 + source[i] as u32) + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FDD_reg(r1: i32, r2: i32) { instr_0FDD(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FDD_mem(addr: i32, r: i32) { + instr_0FDD(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FDD(source: reg128, r: i32) { + // paddusw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = saturate_uw(source.u16[i] as u32 + destination.u16[i] as u32) + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FDD_reg(r1: i32, r2: i32) { instr_660FDD(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FDD_mem(addr: i32, r: i32) { + instr_660FDD(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FDE(source: u64, r: i32) { + // pmaxub mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..8 { + result[i] = u8::max(source[i], destination[i]) + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FDE_reg(r1: i32, r2: i32) { instr_0FDE(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FDE_mem(addr: i32, r: i32) { + instr_0FDE(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FDE(source: reg128, r: i32) { + // pmaxub xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.u8[i] = u8::max(source.u8[i], destination.u8[i]); + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FDE_reg(r1: i32, r2: i32) { instr_660FDE(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FDE_mem(addr: i32, r: i32) { + instr_660FDE(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FDF(source: u64, r: i32) { + // pandn mm, mm/m64 + let destination = read_mmx64s(r); + write_mmx_reg64(r, source & !destination); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FDF_reg(r1: i32, r2: i32) { instr_0FDF(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FDF_mem(addr: i32, r: i32) { + instr_0FDF(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FDF(source: reg128, r: i32) { + // pandn xmm, xmm/m128 + // XXX: Aligned access or #gp + pandn_r128(source, r); +} +pub unsafe fn instr_660FDF_reg(r1: i32, r2: i32) { instr_660FDF(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FDF_mem(addr: i32, r: i32) { + instr_660FDF(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FE0(source: u64, r: i32) { + // pavgb mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..8 { + result[i] = (destination[i] as i32 + source[i] as i32 + 1 >> 1) as u8; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FE0_reg(r1: i32, r2: i32) { instr_0FE0(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FE0_mem(addr: i32, r: i32) { + instr_0FE0(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FE0(source: reg128, r: i32) { + // pavgb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.u8[i] = (destination.u8[i] as i32 + source.u8[i] as i32 + 1 >> 1) as u8; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FE0_reg(r1: i32, r2: i32) { instr_660FE0(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FE0_mem(addr: i32, r: i32) { + instr_660FE0(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FE1(source: u64, r: i32) { + // psraw mm, mm/m64 + psraw_r64(r, source); +} +pub unsafe fn instr_0FE1_reg(r1: i32, r2: i32) { instr_0FE1(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FE1_mem(addr: i32, r: i32) { + instr_0FE1(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FE1(source: reg128, r: i32) { + // psraw xmm, xmm/m128 + // XXX: Aligned access or #gp + psraw_r128(r, source.u64[0]); +} +pub unsafe fn instr_660FE1_reg(r1: i32, r2: i32) { instr_660FE1(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FE1_mem(addr: i32, r: i32) { + instr_660FE1(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FE2(source: u64, r: i32) { + // psrad mm, mm/m64 + psrad_r64(r, source); +} +pub unsafe fn instr_0FE2_reg(r1: i32, r2: i32) { instr_0FE2(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FE2_mem(addr: i32, r: i32) { + instr_0FE2(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FE2(source: reg128, r: i32) { + // psrad xmm, xmm/m128 + // XXX: Aligned access or #gp + psrad_r128(r, source.u64[0]); +} +pub unsafe fn instr_660FE2_reg(r1: i32, r2: i32) { instr_660FE2(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FE2_mem(addr: i32, r: i32) { + instr_660FE2(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FE3(source: u64, r: i32) { + // pavgw mm, mm/m64 + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [u16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = (destination[i] as i32 + source[i] as i32 + 1 >> 1) as u16 + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FE3_reg(r1: i32, r2: i32) { instr_0FE3(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FE3_mem(addr: i32, r: i32) { + instr_0FE3(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FE3(source: reg128, r: i32) { + // pavgw xmm, xmm/m128 + // XXX: Aligned access or #gp + let mut destination = read_xmm128s(r); + for i in 0..8 { + destination.u16[i] = (destination.u16[i] as i32 + source.u16[i] as i32 + 1 >> 1) as u16; + } + write_xmm_reg128(r, destination); +} +pub unsafe fn instr_660FE3_reg(r1: i32, r2: i32) { instr_660FE3(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FE3_mem(addr: i32, r: i32) { + instr_660FE3(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FE4(source: u64, r: i32) { + // pmulhuw mm, mm/m64 + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [u16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = ((destination[i] as i32 * source[i] as i32) >> 16) as u16 + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FE4_reg(r1: i32, r2: i32) { instr_0FE4(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FE4_mem(addr: i32, r: i32) { + instr_0FE4(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FE4(source: reg128, r: i32) { + // pmulhuw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = (source.u16[i] as i32 * destination.u16[i] as i32 >> 16) as u16; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FE4_reg(r1: i32, r2: i32) { instr_660FE4(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FE4_mem(addr: i32, r: i32) { + instr_660FE4(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FE5(source: u64, r: i32) { + // pmulhw mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = ((destination[i] as i32 * source[i] as i32) >> 16) as i16 + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FE5_reg(r1: i32, r2: i32) { instr_0FE5(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FE5_mem(addr: i32, r: i32) { + instr_0FE5(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FE5(source: reg128, r: i32) { + // pmulhw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = (destination.i16[i] as i32 * source.i16[i] as i32 >> 16) as u16 + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FE5_reg(r1: i32, r2: i32) { instr_660FE5(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FE5_mem(addr: i32, r: i32) { + instr_660FE5(return_on_pagefault!(safe_read128s(addr)), r); +} + +#[no_mangle] +pub unsafe fn instr_0FE6_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn instr_0FE6_reg(_r1: i32, _r2: i32) { trigger_ud(); } + +#[no_mangle] +pub unsafe fn instr_660FE6(source: reg128, r: i32) { + // cvttpd2dq xmm1, xmm2/m128 + let result = reg128 { + i32: [ + sse_convert_with_truncation_f64_to_i32(source.f64[0]), + sse_convert_with_truncation_f64_to_i32(source.f64[1]), + 0, + 0, + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FE6_mem(addr: i32, r: i32) { + instr_660FE6(return_on_pagefault!(safe_read128s(addr)), r); +} +pub unsafe fn instr_660FE6_reg(r1: i32, r2: i32) { instr_660FE6(read_xmm128s(r1), r2); } + +#[no_mangle] +pub unsafe fn instr_F20FE6(source: reg128, r: i32) { + // cvtpd2dq xmm1, xmm2/m128 + let result = reg128 { + i32: [ + // XXX: Precision exception + sse_convert_f64_to_i32(source.f64[0]), + sse_convert_f64_to_i32(source.f64[1]), + 0, + 0, + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_F20FE6_mem(addr: i32, r: i32) { + instr_F20FE6(return_on_pagefault!(safe_read128s(addr)), r); +} +pub unsafe fn instr_F20FE6_reg(r1: i32, r2: i32) { instr_F20FE6(read_xmm128s(r1), r2); } + +#[no_mangle] +pub unsafe fn instr_F30FE6(source: u64, r: i32) { + // cvtdq2pd xmm1, xmm2/m64 + let result = reg128 { + f64: [ + // Note: Conversion never fails (i32 fits into f64) + source as i32 as f64, + (source >> 32) as i32 as f64, + ], + }; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_F30FE6_mem(addr: i32, r: i32) { + instr_F30FE6(return_on_pagefault!(safe_read64s(addr)), r); +} +pub unsafe fn instr_F30FE6_reg(r1: i32, r2: i32) { instr_F30FE6(read_xmm64s(r1), r2); } + +#[no_mangle] +pub unsafe fn instr_0FE7_mem(addr: i32, r: i32) { + // movntq m64, mm + mov_r_m64(addr, r); +} +#[no_mangle] +pub unsafe fn instr_0FE7_reg(_r1: i32, _r2: i32) { trigger_ud(); } +pub unsafe fn instr_660FE7_reg(_r1: i32, _r2: i32) { trigger_ud(); } +pub unsafe fn instr_660FE7_mem(addr: i32, r: i32) { + // movntdq m128, xmm + mov_r_m128(addr, r); +} +#[no_mangle] +pub unsafe fn instr_0FE8(source: u64, r: i32) { + // psubsb mm, mm/m64 + let destination: [i8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [i8; 8] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..8 { + result[i] = saturate_sd_to_sb(destination[i] as u32 - source[i] as u32); + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FE8_reg(r1: i32, r2: i32) { instr_0FE8(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FE8_mem(addr: i32, r: i32) { + instr_0FE8(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FE8(source: reg128, r: i32) { + // psubsb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.i8[i] = saturate_sd_to_sb(destination.i8[i] as u32 - source.i8[i] as u32); + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FE8_reg(r1: i32, r2: i32) { instr_660FE8(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FE8_mem(addr: i32, r: i32) { + instr_660FE8(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FE9(source: u64, r: i32) { + // psubsw mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = saturate_sd_to_sw(destination[i] as u32 - source[i] as u32) + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FE9_reg(r1: i32, r2: i32) { instr_0FE9(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FE9_mem(addr: i32, r: i32) { + instr_0FE9(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FE9(source: reg128, r: i32) { + // psubsw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = saturate_sd_to_sw(destination.i16[i] as u32 - source.i16[i] as u32) + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FE9_reg(r1: i32, r2: i32) { instr_660FE9(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FE9_mem(addr: i32, r: i32) { + instr_660FE9(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FEA(source: u64, r: i32) { + // pminsw mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = i16::min(destination[i], source[i]) + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FEA_reg(r1: i32, r2: i32) { instr_0FEA(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FEA_mem(addr: i32, r: i32) { + instr_0FEA(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FEA(source: reg128, r: i32) { + // pminsw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.i16[i] = i16::min(destination.i16[i], source.i16[i]) + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FEA_reg(r1: i32, r2: i32) { instr_660FEA(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FEA_mem(addr: i32, r: i32) { + instr_660FEA(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FEB(source: u64, r: i32) { + // por mm, mm/m64 + let destination = read_mmx64s(r); + write_mmx_reg64(r, source | destination); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FEB_reg(r1: i32, r2: i32) { instr_0FEB(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FEB_mem(addr: i32, r: i32) { + instr_0FEB(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FEB(source: reg128, r: i32) { + // por xmm, xmm/m128 + // XXX: Aligned access or #gp + por_r128(source, r); +} +pub unsafe fn instr_660FEB_reg(r1: i32, r2: i32) { instr_660FEB(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FEB_mem(addr: i32, r: i32) { + instr_660FEB(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FEC(source: u64, r: i32) { + // paddsb mm, mm/m64 + let destination: [i8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [i8; 8] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..8 { + result[i] = saturate_sd_to_sb(destination[i] as u32 + source[i] as u32); + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FEC_reg(r1: i32, r2: i32) { instr_0FEC(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FEC_mem(addr: i32, r: i32) { + instr_0FEC(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FEC(source: reg128, r: i32) { + // paddsb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.i8[i] = saturate_sd_to_sb(destination.i8[i] as u32 + source.i8[i] as u32); + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FEC_reg(r1: i32, r2: i32) { instr_660FEC(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FEC_mem(addr: i32, r: i32) { + instr_660FEC(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FED(source: u64, r: i32) { + // paddsw mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = saturate_sd_to_sw(destination[i] as u32 + source[i] as u32) + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FED_reg(r1: i32, r2: i32) { instr_0FED(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FED_mem(addr: i32, r: i32) { + instr_0FED(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FED(source: reg128, r: i32) { + // paddsw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = saturate_sd_to_sw(destination.i16[i] as u32 + source.i16[i] as u32) + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FED_reg(r1: i32, r2: i32) { instr_660FED(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FED_mem(addr: i32, r: i32) { + instr_660FED(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FEE(source: u64, r: i32) { + // pmaxsw mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = i16::max(destination[i], source[i]) + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FEE_reg(r1: i32, r2: i32) { instr_0FEE(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FEE_mem(addr: i32, r: i32) { + instr_0FEE(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FEE(source: reg128, r: i32) { + // pmaxsw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.i16[i] = i16::max(destination.i16[i], source.i16[i]) + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FEE_reg(r1: i32, r2: i32) { instr_660FEE(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FEE_mem(addr: i32, r: i32) { + instr_660FEE(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FEF(source: u64, r: i32) { + // pxor mm, mm/m64 + let destination = read_mmx64s(r); + write_mmx_reg64(r, source ^ destination); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FEF_reg(r1: i32, r2: i32) { instr_0FEF(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FEF_mem(addr: i32, r: i32) { + instr_0FEF(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FEF(source: reg128, r: i32) { + // pxor xmm, xmm/m128 + // XXX: Aligned access or #gp + pxor_r128(source, r); +} +pub unsafe fn instr_660FEF_reg(r1: i32, r2: i32) { instr_660FEF(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FEF_mem(addr: i32, r: i32) { + instr_660FEF(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FF0() { unimplemented_sse(); } +#[no_mangle] +pub unsafe fn instr_0FF1(source: u64, r: i32) { + // psllw mm, mm/m64 + psllw_r64(r, source); +} +pub unsafe fn instr_0FF1_reg(r1: i32, r2: i32) { instr_0FF1(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FF1_mem(addr: i32, r: i32) { + instr_0FF1(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FF1(source: reg128, r: i32) { + // psllw xmm, xmm/m128 + // XXX: Aligned access or #gp + psllw_r128(r, source.u64[0]); +} +pub unsafe fn instr_660FF1_reg(r1: i32, r2: i32) { instr_660FF1(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FF1_mem(addr: i32, r: i32) { + instr_660FF1(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FF2(source: u64, r: i32) { + // pslld mm, mm/m64 + pslld_r64(r, source); +} +pub unsafe fn instr_0FF2_reg(r1: i32, r2: i32) { instr_0FF2(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FF2_mem(addr: i32, r: i32) { + instr_0FF2(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FF2(source: reg128, r: i32) { + // pslld xmm, xmm/m128 + // XXX: Aligned access or #gp + pslld_r128(r, source.u64[0]); +} +pub unsafe fn instr_660FF2_reg(r1: i32, r2: i32) { instr_660FF2(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FF2_mem(addr: i32, r: i32) { + instr_660FF2(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FF3(source: u64, r: i32) { + // psllq mm, mm/m64 + psllq_r64(r, source); +} +pub unsafe fn instr_0FF3_reg(r1: i32, r2: i32) { instr_0FF3(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FF3_mem(addr: i32, r: i32) { + instr_0FF3(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FF3(source: reg128, r: i32) { + // psllq xmm, xmm/m128 + // XXX: Aligned access or #gp + psllq_r128(r, source.u64[0]); +} +pub unsafe fn instr_660FF3_reg(r1: i32, r2: i32) { instr_660FF3(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FF3_mem(addr: i32, r: i32) { + instr_660FF3(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FF4(source: u64, r: i32) { + // pmuludq mm, mm/m64 + let destination = read_mmx64s(r); + write_mmx_reg64(r, (source as u32 as u64) * (destination as u32 as u64)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FF4_reg(r1: i32, r2: i32) { instr_0FF4(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FF4_mem(addr: i32, r: i32) { + instr_0FF4(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FF4(source: reg128, r: i32) { + // pmuludq xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + result.u64[0] = source.u32[0] as u64 * destination.u32[0] as u64; + result.u64[1] = source.u32[2] as u64 * destination.u32[2] as u64; + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FF4_reg(r1: i32, r2: i32) { instr_660FF4(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FF4_mem(addr: i32, r: i32) { + instr_660FF4(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FF5(source: u64, r: i32) { + // pmaddwd mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mul0 = destination[0] as i32 * source[0] as i32; + let mul1 = destination[1] as i32 * source[1] as i32; + let mul2 = destination[2] as i32 * source[2] as i32; + let mul3 = destination[3] as i32 * source[3] as i32; + let low = mul0 + mul1; + let high = mul2 + mul3; + write_mmx_reg64(r, low as u32 as u64 | (high as u64) << 32); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FF5_reg(r1: i32, r2: i32) { instr_0FF5(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FF5_mem(addr: i32, r: i32) { + instr_0FF5(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FF5(source: reg128, r: i32) { + // pmaddwd xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..4 { + result.i32[i] = destination.i16[2 * i] as i32 * source.i16[2 * i] as i32 + + destination.i16[2 * i + 1] as i32 * source.i16[2 * i + 1] as i32 + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FF5_reg(r1: i32, r2: i32) { instr_660FF5(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FF5_mem(addr: i32, r: i32) { + instr_660FF5(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FF6(source: u64, r: i32) { + // psadbw mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut sum = 0; + for i in 0..8 { + sum += (destination[i] as i32 - source[i] as i32).abs() as u64; + } + write_mmx_reg64(r, sum); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FF6_reg(r1: i32, r2: i32) { instr_0FF6(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FF6_mem(addr: i32, r: i32) { + instr_0FF6(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FF6(source: reg128, r: i32) { + // psadbw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut sum0 = 0; + let mut sum1 = 0; + for i in 0..8 { + sum0 += (destination.u8[i + 0] as i32 - source.u8[i + 0] as i32).abs() as u32; + sum1 += (destination.u8[i + 8] as i32 - source.u8[i + 8] as i32).abs() as u32; + } + write_xmm128(r, sum0 as i32, 0, sum1 as i32, 0); +} +pub unsafe fn instr_660FF6_reg(r1: i32, r2: i32) { instr_660FF6(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FF6_mem(addr: i32, r: i32) { + instr_660FF6(return_on_pagefault!(safe_read128s(addr)), r); +} + +pub unsafe fn instr_0FF7_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn maskmovq(r1: i32, r2: i32, addr: i32) { + // maskmovq mm, mm + let source: [u8; 8] = std::mem::transmute(read_mmx64s(r2)); + let mask: [u8; 8] = std::mem::transmute(read_mmx64s(r1)); + match writable_or_pagefault(addr, 8) { + Ok(()) => *page_fault = false, + Err(()) => { + *page_fault = true; + return; + }, + } + for i in 0..8 { + if 0 != mask[i] & 0x80 { + safe_write8(addr + i as i32, source[i] as i32).unwrap(); + } + } + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FF7_reg(r1: i32, r2: i32) { + maskmovq( + r1, + r2, + return_on_pagefault!(get_seg_prefix_ds(get_reg_asize(EDI))), + ) +} + +pub unsafe fn instr_660FF7_mem(_addr: i32, _r: i32) { trigger_ud(); } +#[no_mangle] +pub unsafe fn maskmovdqu(r1: i32, r2: i32, addr: i32) { + // maskmovdqu xmm, xmm + let source = read_xmm128s(r2); + let mask = read_xmm128s(r1); + match writable_or_pagefault(addr, 16) { + Ok(()) => *page_fault = false, + Err(()) => { + *page_fault = true; + return; + }, + } + for i in 0..16 { + if 0 != mask.u8[i] & 0x80 { + safe_write8(addr + i as i32, source.u8[i] as i32).unwrap(); + } + } +} +pub unsafe fn instr_660FF7_reg(r1: i32, r2: i32) { + maskmovdqu( + r1, + r2, + return_on_pagefault!(get_seg_prefix_ds(get_reg_asize(EDI))), + ) +} +#[no_mangle] +pub unsafe fn instr_0FF8(source: u64, r: i32) { + // psubb mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..8 { + result[i] = destination[i] - source[i]; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FF8_reg(r1: i32, r2: i32) { instr_0FF8(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FF8_mem(addr: i32, r: i32) { + instr_0FF8(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FF8(source: reg128, r: i32) { + // psubb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.u8[i] = destination.u8[i] - source.u8[i]; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FF8_reg(r1: i32, r2: i32) { instr_660FF8(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FF8_mem(addr: i32, r: i32) { + instr_660FF8(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FF9(source: u64, r: i32) { + // psubw mm, mm/m64 + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [i16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = destination[i] - source[i] + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FF9_reg(r1: i32, r2: i32) { instr_0FF9(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FF9_mem(addr: i32, r: i32) { + instr_0FF9(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FF9(source: reg128, r: i32) { + // psubw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.i16[i] = destination.i16[i] - source.i16[i] + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FF9_reg(r1: i32, r2: i32) { instr_660FF9(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FF9_mem(addr: i32, r: i32) { + instr_660FF9(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FFA(source: u64, r: i32) { + // psubd mm, mm/m64 + let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r)); + let source: [i32; 2] = std::mem::transmute(source); + let mut result = [0; 2]; + for i in 0..2 { + result[i] = destination[i] - source[i] + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FFA_reg(r1: i32, r2: i32) { instr_0FFA(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FFA_mem(addr: i32, r: i32) { + instr_0FFA(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FFA(source: reg128, r: i32) { + // psubd xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + write_xmm128( + r, + destination.i32[0] - source.i32[0], + destination.i32[1] - source.i32[1], + destination.i32[2] - source.i32[2], + destination.i32[3] - source.i32[3], + ); +} +pub unsafe fn instr_660FFA_reg(r1: i32, r2: i32) { instr_660FFA(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FFA_mem(addr: i32, r: i32) { + instr_660FFA(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FFB(source: u64, r: i32) { + // psubq mm, mm/m64 + write_mmx_reg64(r, read_mmx64s(r) - source); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FFB_reg(r1: i32, r2: i32) { instr_0FFB(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FFB_mem(addr: i32, r: i32) { + instr_0FFB(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FFB(source: reg128, r: i32) { + // psubq xmm, xmm/m128 + // XXX: Aligned access or #gp + let mut destination = read_xmm128s(r); + destination.u64[0] = destination.u64[0] - source.u64[0]; + destination.u64[1] = destination.u64[1] - source.u64[1]; + write_xmm_reg128(r, destination); +} +pub unsafe fn instr_660FFB_reg(r1: i32, r2: i32) { instr_660FFB(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FFB_mem(addr: i32, r: i32) { + instr_660FFB(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FFC(source: u64, r: i32) { + // paddb mm, mm/m64 + let destination: [u8; 8] = std::mem::transmute(read_mmx64s(r)); + let source: [u8; 8] = std::mem::transmute(source); + let mut result = [0; 8]; + for i in 0..8 { + result[i] = destination[i] + source[i]; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FFC_reg(r1: i32, r2: i32) { instr_0FFC(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FFC_mem(addr: i32, r: i32) { + instr_0FFC(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FFC(source: reg128, r: i32) { + // paddb xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..16 { + result.u8[i] = destination.u8[i] + source.u8[i]; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FFC_reg(r1: i32, r2: i32) { instr_660FFC(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FFC_mem(addr: i32, r: i32) { + instr_660FFC(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FFD(source: u64, r: i32) { + // paddw mm, mm/m64 + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let source: [u16; 4] = std::mem::transmute(source); + let mut result = [0; 4]; + for i in 0..4 { + result[i] = destination[i] + source[i] + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FFD_reg(r1: i32, r2: i32) { instr_0FFD(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FFD_mem(addr: i32, r: i32) { + instr_0FFD(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FFD(source: reg128, r: i32) { + // paddw xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + for i in 0..8 { + result.u16[i] = (destination.u16[i] as i32 + source.u16[i] as i32 & 0xFFFF) as u16; + } + write_xmm_reg128(r, result); +} +pub unsafe fn instr_660FFD_reg(r1: i32, r2: i32) { instr_660FFD(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FFD_mem(addr: i32, r: i32) { + instr_660FFD(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FFE(source: u64, r: i32) { + // paddd mm, mm/m64 + let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r)); + let source: [i32; 2] = std::mem::transmute(source); + let mut result = [0; 2]; + for i in 0..2 { + result[i] = destination[i] + source[i] + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn instr_0FFE_reg(r1: i32, r2: i32) { instr_0FFE(read_mmx64s(r1), r2); } +pub unsafe fn instr_0FFE_mem(addr: i32, r: i32) { + instr_0FFE(return_on_pagefault!(safe_read64s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_660FFE(source: reg128, r: i32) { + // paddd xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let dword0 = destination.i32[0] + source.i32[0]; + let dword1 = destination.i32[1] + source.i32[1]; + let dword2 = destination.i32[2] + source.i32[2]; + let dword3 = destination.i32[3] + source.i32[3]; + write_xmm128(r, dword0, dword1, dword2, dword3); +} +pub unsafe fn instr_660FFE_reg(r1: i32, r2: i32) { instr_660FFE(read_xmm128s(r1), r2); } +pub unsafe fn instr_660FFE_mem(addr: i32, r: i32) { + instr_660FFE(return_on_pagefault!(safe_read128s(addr)), r); +} +#[no_mangle] +pub unsafe fn instr_0FFF() { + // Windows 98 + dbg_log!("#ud: 0F FF"); + trigger_ud(); +} diff --git a/src/rust/cpu/memory.rs b/src/rust/cpu/memory.rs new file mode 100644 index 0000000..57d40af --- /dev/null +++ b/src/rust/cpu/memory.rs @@ -0,0 +1,301 @@ +mod ext { + extern "C" { + pub fn mmap_read8(addr: u32) -> i32; + pub fn mmap_read16(addr: u32) -> i32; + pub fn mmap_read32(addr: u32) -> i32; + + pub fn mmap_write8(addr: u32, value: i32); + pub fn mmap_write16(addr: u32, value: i32); + pub fn mmap_write32(addr: u32, value: i32); + pub fn mmap_write64(addr: u32, v0: i32, v1: i32); + pub fn mmap_write128(addr: u32, v0: i32, v1: i32, v2: i32, v3: i32); + } +} + +use cpu::cpu::reg128; +use cpu::global_pointers::memory_size; +use cpu::vga; +use page::Page; + +use std::alloc; +use std::ptr; + +#[allow(non_upper_case_globals)] +pub static mut mem8: *mut u8 = ptr::null_mut(); + +#[no_mangle] +pub fn allocate_memory(size: u32) -> u32 { + unsafe { + dbg_assert!(mem8.is_null()); + }; + dbg_log!("Allocate memory size={}m", size >> 20); + let layout = alloc::Layout::from_size_align(size as usize, 0x1000).unwrap(); + let ptr = unsafe { alloc::alloc(layout) as u32 }; + unsafe { + mem8 = ptr as *mut u8; + }; + ptr +} + +#[no_mangle] +pub unsafe fn zero_memory(size: u32) { ptr::write_bytes(mem8, 0, size as usize); } + +#[allow(non_upper_case_globals)] +pub static mut vga_mem8: *mut u8 = ptr::null_mut(); +#[allow(non_upper_case_globals)] +pub static mut vga_memory_size: u32 = 0; + +#[no_mangle] +pub fn svga_allocate_memory(size: u32) -> u32 { + unsafe { + dbg_assert!(vga_mem8.is_null()); + }; + let layout = alloc::Layout::from_size_align(size as usize, 0x1000).unwrap(); + let ptr = unsafe { alloc::alloc(layout) as u32 }; + dbg_assert!( + size & (1 << 12 << 6) == 0, + "size not aligned to dirty_bitmap" + ); + unsafe { + vga_mem8 = ptr as *mut u8; + vga_memory_size = size; + vga::dirty_bitmap.resize((size >> 12 >> 6) as usize, 0); + }; + ptr +} + +#[no_mangle] +pub fn in_mapped_range(addr: u32) -> bool { + return addr >= 0xA0000 && addr < 0xC0000 || addr >= unsafe { *memory_size }; +} + +pub const VGA_LFB_ADDRESS: u32 = 0xE0000000; +pub fn in_svga_lfb(addr: u32) -> bool { + addr >= VGA_LFB_ADDRESS && addr < unsafe { VGA_LFB_ADDRESS + vga_memory_size } +} + +#[no_mangle] +pub fn read8(addr: u32) -> i32 { + if in_mapped_range(addr) { + if in_svga_lfb(addr) { + unsafe { *vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) as i32 } + } + else { + unsafe { ext::mmap_read8(addr) } + } + } + else { + read8_no_mmap_check(addr) + } +} +pub fn read8_no_mmap_check(addr: u32) -> i32 { unsafe { *mem8.offset(addr as isize) as i32 } } + +#[no_mangle] +pub fn read16(addr: u32) -> i32 { + if in_mapped_range(addr) { + if in_svga_lfb(addr) { + unsafe { *(vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) as *const u16) as i32 } + } + else { + unsafe { ext::mmap_read16(addr) } + } + } + else { + read16_no_mmap_check(addr) + } +} +pub fn read16_no_mmap_check(addr: u32) -> i32 { + unsafe { *(mem8.offset(addr as isize) as *mut u16) as i32 } +} + +#[no_mangle] +pub fn read32s(addr: u32) -> i32 { + if in_mapped_range(addr) { + if in_svga_lfb(addr) { + unsafe { *(vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) as *const i32) } + } + else { + unsafe { ext::mmap_read32(addr) } + } + } + else { + read32_no_mmap_check(addr) + } +} +pub fn read32_no_mmap_check(addr: u32) -> i32 { + unsafe { *(mem8.offset(addr as isize) as *mut i32) } +} + +pub unsafe fn read64s(addr: u32) -> i64 { + if in_mapped_range(addr) { + if in_svga_lfb(addr) { + *(vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) as *const i64) + } + else { + ext::mmap_read32(addr) as i64 | (ext::mmap_read32(addr + 4) as i64) << 32 + } + } + else { + *(mem8.offset(addr as isize) as *mut i64) + } +} + +pub unsafe fn read128(addr: u32) -> reg128 { + if in_mapped_range(addr) { + if in_svga_lfb(addr) { + reg128 { + i64: [ + *(vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) as *const i64), + *(vga_mem8.offset((addr - VGA_LFB_ADDRESS + 8) as isize) as *const i64), + ], + } + } + else { + reg128 { + i32: [ + ext::mmap_read32(addr + 0), + ext::mmap_read32(addr + 4), + ext::mmap_read32(addr + 8), + ext::mmap_read32(addr + 12), + ], + } + } + } + else { + reg128 { + i64: [ + *(mem8.offset(addr as isize) as *mut i64), + *(mem8.offset(addr as isize).offset(8) as *mut i64), + ], + } + } +} + +#[no_mangle] +pub unsafe fn write8(addr: u32, value: i32) { + if in_mapped_range(addr) { + mmap_write8(addr, value & 0xFF); + } + else { + ::jit::jit_dirty_page(::jit::get_jit_state(), Page::page_of(addr)); + write8_no_mmap_or_dirty_check(addr, value); + }; +} + +pub unsafe fn write8_no_mmap_or_dirty_check(addr: u32, value: i32) { + *mem8.offset(addr as isize) = value as u8 +} + +#[no_mangle] +pub unsafe fn write16(addr: u32, value: i32) { + if in_mapped_range(addr) { + mmap_write16(addr, value & 0xFFFF); + } + else { + ::jit::jit_dirty_cache_small(addr, addr + 2); + write16_no_mmap_or_dirty_check(addr, value); + }; +} +pub unsafe fn write16_no_mmap_or_dirty_check(addr: u32, value: i32) { + *(mem8.offset(addr as isize) as *mut u16) = value as u16 +} + +#[no_mangle] +pub unsafe fn write32(addr: u32, value: i32) { + if in_mapped_range(addr) { + mmap_write32(addr, value); + } + else { + ::jit::jit_dirty_cache_small(addr, addr + 4); + write32_no_mmap_or_dirty_check(addr, value); + }; +} + +pub unsafe fn write32_no_mmap_or_dirty_check(addr: u32, value: i32) { + *(mem8.offset(addr as isize) as *mut i32) = value +} + +pub unsafe fn write64_no_mmap_or_dirty_check(addr: u32, value: u64) { + *(mem8.offset(addr as isize) as *mut u64) = value +} + +pub unsafe fn write128_no_mmap_or_dirty_check(addr: u32, value: reg128) { + *(mem8.offset(addr as isize) as *mut reg128) = value +} + +pub unsafe fn memset_no_mmap_or_dirty_check(addr: u32, value: u8, count: u32) { + ptr::write_bytes(mem8.offset(addr as isize), value, count as usize); +} + +pub unsafe fn memcpy_no_mmap_or_dirty_check(src_addr: u32, dst_addr: u32, count: u32) { + dbg_assert!(src_addr < *memory_size); + dbg_assert!(dst_addr < *memory_size); + ptr::copy( + mem8.offset(src_addr as isize), + mem8.offset(dst_addr as isize), + count as usize, + ) +} + +pub unsafe fn memcpy_into_svga_lfb(src_addr: u32, dst_addr: u32, count: u32) { + dbg_assert!(src_addr < *memory_size); + dbg_assert!(in_svga_lfb(dst_addr)); + ptr::copy_nonoverlapping( + mem8.offset(src_addr as isize), + vga_mem8.offset((dst_addr - VGA_LFB_ADDRESS) as isize), + count as usize, + ) +} + +pub unsafe fn mmap_write8(addr: u32, value: i32) { + if in_svga_lfb(addr) { + vga::mark_dirty(addr); + *vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) = value as u8 + } + else { + ext::mmap_write8(addr, value) + } +} +pub unsafe fn mmap_write16(addr: u32, value: i32) { + if in_svga_lfb(addr) { + vga::mark_dirty(addr); + *(vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) as *mut u16) = value as u16 + } + else { + ext::mmap_write16(addr, value) + } +} +pub unsafe fn mmap_write32(addr: u32, value: i32) { + if in_svga_lfb(addr) { + vga::mark_dirty(addr); + *(vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) as *mut i32) = value + } + else { + ext::mmap_write32(addr, value) + } +} +pub unsafe fn mmap_write64(addr: u32, value: u64) { + if in_svga_lfb(addr) { + vga::mark_dirty(addr); + *(vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) as *mut u64) = value + } + else { + ext::mmap_write64(addr, value as i32, (value >> 32) as i32) + } +} +pub unsafe fn mmap_write128(addr: u32, v0: u64, v1: u64) { + if in_svga_lfb(addr) { + vga::mark_dirty(addr); + *(vga_mem8.offset((addr - VGA_LFB_ADDRESS) as isize) as *mut u64) = v0; + *(vga_mem8.offset((addr - VGA_LFB_ADDRESS + 8) as isize) as *mut u64) = v1 + } + else { + ext::mmap_write128( + addr, + v0 as i32, + (v0 >> 32) as i32, + v1 as i32, + (v1 >> 32) as i32, + ) + } +} diff --git a/src/rust/cpu/misc_instr.rs b/src/rust/cpu/misc_instr.rs new file mode 100644 index 0000000..09ad6c4 --- /dev/null +++ b/src/rust/cpu/misc_instr.rs @@ -0,0 +1,593 @@ +use cpu::cpu::*; +use cpu::fpu::{ + fpu_load_m80, fpu_load_status_word, fpu_set_status_word, fpu_store_m80, set_control_word, +}; +use cpu::global_pointers::*; +use paging::OrPageFault; + +pub unsafe fn getcf() -> bool { + if 0 != *flags_changed & 1 { + let m = (2 << *last_op_size) - 1; + dbg_assert!((*last_op1 as u32) <= m); + dbg_assert!((*last_result as u32) <= m); + + let sub_mask = *flags_changed >> 31; + + // sub: last_op1 < last_result (or last_op1 < last_op2) (or (result ^ ((result ^ b) & (b ^ a)))) + // add: last_result < last_op1 (or last_result < last_op2) (or a ^ ((a ^ b) & (b ^ result))) + return ((*last_result as i32 ^ sub_mask) as u32) < (*last_op1 ^ sub_mask) as u32; + } + else { + return 0 != *flags & 1; + }; +} +#[no_mangle] +pub unsafe fn getpf() -> bool { + if 0 != *flags_changed & FLAG_PARITY { + // inverted lookup table + return 0 != 0x9669 << 2 >> ((*last_result ^ *last_result >> 4) & 15) & FLAG_PARITY; + } + else { + return 0 != *flags & FLAG_PARITY; + }; +} +pub unsafe fn getaf() -> bool { + if 0 != *flags_changed & FLAG_ADJUST { + let is_sub = *flags_changed & FLAG_SUB != 0; + let last_op2 = (*last_result - *last_op1) * if is_sub { -1 } else { 1 }; + return 0 != (*last_op1 ^ last_op2 ^ *last_result) & FLAG_ADJUST; + } + else { + return 0 != *flags & FLAG_ADJUST; + }; +} +pub unsafe fn getzf() -> bool { + if 0 != *flags_changed & FLAG_ZERO { + return 0 != (!*last_result & *last_result - 1) >> *last_op_size & 1; + } + else { + return 0 != *flags & FLAG_ZERO; + }; +} +pub unsafe fn getsf() -> bool { + if 0 != *flags_changed & FLAG_SIGN { + return 0 != *last_result >> *last_op_size & 1; + } + else { + return 0 != *flags & FLAG_SIGN; + }; +} +pub unsafe fn getof() -> bool { + if 0 != *flags_changed & FLAG_OVERFLOW { + let is_sub = (*flags_changed as u32) >> 31; + + // add: (a ^ result) & (b ^ result) + // sub: (a ^ result) & (b ^ result ^ 1) (or (a ^ b) & (result ^ a)) + let b_xor_1_if_sub = (*last_result - *last_op1) - is_sub as i32; + return 0 + != ((*last_op1 ^ *last_result) & (b_xor_1_if_sub ^ *last_result)) >> *last_op_size & 1; + } + else { + return 0 != *flags & FLAG_OVERFLOW; + }; +} + +pub unsafe fn test_o() -> bool { return getof(); } +pub unsafe fn test_b() -> bool { return getcf(); } +pub unsafe fn test_z() -> bool { return getzf(); } +pub unsafe fn test_s() -> bool { return getsf(); } +#[no_mangle] +pub unsafe fn test_p() -> bool { return getpf(); } +pub unsafe fn test_be() -> bool { return getcf() || getzf(); } +pub unsafe fn test_l() -> bool { return getsf() != getof(); } +pub unsafe fn test_le() -> bool { return getzf() || getsf() != getof(); } +pub unsafe fn test_no() -> bool { return !test_o(); } +pub unsafe fn test_nb() -> bool { return !test_b(); } +pub unsafe fn test_nz() -> bool { return !test_z(); } +pub unsafe fn test_ns() -> bool { return !test_s(); } +#[no_mangle] +pub unsafe fn test_np() -> bool { return !test_p(); } +pub unsafe fn test_nbe() -> bool { return !test_be(); } +pub unsafe fn test_nl() -> bool { return !test_l(); } +pub unsafe fn test_nle() -> bool { return !test_le(); } + +pub unsafe fn jmp_rel16(rel16: i32) { + let cs_offset = get_seg_cs(); + // limit ip to 16 bit + *instruction_pointer = cs_offset + (*instruction_pointer - cs_offset + rel16 & 0xFFFF); +} +pub unsafe fn jmpcc16(condition: bool, imm16: i32) { + if condition { + jmp_rel16(imm16); + }; +} +pub unsafe fn jmpcc32(condition: bool, imm32: i32) { + if condition { + *instruction_pointer += imm32 + }; +} +pub unsafe fn loope16(imm8s: i32) { jmpcc16(0 != decr_ecx_asize(is_asize_32()) && getzf(), imm8s); } +pub unsafe fn loopne16(imm8s: i32) { + jmpcc16(0 != decr_ecx_asize(is_asize_32()) && !getzf(), imm8s); +} +pub unsafe fn loop16(imm8s: i32) { jmpcc16(0 != decr_ecx_asize(is_asize_32()), imm8s); } +pub unsafe fn jcxz16(imm8s: i32) { jmpcc16(get_reg_asize(ECX) == 0, imm8s); } +pub unsafe fn loope32(imm8s: i32) { jmpcc32(0 != decr_ecx_asize(is_asize_32()) && getzf(), imm8s); } +pub unsafe fn loopne32(imm8s: i32) { + jmpcc32(0 != decr_ecx_asize(is_asize_32()) && !getzf(), imm8s); +} +pub unsafe fn loop32(imm8s: i32) { jmpcc32(0 != decr_ecx_asize(is_asize_32()), imm8s); } +pub unsafe fn jcxz32(imm8s: i32) { jmpcc32(get_reg_asize(ECX) == 0, imm8s); } + +pub unsafe fn cmovcc16(condition: bool, value: i32, r: i32) { + if condition { + write_reg16(r, value); + }; +} +pub unsafe fn cmovcc32(condition: bool, value: i32, r: i32) { + if condition { + write_reg32(r, value); + }; +} + +pub unsafe fn get_stack_pointer(offset: i32) -> i32 { + if *stack_size_32 { + return get_seg_ss() + read_reg32(ESP) + offset; + } + else { + return get_seg_ss() + (read_reg16(SP) + offset & 0xFFFF); + }; +} +pub unsafe fn adjust_stack_reg(adjustment: i32) { + if *stack_size_32 { + write_reg32(ESP, read_reg32(ESP) + adjustment); + } + else { + write_reg16(SP, read_reg16(SP) + adjustment); + }; +} + +pub unsafe fn push16_ss16(imm16: i32) -> OrPageFault<()> { + let sp = get_seg_ss() + (read_reg16(SP) - 2 & 0xFFFF); + safe_write16(sp, imm16)?; + write_reg16(SP, read_reg16(SP) - 2); + Ok(()) +} +pub unsafe fn push16_ss32(imm16: i32) -> OrPageFault<()> { + let sp = get_seg_ss() + read_reg32(ESP) - 2; + safe_write16(sp, imm16)?; + write_reg32(ESP, read_reg32(ESP) - 2); + Ok(()) +} + +pub unsafe fn push16_ss16_mem(addr: i32) -> OrPageFault<()> { push16_ss16(safe_read16(addr)?) } +pub unsafe fn push16_ss32_mem(addr: i32) -> OrPageFault<()> { push16_ss32(safe_read16(addr)?) } + +pub unsafe fn push16(imm16: i32) -> OrPageFault<()> { + if *stack_size_32 { push16_ss32(imm16) } else { push16_ss16(imm16) } +} + +pub unsafe fn push32_ss16(imm32: i32) -> OrPageFault<()> { + let new_sp = read_reg16(SP) - 4 & 0xFFFF; + safe_write32(get_seg_ss() + new_sp, imm32)?; + write_reg16(SP, new_sp); + Ok(()) +} +pub unsafe fn push32_ss32(imm32: i32) -> OrPageFault<()> { + let new_esp = read_reg32(ESP) - 4; + safe_write32(get_seg_ss() + new_esp, imm32)?; + write_reg32(ESP, new_esp); + Ok(()) +} + +pub unsafe fn push32_ss16_mem(addr: i32) -> OrPageFault<()> { push32_ss16(safe_read32s(addr)?) } +pub unsafe fn push32_ss32_mem(addr: i32) -> OrPageFault<()> { push32_ss32(safe_read32s(addr)?) } + +pub unsafe fn push32(imm32: i32) -> OrPageFault<()> { + if *stack_size_32 { push32_ss32(imm32) } else { push32_ss16(imm32) } +} + +pub unsafe fn push32_sreg(i: i32) -> OrPageFault<()> { + // you can't make this up ... + if *stack_size_32 { + let new_esp = read_reg32(ESP) - 4; + safe_write16(get_seg_ss() + new_esp, *sreg.offset(i as isize) as i32)?; + write_reg32(ESP, new_esp); + } + else { + let new_sp = read_reg16(SP) - 4 & 0xFFFF; + safe_write16(get_seg_ss() + new_sp, *sreg.offset(i as isize) as i32)?; + write_reg16(SP, new_sp); + } + Ok(()) +} + +pub unsafe fn pop16() -> OrPageFault { + if *stack_size_32 { pop16_ss32() } else { pop16_ss16() } +} +pub unsafe fn pop16_ss16() -> OrPageFault { + let sp = get_seg_ss() + read_reg16(SP); + let result = safe_read16(sp)?; + write_reg16(SP, read_reg16(SP) + 2); + Ok(result) +} +pub unsafe fn pop16_ss32() -> OrPageFault { + let esp = get_seg_ss() + read_reg32(ESP); + let result = safe_read16(esp)?; + write_reg32(ESP, read_reg32(ESP) + 2); + Ok(result) +} +pub unsafe fn pop32s() -> OrPageFault { + if *stack_size_32 { pop32s_ss32() } else { pop32s_ss16() } +} +pub unsafe fn pop32s_ss16() -> OrPageFault { + let sp = read_reg16(SP); + let result = safe_read32s(get_seg_ss() + sp)?; + write_reg16(SP, sp + 4); + Ok(result) +} +pub unsafe fn pop32s_ss32() -> OrPageFault { + let esp = read_reg32(ESP); + let result = safe_read32s(get_seg_ss() + esp)?; + write_reg32(ESP, read_reg32(ESP) + 4); + Ok(result) +} +pub unsafe fn pusha16() { + let temp = read_reg16(SP); + // make sure we don't get a pagefault after having + // pushed several registers already + return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-16), 16)); + push16(read_reg16(AX)).unwrap(); + push16(read_reg16(CX)).unwrap(); + push16(read_reg16(DX)).unwrap(); + push16(read_reg16(BX)).unwrap(); + push16(temp as i32).unwrap(); + push16(read_reg16(BP)).unwrap(); + push16(read_reg16(SI)).unwrap(); + push16(read_reg16(DI)).unwrap(); +} +pub unsafe fn pusha32() { + let temp = read_reg32(ESP); + return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-32), 32)); + push32(read_reg32(EAX)).unwrap(); + push32(read_reg32(ECX)).unwrap(); + push32(read_reg32(EDX)).unwrap(); + push32(read_reg32(EBX)).unwrap(); + push32(temp).unwrap(); + push32(read_reg32(EBP)).unwrap(); + push32(read_reg32(ESI)).unwrap(); + push32(read_reg32(EDI)).unwrap(); +} + +pub unsafe fn lss16(addr: i32, reg: i32, seg: i32) { + let new_reg = return_on_pagefault!(safe_read16(addr)); + let new_seg = return_on_pagefault!(safe_read16(addr + 2)); + + if !switch_seg(seg, new_seg) { + return; + } + + write_reg16(reg, new_reg); +} + +pub unsafe fn lss32(addr: i32, reg: i32, seg: i32) { + let new_reg = return_on_pagefault!(safe_read32s(addr)); + let new_seg = return_on_pagefault!(safe_read16(addr + 4)); + + if !switch_seg(seg, new_seg) { + return; + } + + write_reg32(reg, new_reg); +} + +pub unsafe fn enter16(size: i32, mut nesting_level: i32) { + nesting_level &= 31; + + if nesting_level > 0 { + dbg_log!( + "enter16 stack={} size={} nest={}", + (if *stack_size_32 { 16 } else { 32 }), + size, + nesting_level, + ); + } + + let ss_mask = if *stack_size_32 { -1 } else { 0xFFFF }; + let ss = get_seg_ss(); + let frame_temp = read_reg32(ESP) - 2; + + if nesting_level > 0 { + let mut tmp_ebp = read_reg32(EBP); + for _ in 1..nesting_level { + tmp_ebp -= 2; + push16(safe_read16(ss + (tmp_ebp & ss_mask)).unwrap()).unwrap(); + } + push16(frame_temp).unwrap(); + } + + return_on_pagefault!(safe_write16(ss + (frame_temp & ss_mask), read_reg16(BP))); + write_reg16(BP, frame_temp); + adjust_stack_reg(-size - 2); +} + +pub unsafe fn enter32(size: i32, mut nesting_level: i32) { + nesting_level &= 31; + + if nesting_level > 0 { + dbg_log!( + "enter32 stack={} size={} nest={}", + (if *stack_size_32 { 16 } else { 32 }), + size, + nesting_level, + ); + } + + let ss_mask = if *stack_size_32 { -1 } else { 0xFFFF }; + let ss = get_seg_ss(); + let frame_temp = read_reg32(ESP) - 4; + + if nesting_level > 0 { + let mut tmp_ebp = read_reg32(EBP); + for _ in 1..nesting_level { + tmp_ebp -= 4; + push32(safe_read32s(ss + (tmp_ebp & ss_mask)).unwrap()).unwrap(); + } + push32(frame_temp).unwrap(); + } + + return_on_pagefault!(safe_write32(ss + (frame_temp & ss_mask), read_reg32(EBP))); + write_reg32(EBP, frame_temp); + adjust_stack_reg(-size - 4); +} + +pub unsafe fn setcc_reg(condition: bool, r: i32) { write_reg8(r, condition as i32); } +pub unsafe fn setcc_mem(condition: bool, addr: i32) { + return_on_pagefault!(safe_write8(addr, condition as i32)); +} + +pub unsafe fn fxsave(addr: i32) { + dbg_assert!(addr & 0xF == 0, "TODO: #gp"); + return_on_pagefault!(writable_or_pagefault(addr, 288)); + + safe_write16(addr + 0, (*fpu_control_word).into()).unwrap(); + safe_write16(addr + 2, fpu_load_status_word().into()).unwrap(); + safe_write8(addr + 4, !*fpu_stack_empty as i32 & 0xFF).unwrap(); + safe_write16(addr + 6, *fpu_opcode).unwrap(); + safe_write32(addr + 8, *fpu_ip).unwrap(); + safe_write16(addr + 12, *fpu_ip_selector).unwrap(); + safe_write32(addr + 16, *fpu_dp).unwrap(); + safe_write16(addr + 20, *fpu_dp_selector).unwrap(); + + safe_write32(addr + 24, *mxcsr).unwrap(); + safe_write32(addr + 28, MXCSR_MASK).unwrap(); + + for i in 0..8 { + let reg_index = i + *fpu_stack_ptr as i32 & 7; + fpu_store_m80(addr + 32 + (i << 4), *fpu_st.offset(reg_index as isize)); + } + + // If the OSFXSR bit in control register CR4 is not set, the FXSAVE + // instruction may not save these registers. This behavior is + // implementation dependent. + for i in 0..8 { + safe_write128(addr + 160 + (i << 4), *reg_xmm.offset(i as isize)).unwrap(); + } +} +pub unsafe fn fxrstor(addr: i32) { + dbg_assert!(addr & 0xF == 0, "TODO: #gp"); + return_on_pagefault!(readable_or_pagefault(addr, 288)); + + let new_mxcsr = safe_read32s(addr + 24).unwrap(); + + if 0 != new_mxcsr & !MXCSR_MASK { + dbg_log!("#gp Invalid mxcsr bits"); + trigger_gp(0); + return; + } + + set_control_word(safe_read16(addr + 0).unwrap() as u16); + fpu_set_status_word(safe_read16(addr + 2).unwrap() as u16); + *fpu_stack_empty = !safe_read8(addr + 4).unwrap() as u8; + *fpu_opcode = safe_read16(addr + 6).unwrap(); + *fpu_ip = safe_read32s(addr + 8).unwrap(); + *fpu_ip_selector = safe_read16(addr + 12).unwrap(); + *fpu_dp = safe_read32s(addr + 16).unwrap(); + *fpu_dp_selector = safe_read16(addr + 20).unwrap(); + + set_mxcsr(new_mxcsr); + + for i in 0..8 { + let reg_index = *fpu_stack_ptr as i32 + i & 7; + *fpu_st.offset(reg_index as isize) = fpu_load_m80(addr + 32 + (i << 4)).unwrap(); + } + + for i in 0..8 { + *reg_xmm.offset(i as isize) = safe_read128s(addr + 160 + (i << 4)).unwrap(); + } +} + +pub unsafe fn xchg8(data: i32, r8: i32) -> i32 { + let tmp = read_reg8(r8); + write_reg8(r8, data); + return tmp; +} +pub unsafe fn xchg16(data: i32, r16: i32) -> i32 { + let tmp = read_reg16(r16); + write_reg16(r16, data); + return tmp; +} +pub unsafe fn xchg16r(r16: i32) { + let tmp = read_reg16(AX); + write_reg16(AX, read_reg16(r16)); + write_reg16(r16, tmp); +} +pub unsafe fn xchg32(data: i32, r32: i32) -> i32 { + let tmp = read_reg32(r32); + write_reg32(r32, data); + return tmp; +} +pub unsafe fn xchg32r(r32: i32) { + let tmp = read_reg32(EAX); + write_reg32(EAX, read_reg32(r32)); + write_reg32(r32, tmp); +} + +pub unsafe fn bswap(r: i32) { write_reg32(r, read_reg32(r).swap_bytes()) } + +pub unsafe fn lar(selector: i32, original: i32) -> i32 { + if false { + dbg_log!("lar sel={:x}", selector); + } + + const LAR_INVALID_TYPE: u32 = + 1 << 0 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 0xA | 1 << 0xD | 1 << 0xE | 1 << 0xF; + + let sel = SegmentSelector::of_u16(selector as u16); + match lookup_segment_selector(sel) { + Err(()) => { + // pagefault + return original; + }, + Ok(Err(_)) => { + *flags_changed &= !FLAG_ZERO; + *flags &= !FLAG_ZERO; + dbg_log!("lar: invalid selector={:x}: null or invalid", selector); + return original; + }, + Ok(Ok((desc, _))) => { + *flags_changed &= !FLAG_ZERO; + let dpl_bad = desc.dpl() < *cpl || desc.dpl() < sel.rpl(); + + if if desc.is_system() { + (LAR_INVALID_TYPE >> desc.system_type() & 1 == 1) || dpl_bad + } + else { + !desc.is_conforming_executable() && dpl_bad + } { + dbg_log!( + "lar: invalid selector={:x} is_null={} is_system={}", + selector, + false, + desc.is_system() + ); + *flags &= !FLAG_ZERO; + return original; + } + else { + *flags |= FLAG_ZERO; + return (desc.raw >> 32) as i32 & 0x00FFFF00; + } + }, + } +} + +pub unsafe fn lsl(selector: i32, original: i32) -> i32 { + if false { + dbg_log!("lsl sel={:x}", selector); + } + + const LSL_INVALID_TYPE: i32 = 1 << 0 + | 1 << 4 + | 1 << 5 + | 1 << 6 + | 1 << 7 + | 1 << 8 + | 1 << 0xA + | 1 << 0xC + | 1 << 0xD + | 1 << 0xE + | 1 << 0xF; + + let sel = SegmentSelector::of_u16(selector as u16); + match lookup_segment_selector(sel) { + Err(()) => { + // pagefault + return original; + }, + Ok(Err(_)) => { + *flags_changed &= !FLAG_ZERO; + *flags &= !FLAG_ZERO; + dbg_log!("lsl: invalid selector={:x}: null or invalid", selector); + return original; + }, + Ok(Ok((desc, _))) => { + *flags_changed &= !FLAG_ZERO; + let dpl_bad = desc.dpl() < *cpl || desc.dpl() < sel.rpl(); + + if if desc.is_system() { + (LSL_INVALID_TYPE >> desc.system_type() & 1 == 1) || dpl_bad + } + else { + !desc.is_conforming_executable() && dpl_bad + } { + dbg_log!( + "lsl: invalid selector={:x} is_null={} is_system={}", + selector, + false, + desc.is_system(), + ); + *flags &= !FLAG_ZERO; + return original; + } + else { + *flags |= FLAG_ZERO; + return desc.effective_limit() as i32; + } + }, + } +} + +pub unsafe fn verr(selector: i32) { + *flags_changed &= !FLAG_ZERO; + let sel = SegmentSelector::of_u16(selector as u16); + match return_on_pagefault!(lookup_segment_selector(sel)) { + Err(_) => { + *flags &= !FLAG_ZERO; + dbg_log!("verr -> invalid. selector={:x}", selector); + }, + Ok((desc, _)) => { + if desc.is_system() + || !desc.is_readable() + || (!desc.is_conforming_executable() + && (desc.dpl() < *cpl || desc.dpl() < sel.rpl())) + { + dbg_log!("verr -> invalid. selector={:x}", selector); + *flags &= !FLAG_ZERO; + } + else { + dbg_log!("verr -> valid. selector={:x}", selector); + *flags |= FLAG_ZERO; + } + }, + } +} + +pub unsafe fn verw(selector: i32) { + *flags_changed &= !FLAG_ZERO; + let sel = SegmentSelector::of_u16(selector as u16); + match return_on_pagefault!(lookup_segment_selector(sel)) { + Err(_) => { + *flags &= !FLAG_ZERO; + dbg_log!("verw -> invalid. selector={:x}", selector); + }, + Ok((desc, _)) => { + if desc.is_system() + || !desc.is_writable() + || desc.dpl() < *cpl + || desc.dpl() < sel.rpl() + { + dbg_log!( + "verw invalid selector={:x} is_system={} is_writable={}", + selector, + desc.is_system(), + desc.is_writable(), + ); + *flags &= !FLAG_ZERO; + } + else { + *flags |= FLAG_ZERO; + } + }, + } +} diff --git a/src/rust/cpu/mod.rs b/src/rust/cpu/mod.rs new file mode 100644 index 0000000..346eed7 --- /dev/null +++ b/src/rust/cpu/mod.rs @@ -0,0 +1,13 @@ +pub mod arith; +pub mod call_indirect; +pub mod cpu; +pub mod fpu; +pub mod global_pointers; +pub mod instructions; +pub mod instructions_0f; +pub mod memory; +pub mod misc_instr; +pub mod modrm; +pub mod sse_instr; +pub mod string; +pub mod vga; diff --git a/src/rust/cpu/modrm.rs b/src/rust/cpu/modrm.rs new file mode 100644 index 0000000..f8add01 --- /dev/null +++ b/src/rust/cpu/modrm.rs @@ -0,0 +1,202 @@ +use cpu::cpu::*; +use paging::OrPageFault; + +pub unsafe fn resolve_modrm16(modrm_byte: i32) -> OrPageFault { + Ok(match modrm_byte { + 0 | 8 | 16 | 24 | 32 | 40 | 48 | 56 => { + get_seg_prefix_ds(read_reg16(BX) + read_reg16(SI) & 0xFFFF)? + }, + 64 | 72 | 80 | 88 | 96 | 104 | 112 | 120 => { + get_seg_prefix_ds(read_reg16(BX) + read_reg16(SI) + read_imm8s()? & 0xFFFF)? + }, + 128 | 136 | 144 | 152 | 160 | 168 | 176 | 184 => { + get_seg_prefix_ds(read_reg16(BX) + read_reg16(SI) + read_imm16()? & 0xFFFF)? + }, + 1 | 9 | 17 | 25 | 33 | 41 | 49 | 57 => { + get_seg_prefix_ds(read_reg16(BX) + read_reg16(DI) & 0xFFFF)? + }, + 65 | 73 | 81 | 89 | 97 | 105 | 113 | 121 => { + get_seg_prefix_ds(read_reg16(BX) + read_reg16(DI) + read_imm8s()? & 0xFFFF)? + }, + 129 | 137 | 145 | 153 | 161 | 169 | 177 | 185 => { + get_seg_prefix_ds(read_reg16(BX) + read_reg16(DI) + read_imm16()? & 0xFFFF)? + }, + 2 | 10 | 18 | 26 | 34 | 42 | 50 | 58 => { + get_seg_prefix_ss(read_reg16(BP) + read_reg16(SI) & 0xFFFF)? + }, + 66 | 74 | 82 | 90 | 98 | 106 | 114 | 122 => { + get_seg_prefix_ss(read_reg16(BP) + read_reg16(SI) + read_imm8s()? & 0xFFFF)? + }, + 130 | 138 | 146 | 154 | 162 | 170 | 178 | 186 => { + get_seg_prefix_ss(read_reg16(BP) + read_reg16(SI) + read_imm16()? & 0xFFFF)? + }, + 3 | 11 | 19 | 27 | 35 | 43 | 51 | 59 => { + get_seg_prefix_ss(read_reg16(BP) + read_reg16(DI) & 0xFFFF)? + }, + 67 | 75 | 83 | 91 | 99 | 107 | 115 | 123 => { + get_seg_prefix_ss(read_reg16(BP) + read_reg16(DI) + read_imm8s()? & 0xFFFF)? + }, + 131 | 139 | 147 | 155 | 163 | 171 | 179 | 187 => { + get_seg_prefix_ss(read_reg16(BP) + read_reg16(DI) + read_imm16()? & 0xFFFF)? + }, + 4 | 12 | 20 | 28 | 36 | 44 | 52 | 60 => get_seg_prefix_ds(read_reg16(SI) & 0xFFFF)?, + 68 | 76 | 84 | 92 | 100 | 108 | 116 | 124 => { + get_seg_prefix_ds(read_reg16(SI) + read_imm8s()? & 0xFFFF)? + }, + 132 | 140 | 148 | 156 | 164 | 172 | 180 | 188 => { + get_seg_prefix_ds(read_reg16(SI) + read_imm16()? & 0xFFFF)? + }, + 5 | 13 | 21 | 29 | 37 | 45 | 53 | 61 => get_seg_prefix_ds(read_reg16(DI) & 0xFFFF)?, + 69 | 77 | 85 | 93 | 101 | 109 | 117 | 125 => { + get_seg_prefix_ds(read_reg16(DI) + read_imm8s()? & 0xFFFF)? + }, + 133 | 141 | 149 | 157 | 165 | 173 | 181 | 189 => { + get_seg_prefix_ds(read_reg16(DI) + read_imm16()? & 0xFFFF)? + }, + 6 | 14 | 22 | 30 | 38 | 46 | 54 | 62 => get_seg_prefix_ds(read_imm16()?)?, + 70 | 78 | 86 | 94 | 102 | 110 | 118 | 126 => { + get_seg_prefix_ss(read_reg16(BP) + read_imm8s()? & 0xFFFF)? + }, + 134 | 142 | 150 | 158 | 166 | 174 | 182 | 190 => { + get_seg_prefix_ss(read_reg16(BP) + read_imm16()? & 0xFFFF)? + }, + 7 | 15 | 23 | 31 | 39 | 47 | 55 | 63 => get_seg_prefix_ds(read_reg16(BX) & 0xFFFF)?, + 71 | 79 | 87 | 95 | 103 | 111 | 119 | 127 => { + get_seg_prefix_ds(read_reg16(BX) + read_imm8s()? & 0xFFFF)? + }, + 135 | 143 | 151 | 159 | 167 | 175 | 183 | 191 => { + get_seg_prefix_ds(read_reg16(BX) + read_imm16()? & 0xFFFF)? + }, + _ => { + dbg_assert!(false); + 0 + }, + }) +} + +pub unsafe fn resolve_modrm32_(modrm_byte: i32) -> OrPageFault { + let r = (modrm_byte & 7) as u8; + dbg_assert!(modrm_byte < 192); + Ok(if r as i32 == 4 { + if modrm_byte < 64 { + resolve_sib(false)? + } + else { + resolve_sib(true)? + if modrm_byte < 128 { read_imm8s()? } else { read_imm32s()? } + } + } + else if r as i32 == 5 { + if modrm_byte < 64 { + get_seg_prefix_ds(read_imm32s()?)? + } + else { + get_seg_prefix_ss( + read_reg32(EBP) + if modrm_byte < 128 { read_imm8s()? } else { read_imm32s()? }, + )? + } + } + else if modrm_byte < 64 { + get_seg_prefix_ds(read_reg32(r as i32))? + } + else { + get_seg_prefix_ds( + read_reg32(r as i32) + if modrm_byte < 128 { read_imm8s()? } else { read_imm32s()? }, + )? + }) +} +unsafe fn resolve_sib(with_imm: bool) -> OrPageFault { + let s; + let sib_byte = read_imm8()? as u8; + let r = (sib_byte as i32 & 7) as u8; + let m = (sib_byte as i32 >> 3 & 7) as u8; + let base; + let seg; + if r as i32 == 4 { + base = read_reg32(ESP); + seg = SS + } + else if r as i32 == 5 { + if with_imm { + base = read_reg32(EBP); + seg = SS + } + else { + base = read_imm32s()?; + seg = DS + } + } + else { + base = read_reg32(r as i32); + seg = DS + } + let offset; + if m as i32 == 4 { + offset = 0 + } + else { + s = (sib_byte as i32 >> 6 & 3) as u8; + offset = read_reg32(m as i32) << s as i32 + } + Ok(get_seg_prefix(seg)? + base + offset) +} + +pub unsafe fn resolve_modrm32(modrm_byte: i32) -> OrPageFault { + Ok(match modrm_byte { + 0 | 8 | 16 | 24 | 32 | 40 | 48 | 56 => get_seg_prefix_ds(read_reg32(EAX))?, + 64 | 72 | 80 | 88 | 96 | 104 | 112 | 120 => { + get_seg_prefix_ds(read_reg32(EAX) + read_imm8s()?)? + }, + 128 | 136 | 144 | 152 | 160 | 168 | 176 | 184 => { + get_seg_prefix_ds(read_reg32(EAX) + read_imm32s()?)? + }, + 1 | 9 | 17 | 25 | 33 | 41 | 49 | 57 => get_seg_prefix_ds(read_reg32(ECX))?, + 65 | 73 | 81 | 89 | 97 | 105 | 113 | 121 => { + get_seg_prefix_ds(read_reg32(ECX) + read_imm8s()?)? + }, + 129 | 137 | 145 | 153 | 161 | 169 | 177 | 185 => { + get_seg_prefix_ds(read_reg32(ECX) + read_imm32s()?)? + }, + 2 | 10 | 18 | 26 | 34 | 42 | 50 | 58 => get_seg_prefix_ds(read_reg32(EDX))?, + 66 | 74 | 82 | 90 | 98 | 106 | 114 | 122 => { + get_seg_prefix_ds(read_reg32(EDX) + read_imm8s()?)? + }, + 130 | 138 | 146 | 154 | 162 | 170 | 178 | 186 => { + get_seg_prefix_ds(read_reg32(EDX) + read_imm32s()?)? + }, + 3 | 11 | 19 | 27 | 35 | 43 | 51 | 59 => get_seg_prefix_ds(read_reg32(EBX))?, + 67 | 75 | 83 | 91 | 99 | 107 | 115 | 123 => { + get_seg_prefix_ds(read_reg32(EBX) + read_imm8s()?)? + }, + 131 | 139 | 147 | 155 | 163 | 171 | 179 | 187 => { + get_seg_prefix_ds(read_reg32(EBX) + read_imm32s()?)? + }, + 4 | 12 | 20 | 28 | 36 | 44 | 52 | 60 => resolve_sib(false)?, + 68 | 76 | 84 | 92 | 100 | 108 | 116 | 124 => resolve_sib(true)? + read_imm8s()?, + 132 | 140 | 148 | 156 | 164 | 172 | 180 | 188 => resolve_sib(true)? + read_imm32s()?, + 5 | 13 | 21 | 29 | 37 | 45 | 53 | 61 => get_seg_prefix_ds(read_imm32s()?)?, + 69 | 77 | 85 | 93 | 101 | 109 | 117 | 125 => { + get_seg_prefix_ss(read_reg32(EBP) + read_imm8s()?)? + }, + 133 | 141 | 149 | 157 | 165 | 173 | 181 | 189 => { + get_seg_prefix_ss(read_reg32(EBP) + read_imm32s()?)? + }, + 6 | 14 | 22 | 30 | 38 | 46 | 54 | 62 => get_seg_prefix_ds(read_reg32(ESI))?, + 70 | 78 | 86 | 94 | 102 | 110 | 118 | 126 => { + get_seg_prefix_ds(read_reg32(ESI) + read_imm8s()?)? + }, + 134 | 142 | 150 | 158 | 166 | 174 | 182 | 190 => { + get_seg_prefix_ds(read_reg32(ESI) + read_imm32s()?)? + }, + 7 | 15 | 23 | 31 | 39 | 47 | 55 | 63 => get_seg_prefix_ds(read_reg32(EDI))?, + 71 | 79 | 87 | 95 | 103 | 111 | 119 | 127 => { + get_seg_prefix_ds(read_reg32(EDI) + read_imm8s()?)? + }, + 135 | 143 | 151 | 159 | 167 | 175 | 183 | 191 => { + get_seg_prefix_ds(read_reg32(EDI) + read_imm32s()?)? + }, + _ => { + dbg_assert!(false); + 0 + }, + }) +} diff --git a/src/rust/cpu/sse_instr.rs b/src/rust/cpu/sse_instr.rs new file mode 100644 index 0000000..ef0144d --- /dev/null +++ b/src/rust/cpu/sse_instr.rs @@ -0,0 +1,361 @@ +use cpu::cpu::*; +use cpu::global_pointers::mxcsr; + +pub unsafe fn mov_r_m64(addr: i32, r: i32) { + // mov* m64, mm + let data = read_mmx64s(r); + return_on_pagefault!(safe_write64(addr, data)); + transition_fpu_to_mmx(); +} +pub unsafe fn movl_r128_m64(addr: i32, r: i32) { + // mov* m64, xmm + let data = read_xmm64s(r); + return_on_pagefault!(safe_write64(addr, data)); +} +pub unsafe fn mov_r_r128(r1: i32, r2: i32) { + // mov* xmm, xmm + let data = read_xmm128s(r2); + write_xmm_reg128(r1, data); +} +pub unsafe fn mov_r_m128(addr: i32, r: i32) { + // mov* m128, xmm + let data = read_xmm128s(r); + return_on_pagefault!(safe_write128(addr, data)); +} +pub unsafe fn mov_rm_r128(source: reg128, r: i32) { + // mov* xmm, xmm/m128 + write_xmm_reg128(r, source); +} +pub unsafe fn movh_r128_m64(addr: i32, r: i32) { + // movhp* m64, xmm + let data = read_xmm128s(r); + return_on_pagefault!(safe_write64(addr, data.u64[1])); +} + +pub unsafe fn pand_r128(source: reg128, r: i32) { + // pand xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + result.u64[0] = source.u64[0] & destination.u64[0]; + result.u64[1] = source.u64[1] & destination.u64[1]; + write_xmm_reg128(r, result); +} +pub unsafe fn pandn_r128(source: reg128, r: i32) { + // pandn xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + result.u64[0] = source.u64[0] & !destination.u64[0]; + result.u64[1] = source.u64[1] & !destination.u64[1]; + write_xmm_reg128(r, result); +} +pub unsafe fn pxor_r128(source: reg128, r: i32) { + // pxor xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + result.u64[0] = source.u64[0] ^ destination.u64[0]; + result.u64[1] = source.u64[1] ^ destination.u64[1]; + write_xmm_reg128(r, result); +} +pub unsafe fn por_r128(source: reg128, r: i32) { + // por xmm, xmm/m128 + // XXX: Aligned access or #gp + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + result.u64[0] = source.u64[0] | destination.u64[0]; + result.u64[1] = source.u64[1] | destination.u64[1]; + write_xmm_reg128(r, result); +} + +pub unsafe fn psrlw_r64(r: i32, shift: u64) { + // psrlw mm, {shift} + let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r)); + let shift = if shift > 15 { 16 } else { shift }; + let mut result = [0; 4]; + for i in 0..4 { + result[i] = ((destination[i] as u32) >> shift) as u16 + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn psraw_r64(r: i32, shift: u64) { + // psraw mm, {shift} + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let shift = if shift > 15 { 16 } else { shift }; + let mut result = [0; 4]; + for i in 0..4 { + result[i] = (destination[i] as i32 >> shift) as i16 + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn psllw_r64(r: i32, shift: u64) { + // psllw mm, {shift} + let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r)); + let mut result = [0; 4]; + if shift <= 15 { + for i in 0..4 { + result[i] = destination[i] << shift + } + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn psrld_r64(r: i32, shift: u64) { + // psrld mm, {shift} + let destination: [u32; 2] = std::mem::transmute(read_mmx64s(r)); + let mut result = [0; 2]; + if shift <= 31 { + for i in 0..2 { + result[i] = destination[i] >> shift; + } + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn psrad_r64(r: i32, shift: u64) { + // psrad mm, {shift} + let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r)); + let shift = if shift > 31 { 31 } else { shift }; + let mut result = [0; 2]; + for i in 0..2 { + result[i] = destination[i] >> shift; + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn pslld_r64(r: i32, shift: u64) { + // pslld mm, {shift} + let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r)); + let mut result = [0; 2]; + if shift <= 31 { + for i in 0..2 { + result[i] = destination[i] << shift; + } + } + write_mmx_reg64(r, std::mem::transmute(result)); + transition_fpu_to_mmx(); +} +pub unsafe fn psrlq_r64(r: i32, shift: u64) { + // psrlq mm, {shift} + let destination = read_mmx64s(r); + let mut result = 0; + if shift <= 63 { + result = destination >> shift + } + write_mmx_reg64(r, result); + transition_fpu_to_mmx(); +} +pub unsafe fn psllq_r64(r: i32, shift: u64) { + // psllq mm, {shift} + let destination = read_mmx64s(r); + let mut result = 0; + if shift <= 63 { + result = destination << shift + } + write_mmx_reg64(r, result); + transition_fpu_to_mmx(); +} +pub unsafe fn psrlw_r128(r: i32, shift: u64) { + // psrlw xmm, {shift} + let destination = read_xmm128s(r); + let mut dword0: i32 = 0; + let mut dword1: i32 = 0; + let mut dword2: i32 = 0; + let mut dword3: i32 = 0; + if shift <= 15 { + dword0 = destination.u16[0] as i32 >> shift | destination.u16[1] as i32 >> shift << 16; + dword1 = destination.u16[2] as i32 >> shift | destination.u16[3] as i32 >> shift << 16; + dword2 = destination.u16[4] as i32 >> shift | destination.u16[5] as i32 >> shift << 16; + dword3 = destination.u16[6] as i32 >> shift | destination.u16[7] as i32 >> shift << 16 + } + write_xmm128(r, dword0, dword1, dword2, dword3); +} +pub unsafe fn psraw_r128(r: i32, shift: u64) { + // psraw xmm, {shift} + let destination = read_xmm128s(r); + let shift_clamped = (if shift > 15 { 16 } else { shift as u32 }) as i32; + let dword0 = destination.i16[0] as i32 >> shift_clamped & 0xFFFF + | destination.i16[1] as i32 >> shift_clamped << 16; + let dword1 = destination.i16[2] as i32 >> shift_clamped & 0xFFFF + | destination.i16[3] as i32 >> shift_clamped << 16; + let dword2 = destination.i16[4] as i32 >> shift_clamped & 0xFFFF + | destination.i16[5] as i32 >> shift_clamped << 16; + let dword3 = destination.i16[6] as i32 >> shift_clamped & 0xFFFF + | destination.i16[7] as i32 >> shift_clamped << 16; + write_xmm128(r, dword0, dword1, dword2, dword3); +} +pub unsafe fn psllw_r128(r: i32, shift: u64) { + // psllw xmm, {shift} + let destination = read_xmm128s(r); + let mut dword0: i32 = 0; + let mut dword1: i32 = 0; + let mut dword2: i32 = 0; + let mut dword3: i32 = 0; + if shift <= 15 { + dword0 = (destination.u16[0] as i32) << shift & 0xFFFF + | (destination.u16[1] as i32) << shift << 16; + dword1 = (destination.u16[2] as i32) << shift & 0xFFFF + | (destination.u16[3] as i32) << shift << 16; + dword2 = (destination.u16[4] as i32) << shift & 0xFFFF + | (destination.u16[5] as i32) << shift << 16; + dword3 = (destination.u16[6] as i32) << shift & 0xFFFF + | (destination.u16[7] as i32) << shift << 16 + } + write_xmm128(r, dword0, dword1, dword2, dword3); +} +pub unsafe fn psrld_r128(r: i32, shift: u64) { + // psrld xmm, {shift} + let destination = read_xmm128s(r); + let mut dword0: i32 = 0; + let mut dword1: i32 = 0; + let mut dword2: i32 = 0; + let mut dword3: i32 = 0; + if shift <= 31 { + dword0 = (destination.u32[0] >> shift) as i32; + dword1 = (destination.u32[1] >> shift) as i32; + dword2 = (destination.u32[2] >> shift) as i32; + dword3 = (destination.u32[3] >> shift) as i32 + } + write_xmm128(r, dword0, dword1, dword2, dword3); +} +pub unsafe fn psrad_r128(r: i32, shift: u64) { + // psrad xmm, {shift} + let destination = read_xmm128s(r); + let shift_clamped = (if shift > 31 { 31 } else { shift }) as i32; + let dword0 = destination.i32[0] >> shift_clamped; + let dword1 = destination.i32[1] >> shift_clamped; + let dword2 = destination.i32[2] >> shift_clamped; + let dword3 = destination.i32[3] >> shift_clamped; + write_xmm128(r, dword0, dword1, dword2, dword3); +} +pub unsafe fn pslld_r128(r: i32, shift: u64) { + // pslld xmm, {shift} + let destination = read_xmm128s(r); + let mut dword0: i32 = 0; + let mut dword1: i32 = 0; + let mut dword2: i32 = 0; + let mut dword3: i32 = 0; + if shift <= 31 { + dword0 = destination.i32[0] << shift; + dword1 = destination.i32[1] << shift; + dword2 = destination.i32[2] << shift; + dword3 = destination.i32[3] << shift + } + write_xmm128(r, dword0, dword1, dword2, dword3); +} +pub unsafe fn psrlq_r128(r: i32, shift: u64) { + // psrlq xmm, {shift} + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + if shift <= 63 { + result.u64[0] = destination.u64[0] >> shift; + result.u64[1] = destination.u64[1] >> shift + } + write_xmm_reg128(r, result); +} +pub unsafe fn psllq_r128(r: i32, shift: u64) { + // psllq xmm, {shift} + let destination = read_xmm128s(r); + let mut result = reg128 { i8: [0; 16] }; + if shift <= 63 { + result.u64[0] = destination.u64[0] << shift; + result.u64[1] = destination.u64[1] << shift + } + write_xmm_reg128(r, result); +} + +pub unsafe fn sse_comparison(op: i32, x: f64, y: f64) -> bool { + // TODO: Signaling + match op & 7 { + 0 => return x == y, + 1 => return x < y, + 2 => return x <= y, + 3 => return x.is_nan() || y.is_nan(), + 4 => return x != y || x.is_nan() || y.is_nan(), + 5 => return x >= y || x.is_nan() || y.is_nan(), + 6 => return x > y || x.is_nan() || y.is_nan(), + 7 => return !x.is_nan() && !y.is_nan(), + _ => { + dbg_assert!(false); + return false; + }, + }; +} +pub unsafe fn sse_min(x: f64, y: f64) -> f64 { + // if both x and y are 0 or x is nan, y is returned + return if x < y { x } else { y }; +} +pub unsafe fn sse_max(x: f64, y: f64) -> f64 { + // if both x and y are 0 or x is nan, y is returned + return if x > y { x } else { y }; +} + +#[no_mangle] +pub unsafe fn sse_convert_with_truncation_f32_to_i32(x: f32) -> i32 { + let x = x.trunc(); + if x >= -2147483648.0 && x < 2147483648.0 { + return x as i64 as i32; + } + else { + // TODO: Signal + return -0x80000000; + }; +} +#[no_mangle] +pub unsafe fn sse_convert_f32_to_i32(x: f32) -> i32 { + let x = sse_integer_round(x as f64); + if x >= -2147483648.0 && x < 2147483648.0 { + return x as i64 as i32; + } + else { + // TODO: Signal + return -0x80000000; + }; +} + +#[no_mangle] +pub unsafe fn sse_convert_with_truncation_f64_to_i32(x: f64) -> i32 { + let x = x.trunc(); + if x >= -2147483648.0 && x < 2147483648.0 { + return x as i64 as i32; + } + else { + // TODO: Signal + return -0x80000000; + }; +} +#[no_mangle] +pub unsafe fn sse_convert_f64_to_i32(x: f64) -> i32 { + let x = sse_integer_round(x); + if x >= -2147483648.0 && x < 2147483648.0 { + return x as i64 as i32; + } + else { + // TODO: Signal + return -0x80000000; + }; +} + +pub unsafe fn sse_integer_round(f: f64) -> f64 { + // see fpu_integer_round + let rc = *mxcsr >> MXCSR_RC_SHIFT & 3; + if rc == 0 { + // Round to nearest, or even if equidistant + let mut rounded = f.round(); + let diff = rounded - f; + if diff == 0.5 || diff == -0.5 { + rounded = 2.0 * (f * 0.5).round() + } + return rounded; + } + else if rc == 1 || rc == 3 && f > 0.0 { + // rc=3 is truncate -> floor for positive numbers + return f.floor(); + } + else { + return f.ceil(); + }; +} diff --git a/src/rust/cpu/string.rs b/src/rust/cpu/string.rs new file mode 100644 index 0000000..27d9ce0 --- /dev/null +++ b/src/rust/cpu/string.rs @@ -0,0 +1,696 @@ +// string operations +// +// cmp si di +// movs 0 1 1/w A4 +// cmps 1 1 1/r A6 +// stos 0 0 1/w AA +// lods 0 1 0 AC +// scas 1 0 1/r AE +// ins 0 0 1/w +// outs 0 1 0 + +use cpu::arith::{cmp8, cmp16, cmp32}; +use cpu::cpu::{ + get_seg, io_port_read8, io_port_read16, io_port_read32, io_port_write8, io_port_write16, + io_port_write32, read_reg16, read_reg32, safe_read8, safe_read16, safe_read32s, safe_write8, + safe_write16, safe_write32, set_reg_asize, test_privileges_for_io, translate_address_read, + translate_address_write_and_can_skip_dirty, writable_or_pagefault, write_reg8, write_reg16, + write_reg32, AL, AX, DX, EAX, ECX, EDI, ES, ESI, FLAG_DIRECTION, +}; +use cpu::global_pointers::{flags, instruction_pointer, previous_ip}; +use cpu::memory::{ + in_mapped_range, in_svga_lfb, memcpy_into_svga_lfb, memcpy_no_mmap_or_dirty_check, + memset_no_mmap_or_dirty_check, read8_no_mmap_check, read16_no_mmap_check, read32_no_mmap_check, + write8_no_mmap_or_dirty_check, write16_no_mmap_or_dirty_check, write32_no_mmap_or_dirty_check, +}; +use page::Page; + +fn count_until_end_of_page(direction: i32, size: i32, addr: u32) -> u32 { + (if direction == 1 { + (0x1000 - (addr & 0xFFF)) / size as u32 + } + else { + (addr & 0xFFF) / size as u32 + 1 + }) as u32 +} + +#[derive(Copy, Clone, PartialEq)] +enum Instruction { + Movs, + Lods, + Stos, + Scas, + Cmps, + Ins, + Outs, +} +#[derive(PartialEq)] +enum Size { + B, + W, + D, +} +#[derive(Copy, Clone)] +enum Rep { + None, + Z, + NZ, +} + +// We implement all string instructions here and rely on the inliner on doing its job of optimising +// away anything known at compile time (check with `wasm-dis build/v86.wasm`) +#[inline(always)] +unsafe fn string_instruction( + is_asize_32: bool, + ds: i32, + instruction: Instruction, + size: Size, + rep: Rep, +) { + let asize_mask = if is_asize_32 { -1 } else { 0xFFFF }; + + let direction = if 0 != *flags & FLAG_DIRECTION { -1 } else { 1 }; + + let es = match instruction { + Instruction::Movs + | Instruction::Cmps + | Instruction::Stos + | Instruction::Scas + | Instruction::Ins => return_on_pagefault!(get_seg(ES)), + _ => 0, + }; + + let size_bytes = match size { + Size::B => 1, + Size::W => 2, + Size::D => 4, + }; + let size_mask = match size { + Size::B => 0xFF, + Size::W => 0xFFFF, + Size::D => -1, + }; + + let increment = direction * size_bytes; + + let data = match instruction { + Instruction::Stos | Instruction::Scas => read_reg32(EAX), + _ => 0, + }; + + let mut src = match instruction { + Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => { + read_reg32(ESI) & asize_mask + }, + _ => 0, + }; + let mut dst = match instruction { + Instruction::Movs + | Instruction::Cmps + | Instruction::Stos + | Instruction::Scas + | Instruction::Ins => read_reg32(EDI) & asize_mask, + _ => 0, + }; + let mut count = match rep { + Rep::Z | Rep::NZ => { + let c = (read_reg32(ECX) & asize_mask) as u32; + if c == 0 { + return; + }; + c + }, + Rep::None => 0, + }; + + let port = match instruction { + Instruction::Ins | Instruction::Outs => { + let port = read_reg16(DX); + if !test_privileges_for_io(port, size_bytes) { + return; + } + port + }, + _ => 0, + }; + + let is_aligned = (ds + src) & (size_bytes - 1) == 0 && (es + dst) & (size_bytes - 1) == 0; + + // unaligned movs is properly handled in the fast path + let mut rep_fast = (instruction == Instruction::Movs || is_aligned) + && is_asize_32 // 16-bit address wraparound + && match rep { + Rep::NZ | Rep::Z => true, + Rep::None => false, + }; + + let mut phys_dst = 0; + let mut phys_src = 0; + let mut skip_dirty_page = false; + + let mut movs_into_svga_lfb = false; + let mut movs_reenter_fast_path = false; + + let count_until_end_of_page = if rep_fast { + match instruction { + Instruction::Movs => { + let (addr, skip) = + return_on_pagefault!(translate_address_write_and_can_skip_dirty(es + dst)); + movs_into_svga_lfb = in_svga_lfb(addr); + rep_fast = rep_fast && (!in_mapped_range(addr) || movs_into_svga_lfb); + phys_dst = addr; + skip_dirty_page = skip; + }, + Instruction::Stos | Instruction::Ins => { + let (addr, skip) = + return_on_pagefault!(translate_address_write_and_can_skip_dirty(es + dst)); + rep_fast = rep_fast && !in_mapped_range(addr); + phys_dst = addr; + skip_dirty_page = skip; + }, + Instruction::Cmps | Instruction::Scas => { + let addr = return_on_pagefault!(translate_address_read(es + dst)); + rep_fast = rep_fast && !in_mapped_range(addr); + phys_dst = addr; + skip_dirty_page = true; + }, + _ => {}, + }; + + match instruction { + Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => { + let addr = return_on_pagefault!(translate_address_read(ds + src)); + rep_fast = rep_fast && !in_mapped_range(addr); + phys_src = addr; + }, + _ => {}, + }; + + let count_until_end_of_page = u32::min( + count, + match instruction { + Instruction::Movs | Instruction::Cmps => u32::min( + count_until_end_of_page(direction, size_bytes, phys_src), + count_until_end_of_page(direction, size_bytes, phys_dst), + ), + Instruction::Stos | Instruction::Ins | Instruction::Scas => { + count_until_end_of_page(direction, size_bytes, phys_dst) + }, + Instruction::Lods | Instruction::Outs => { + count_until_end_of_page(direction, size_bytes, phys_src) + }, + }, + ); + + match instruction { + Instruction::Movs => { + let c = count_until_end_of_page * size_bytes as u32; + + let overlap_interferes = if phys_src < phys_dst { + // backward moves may overlap at the front of the destination string + phys_dst - phys_src < c && direction == 1 + } + else if phys_src > phys_dst { + // forward moves may overlap at the front of the source string + phys_src - phys_dst < c && direction == -1 + } + else { + false + }; + rep_fast = rep_fast && !overlap_interferes; + + // In case the following page-boundary check fails, re-enter instruction after + // one iteration of the slow path + movs_reenter_fast_path = rep_fast; + rep_fast = rep_fast + && (phys_src & 0xFFF <= 0x1000 - size_bytes as u32) + && (phys_dst & 0xFFF <= 0x1000 - size_bytes as u32); + }, + _ => {}, + } + + count_until_end_of_page + } + else { + 0 // not used + }; + + if rep_fast { + dbg_assert!(count_until_end_of_page > 0); + + if !skip_dirty_page { + ::jit::jit_dirty_page(::jit::get_jit_state(), Page::page_of(phys_dst)); + } + + let mut rep_cmp_finished = false; + + let mut i = 0; + while i < count_until_end_of_page { + i += 1; + + let src_val = match instruction { + Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => { + match size { + Size::B => read8_no_mmap_check(phys_src), + Size::W => read16_no_mmap_check(phys_src), + Size::D => read32_no_mmap_check(phys_src), + } + }, + Instruction::Scas | Instruction::Stos => data & size_mask, + Instruction::Ins => match size { + Size::B => io_port_read8(port), + Size::W => io_port_read16(port), + Size::D => io_port_read32(port), + }, + }; + + let mut dst_val = 0; + + match instruction { + Instruction::Cmps | Instruction::Scas => match size { + Size::B => dst_val = read8_no_mmap_check(phys_dst), + Size::W => dst_val = read16_no_mmap_check(phys_dst), + Size::D => dst_val = read32_no_mmap_check(phys_dst), + }, + Instruction::Outs => match size { + Size::B => io_port_write8(port, src_val), + Size::W => io_port_write16(port, src_val), + Size::D => io_port_write32(port, src_val), + }, + Instruction::Lods => match size { + Size::B => write_reg8(AL, src_val), + Size::W => write_reg16(AX, src_val), + Size::D => write_reg32(EAX, src_val), + }, + Instruction::Ins => match size { + Size::B => write8_no_mmap_or_dirty_check(phys_dst, src_val), + Size::W => write16_no_mmap_or_dirty_check(phys_dst, src_val), + Size::D => write32_no_mmap_or_dirty_check(phys_dst, src_val), + }, + Instruction::Movs => { + if direction == -1 { + phys_src -= (count_until_end_of_page - 1) * size_bytes as u32; + phys_dst -= (count_until_end_of_page - 1) * size_bytes as u32; + } + if movs_into_svga_lfb { + ::cpu::vga::mark_dirty(phys_dst); + memcpy_into_svga_lfb( + phys_src, + phys_dst, + count_until_end_of_page * size_bytes as u32, + ); + } + else { + memcpy_no_mmap_or_dirty_check( + phys_src, + phys_dst, + count_until_end_of_page * size_bytes as u32, + ); + } + i = count_until_end_of_page; + break; + }, + Instruction::Stos => match size { + Size::B => { + if direction == -1 { + phys_dst -= count_until_end_of_page - 1 + } + memset_no_mmap_or_dirty_check( + phys_dst, + src_val as u8, + count_until_end_of_page, + ); + i = count_until_end_of_page; + break; + }, + Size::W => write16_no_mmap_or_dirty_check(phys_dst, src_val), + Size::D => write32_no_mmap_or_dirty_check(phys_dst, src_val), + }, + }; + + match instruction { + Instruction::Movs + | Instruction::Cmps + | Instruction::Stos + | Instruction::Scas + | Instruction::Ins => { + phys_dst += increment as u32; + }, + _ => {}, + } + match instruction { + Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => { + phys_src += increment as u32; + }, + _ => {}, + }; + + match instruction { + Instruction::Scas | Instruction::Cmps => { + let rep_cmp = match rep { + Rep::Z => src_val == dst_val, + Rep::NZ => src_val != dst_val, + Rep::None => { + dbg_assert!(false); + true + }, + }; + if !rep_cmp || count == i { + match size { + Size::B => cmp8(src_val, dst_val), + Size::W => cmp16(src_val, dst_val), + Size::D => cmp32(src_val, dst_val), + }; + rep_cmp_finished = true; + break; + } + }, + _ => {}, + } + } + + dbg_assert!(i <= count); + count -= i; + + if !rep_cmp_finished && count != 0 { + // go back to the current instruction, since this loop just handles a single page + *instruction_pointer = *previous_ip; + } + + src += i as i32 * increment; + dst += i as i32 * increment; + } + else { + loop { + match instruction { + Instruction::Ins => { + // check fault *before* reading from port + // (technically not necessary according to Intel manuals) + break_on_pagefault!(writable_or_pagefault(es + dst, size_bytes)); + }, + _ => {}, + }; + let src_val = match instruction { + Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => { + break_on_pagefault!(match size { + Size::B => safe_read8(ds + src), + Size::W => safe_read16(ds + src), + Size::D => safe_read32s(ds + src), + }) + }, + Instruction::Scas | Instruction::Stos => data & size_mask, + Instruction::Ins => match size { + Size::B => io_port_read8(port), + Size::W => io_port_read16(port), + Size::D => io_port_read32(port), + }, + }; + + let mut dst_val = 0; + + match instruction { + Instruction::Cmps | Instruction::Scas => match size { + Size::B => dst_val = break_on_pagefault!(safe_read8(es + dst)), + Size::W => dst_val = break_on_pagefault!(safe_read16(es + dst)), + Size::D => dst_val = break_on_pagefault!(safe_read32s(es + dst)), + }, + Instruction::Outs => match size { + Size::B => io_port_write8(port, src_val), + Size::W => io_port_write16(port, src_val), + Size::D => io_port_write32(port, src_val), + }, + Instruction::Lods => match size { + Size::B => write_reg8(AL, src_val), + Size::W => write_reg16(AX, src_val), + Size::D => write_reg32(EAX, src_val), + }, + Instruction::Movs | Instruction::Stos | Instruction::Ins => match size { + Size::B => break_on_pagefault!(safe_write8(es + dst, src_val)), + Size::W => break_on_pagefault!(safe_write16(es + dst, src_val)), + Size::D => break_on_pagefault!(safe_write32(es + dst, src_val)), + }, + }; + + match instruction { + Instruction::Movs + | Instruction::Cmps + | Instruction::Stos + | Instruction::Scas + | Instruction::Ins => dst = dst + increment & asize_mask, + _ => {}, + } + match instruction { + Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => { + src = src + increment & asize_mask + }, + _ => {}, + }; + + count -= 1; + + let finished = match rep { + Rep::Z | Rep::NZ => match (rep, instruction) { + (Rep::Z, Instruction::Cmps) => src_val != dst_val || count == 0, + (Rep::Z, Instruction::Scas) => src_val != dst_val || count == 0, + (Rep::NZ, Instruction::Cmps) => src_val == dst_val || count == 0, + (Rep::NZ, Instruction::Scas) => src_val == dst_val || count == 0, + (Rep::NZ | Rep::Z, Instruction::Movs) => { + if count == 0 { + true + } + else if movs_reenter_fast_path { + *instruction_pointer = *previous_ip; + true + } + else { + false + } + }, + _ => count == 0, + }, + Rep::None => true, + }; + + if finished { + match instruction { + Instruction::Scas | Instruction::Cmps => match size { + Size::B => cmp8(src_val, dst_val), + Size::W => cmp16(src_val, dst_val), + Size::D => cmp32(src_val, dst_val), + }, + _ => {}, + } + break; + } + } + } + + match instruction { + Instruction::Movs + | Instruction::Cmps + | Instruction::Stos + | Instruction::Scas + | Instruction::Ins => set_reg_asize(is_asize_32, EDI, dst), + _ => {}, + } + match instruction { + Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => { + set_reg_asize(is_asize_32, ESI, src) + }, + _ => {}, + }; + + match rep { + Rep::Z | Rep::NZ => { + set_reg_asize(is_asize_32, ECX, count as i32); + }, + Rep::None => {}, + } +} + +#[no_mangle] +pub unsafe fn movsb_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Movs, Size::B, Rep::Z) +} +#[no_mangle] +pub unsafe fn movsw_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Movs, Size::W, Rep::Z) +} +#[no_mangle] +pub unsafe fn movsd_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Movs, Size::D, Rep::Z) +} +pub unsafe fn movsb_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Movs, Size::B, Rep::None) +} +pub unsafe fn movsw_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Movs, Size::W, Rep::None) +} +pub unsafe fn movsd_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Movs, Size::D, Rep::None) +} + +#[no_mangle] +pub unsafe fn lodsb_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Lods, Size::B, Rep::Z) +} +#[no_mangle] +pub unsafe fn lodsw_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Lods, Size::W, Rep::Z) +} +#[no_mangle] +pub unsafe fn lodsd_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Lods, Size::D, Rep::Z) +} +pub unsafe fn lodsb_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Lods, Size::B, Rep::None) +} +pub unsafe fn lodsw_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Lods, Size::W, Rep::None) +} +pub unsafe fn lodsd_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Lods, Size::D, Rep::None) +} + +#[no_mangle] +pub unsafe fn stosb_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Stos, Size::B, Rep::Z) +} +#[no_mangle] +pub unsafe fn stosw_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Stos, Size::W, Rep::Z) +} +#[no_mangle] +pub unsafe fn stosd_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Stos, Size::D, Rep::Z) +} +pub unsafe fn stosb_no_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Stos, Size::B, Rep::None) +} +pub unsafe fn stosw_no_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Stos, Size::W, Rep::None) +} +pub unsafe fn stosd_no_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Stos, Size::D, Rep::None) +} + +#[no_mangle] +pub unsafe fn cmpsb_repz(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Cmps, Size::B, Rep::Z) +} +#[no_mangle] +pub unsafe fn cmpsw_repz(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Cmps, Size::W, Rep::Z) +} +#[no_mangle] +pub unsafe fn cmpsd_repz(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Cmps, Size::D, Rep::Z) +} +#[no_mangle] +pub unsafe fn cmpsb_repnz(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Cmps, Size::B, Rep::NZ) +} +#[no_mangle] +pub unsafe fn cmpsw_repnz(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Cmps, Size::W, Rep::NZ) +} +#[no_mangle] +pub unsafe fn cmpsd_repnz(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Cmps, Size::D, Rep::NZ) +} +#[no_mangle] +pub unsafe fn cmpsb_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Cmps, Size::B, Rep::None) +} +#[no_mangle] +pub unsafe fn cmpsw_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Cmps, Size::W, Rep::None) +} +#[no_mangle] +pub unsafe fn cmpsd_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Cmps, Size::D, Rep::None) +} + +#[no_mangle] +pub unsafe fn scasb_repz(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Scas, Size::B, Rep::Z) +} +#[no_mangle] +pub unsafe fn scasw_repz(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Scas, Size::W, Rep::Z) +} +#[no_mangle] +pub unsafe fn scasd_repz(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Scas, Size::D, Rep::Z) +} +#[no_mangle] +pub unsafe fn scasb_repnz(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Scas, Size::B, Rep::NZ) +} +#[no_mangle] +pub unsafe fn scasw_repnz(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Scas, Size::W, Rep::NZ) +} +#[no_mangle] +pub unsafe fn scasd_repnz(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Scas, Size::D, Rep::NZ) +} +pub unsafe fn scasb_no_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Scas, Size::B, Rep::None) +} +pub unsafe fn scasw_no_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Scas, Size::W, Rep::None) +} +pub unsafe fn scasd_no_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Scas, Size::D, Rep::None) +} + +#[no_mangle] +pub unsafe fn outsb_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Outs, Size::B, Rep::Z) +} +#[no_mangle] +pub unsafe fn outsw_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Outs, Size::W, Rep::Z) +} +#[no_mangle] +pub unsafe fn outsd_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Outs, Size::D, Rep::Z) +} +#[no_mangle] +pub unsafe fn outsb_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Outs, Size::B, Rep::None) +} +#[no_mangle] +pub unsafe fn outsw_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Outs, Size::W, Rep::None) +} +#[no_mangle] +pub unsafe fn outsd_no_rep(is_asize_32: bool, ds: i32) { + string_instruction(is_asize_32, ds, Instruction::Outs, Size::D, Rep::None) +} + +#[no_mangle] +pub unsafe fn insb_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Ins, Size::B, Rep::Z) +} +#[no_mangle] +pub unsafe fn insw_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Ins, Size::W, Rep::Z) +} +#[no_mangle] +pub unsafe fn insd_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Ins, Size::D, Rep::Z) +} +#[no_mangle] +pub unsafe fn insb_no_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Ins, Size::B, Rep::None) +} +#[no_mangle] +pub unsafe fn insw_no_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Ins, Size::W, Rep::None) +} +#[no_mangle] +pub unsafe fn insd_no_rep(is_asize_32: bool) { + string_instruction(is_asize_32, 0, Instruction::Ins, Size::D, Rep::None) +} diff --git a/src/rust/cpu/vga.rs b/src/rust/cpu/vga.rs new file mode 100644 index 0000000..31b6c05 --- /dev/null +++ b/src/rust/cpu/vga.rs @@ -0,0 +1,169 @@ +#![allow(non_upper_case_globals)] + +use cpu::global_pointers; +use cpu::memory; + +pub static mut dirty_bitmap: Vec = Vec::new(); +pub static mut dest_buffer: Vec = Vec::new(); + +#[no_mangle] +pub unsafe fn svga_allocate_dest_buffer(size: u32) -> u32 { + dest_buffer.resize(size as usize, 0); + dest_buffer.as_mut_ptr() as u32 +} + +#[no_mangle] +pub unsafe fn mark_dirty(addr: u32) { + let page = (addr - memory::VGA_LFB_ADDRESS) >> 12; + dbg_assert!(((page >> 6) as usize) < dirty_bitmap.len()); + *dirty_bitmap.get_unchecked_mut((page >> 6) as usize) |= 1 << (page & 63) +} + +#[no_mangle] +pub unsafe fn svga_mark_dirty() { + for v in dirty_bitmap.iter_mut() { + *v = u64::MAX + } +} + +fn iter_dirty_pages(f: &dyn Fn(isize)) { + let mut min_off = u32::MAX; + let mut max_off = u32::MIN; + + for (i, &word) in unsafe { &dirty_bitmap }.iter().enumerate() { + if word == 0 { + continue; + } + for j in 0..64 { + if word & 1 << j == 0 { + continue; + } + let off = ((i << 6 | j) << 12) as isize; + dbg_assert!(off < unsafe { memory::vga_memory_size as isize }); + if min_off == u32::MAX { + min_off = off as u32; + } + max_off = off as u32; + f(off); + } + } + + unsafe { + *global_pointers::svga_dirty_bitmap_min_offset = min_off; + *global_pointers::svga_dirty_bitmap_max_offset = max_off + 0xFFF; + } +} + +#[no_mangle] +pub unsafe fn svga_fill_pixel_buffer(bpp: u32, svga_dest_offset: u32) { + let debug_bounds = false; + + match bpp { + 32 => iter_dirty_pages(&|off| { + dbg_assert!(off >= 0); + let src = memory::vga_mem8.offset(off) as *const u32; + let dest_offset = off / 4 - svga_dest_offset as isize; + let dest = dest_buffer.as_mut_ptr().offset(dest_offset) as *mut u32; + let end = if dest_offset < 0 { + 0 + } + else { + isize::min(1024, dest_buffer.len() as isize - dest_offset) + }; + + dbg_assert!(src as u32 % 8 == 0); + dbg_assert!(dest as u32 % 8 == 0); + for i in 0..end { + dbg_assert!(off + i < memory::vga_memory_size as isize); + let dword = *src.offset(i); + let dword = if debug_bounds && (i == 0 || i == end - 1) { 0xFFFFFF } else { dword }; + dbg_assert!(dest_offset + i < dest_buffer.len() as isize); + *dest.offset(i) = dword << 16 | dword >> 16 & 0xFF | dword & 0xFF00 | 0xFF00_0000; + } + }), + 24 => iter_dirty_pages(&|off| { + dbg_assert!(off >= 0 && off < memory::vga_memory_size as isize); + let off = off - off % 3; + let src = memory::vga_mem8.offset(off); + let dest_offset = off / 3 - svga_dest_offset as isize; + let dest = dest_buffer.as_mut_ptr().offset(dest_offset) as *mut u32; + let end = if dest_offset < 0 { + 0 + } + else { + isize::min(4096 / 3 + 1, dest_buffer.len() as isize - dest_offset) + }; + for i in 0..end { + let dword = *(src.offset(3 * i) as *const u32); + let dword = if debug_bounds && (i == 0 || i == end - 1) { 0xFFFFFF } else { dword }; + dbg_assert!(dest_offset + i < dest_buffer.len() as isize); + *dest.offset(i) = dword << 16 | dword >> 16 & 0xFF | dword & 0xFF00 | 0xFF00_0000; + } + }), + 16 => iter_dirty_pages(&|off| { + dbg_assert!(off >= 0 && off + 2048 < memory::vga_memory_size as isize); + let src = memory::vga_mem8.offset(off) as *const u16; + let dest_offset = off / 2 - svga_dest_offset as isize; + let dest = dest_buffer.as_mut_ptr().offset(dest_offset) as *mut u32; + let end = if dest_offset < 0 { + 0 + } + else { + isize::min(2048, dest_buffer.len() as isize - dest_offset) + }; + for i in 0..end { + dbg_assert!(off + i < memory::vga_memory_size as isize); + let word = *src.offset(i); + let word = if debug_bounds && (i == 0 || i == end - 1) { 0xFFFF } else { word }; + let r = (word & 0x1F) * 0xFF / 0x1F; + let g = (word >> 5 & 0x3F) * 0xFF / 0x3F; + let b = (word >> 11) * 0xFF / 0x1F; + dbg_assert!(dest_offset + i < dest_buffer.len() as isize); + *dest.offset(i) = (r as u32) << 16 | (g as u32) << 8 | b as u32 | 0xFF00_0000; + } + }), + 15 => iter_dirty_pages(&|off| { + dbg_assert!(off >= 0 && off + 2048 < memory::vga_memory_size as isize); + let src = memory::vga_mem8.offset(off) as *const u16; + let dest_offset = off / 2 - svga_dest_offset as isize; + let dest = dest_buffer.as_mut_ptr().offset(dest_offset) as *mut u32; + let end = if dest_offset < 0 { + 0 + } + else { + isize::min(2048, dest_buffer.len() as isize - dest_offset) + }; + for i in 0..end { + dbg_assert!(off + i < memory::vga_memory_size as isize); + let word = *src.offset(i); + let word = if debug_bounds && (i == 0 || i == end - 1) { 0xFFFF } else { word }; + let r = (word & 0x1F) * 0xFF / 0x1F; + let g = (word >> 5 & 0x1F) * 0xFF / 0x1F; + let b = (word >> 10 & 0x1F) * 0xFF / 0x1F; + dbg_assert!(dest_offset + i < dest_buffer.len() as isize); + *dest.offset(i) = (r as u32) << 16 | (g as u32) << 8 | b as u32 | 0xFF00_0000; + } + }), + _ => { + dbg_log!("{}", bpp); + dbg_assert!(false, "Unsupported bpp"); + }, + } + + //if cfg!(debug_assertions) { + // let mut pages = 0; + // for &word in dirty_bitmap.iter() { + // pages += word.count_ones(); + // } + // dbg_log!( + // "fill offset={:x} bpp={} pages={}", + // svga_dest_offset, + // bpp, + // pages, + // ); + //} + + for v in dirty_bitmap.iter_mut() { + *v = 0 + } +} diff --git a/src/rust/cpu_context.rs b/src/rust/cpu_context.rs new file mode 100644 index 0000000..b065f5f --- /dev/null +++ b/src/rust/cpu_context.rs @@ -0,0 +1,59 @@ +use cpu::memory; +use prefix::{PREFIX_MASK_ADDRSIZE, PREFIX_MASK_OPSIZE}; +use state_flags::CachedStateFlags; + +#[derive(Clone)] +pub struct CpuContext { + pub eip: u32, + pub prefixes: u32, + pub cs_offset: u32, + pub state_flags: CachedStateFlags, +} + +impl CpuContext { + pub fn advance16(&mut self) { + dbg_assert!(self.eip & 0xFFF < 0xFFE); + self.eip += 2; + } + pub fn advance32(&mut self) { + dbg_assert!(self.eip & 0xFFF < 0xFFC); + self.eip += 4; + } + #[allow(unused)] + pub fn advance_moffs(&mut self) { + if self.asize_32() { self.advance32() } else { self.advance16() } + } + + pub fn read_imm8(&mut self) -> u8 { + dbg_assert!(self.eip & 0xFFF < 0xFFF); + let v = memory::read8(self.eip) as u8; + self.eip += 1; + v + } + pub fn read_imm8s(&mut self) -> i8 { self.read_imm8() as i8 } + pub fn read_imm16(&mut self) -> u16 { + dbg_assert!(self.eip & 0xFFF < 0xFFE); + let v = memory::read16(self.eip) as u16; + self.eip += 2; + v + } + pub fn read_imm32(&mut self) -> u32 { + dbg_assert!(self.eip & 0xFFF < 0xFFC); + let v = memory::read32s(self.eip) as u32; + self.eip += 4; + v + } + pub fn read_moffs(&mut self) -> u32 { + if self.asize_32() { self.read_imm32() } else { self.read_imm16() as u32 } + } + + pub fn cpl3(&self) -> bool { self.state_flags.cpl3() } + pub fn has_flat_segmentation(&self) -> bool { self.state_flags.has_flat_segmentation() } + pub fn osize_32(&self) -> bool { + self.state_flags.is_32() != (self.prefixes & PREFIX_MASK_OPSIZE != 0) + } + pub fn asize_32(&self) -> bool { + self.state_flags.is_32() != (self.prefixes & PREFIX_MASK_ADDRSIZE != 0) + } + pub fn ssize_32(&self) -> bool { self.state_flags.ssize_32() } +} diff --git a/src/rust/dbg.rs b/src/rust/dbg.rs new file mode 100644 index 0000000..8c62714 --- /dev/null +++ b/src/rust/dbg.rs @@ -0,0 +1,98 @@ +#[allow(unused_macros)] +macro_rules! dbg_log { + ($fmt:expr) => { + println!($fmt); + }; + ($fmt:expr, $($arg:tt)*) => { + println!($fmt, $($arg)*); + } +} + +#[allow(unused_macros)] +macro_rules! console_log { + ($fmt:expr) => { + println!($fmt); + }; + ($fmt:expr, $($arg:tt)*) => { + println!($fmt, $($arg)*); + } +} + +#[allow(unused_macros)] +macro_rules! dbg_assert { + ($($arg:tt)*) => { + debug_assert!($($arg)*) + }; +} + +#[cfg(target_arch = "wasm32")] +#[allow(unused_macros)] +macro_rules! console_log { + ($fmt:expr) => { + { + use ::util::{ console_log_to_js_console }; + console_log_to_js_console($fmt); + } + }; + ($fmt:expr, $($arg:tt)*) => { + { + use ::util::{ console_log_to_js_console }; + console_log_to_js_console(format!($fmt, $($arg)*)); + } + }; +} + +#[cfg(target_arch = "wasm32")] +#[allow(unused_macros)] +macro_rules! dbg_log { + ($fmt:expr) => { + { + use ::util::{ DEBUG, log_to_js_console }; + if DEBUG { log_to_js_console($fmt); } + } + }; + ($fmt:expr, $($arg:tt)*) => { + { + use ::util::{ DEBUG, log_to_js_console }; + if DEBUG { log_to_js_console(format!($fmt, $($arg)*)); } + } + }; +} + +#[cfg(target_arch = "wasm32")] +#[allow(unused_macros)] +macro_rules! dbg_assert { + ($cond:expr) => {{ + use util::{abort, log_to_js_console, DEBUG}; + if DEBUG && !$cond { + log_to_js_console(format!( + "Assertion failed at {}:{}:{}: '{}'", + file!(), + line!(), + column!(), + stringify!($cond), + )); + #[allow(unused_unsafe)] + unsafe { + abort(); + } + } + }}; + ($cond:expr, $desc:expr) => {{ + use util::{abort, log_to_js_console, DEBUG}; + if DEBUG && !$cond { + log_to_js_console(format!( + "Assertion failed at {}:{}:{}: '{}' - '{}'", + file!(), + line!(), + column!(), + stringify!($cond), + $desc, + )); + #[allow(unused_unsafe)] + unsafe { + abort(); + } + } + }}; +} diff --git a/src/rust/gen/mod.rs b/src/rust/gen/mod.rs new file mode 100644 index 0000000..8e076db --- /dev/null +++ b/src/rust/gen/mod.rs @@ -0,0 +1,8 @@ +pub mod interpreter; +pub mod interpreter0f; + +pub mod jit; +pub mod jit0f; + +pub mod analyzer; +pub mod analyzer0f; diff --git a/src/rust/jit.rs b/src/rust/jit.rs new file mode 100644 index 0000000..9981322 --- /dev/null +++ b/src/rust/jit.rs @@ -0,0 +1,2419 @@ +use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; +use std::iter::FromIterator; +use std::mem; +use std::ptr::NonNull; + +use analysis::AnalysisType; +use codegen; +use control_flow; +use control_flow::WasmStructure; +use cpu::cpu; +use cpu::global_pointers; +use cpu::memory; +use cpu_context::CpuContext; +use jit_instructions; +use opstats; +use page::Page; +use profiler; +use profiler::stat; +use state_flags::CachedStateFlags; +use util::SafeToU16; +use wasmgen::wasm_builder::{Label, WasmBuilder, WasmLocal}; + +#[derive(Copy, Clone, Eq, Hash, PartialEq)] +#[repr(transparent)] +pub struct WasmTableIndex(u16); +impl WasmTableIndex { + pub fn to_u16(self) -> u16 { self.0 } +} + +mod unsafe_jit { + use jit::{CachedStateFlags, WasmTableIndex}; + + extern "C" { + pub fn codegen_finalize( + wasm_table_index: WasmTableIndex, + phys_addr: u32, + state_flags: CachedStateFlags, + ptr: u32, + len: u32, + ); + pub fn jit_clear_func(wasm_table_index: WasmTableIndex); + } +} + +fn codegen_finalize( + wasm_table_index: WasmTableIndex, + phys_addr: u32, + state_flags: CachedStateFlags, + ptr: u32, + len: u32, +) { + unsafe { unsafe_jit::codegen_finalize(wasm_table_index, phys_addr, state_flags, ptr, len) } +} + +pub fn jit_clear_func(wasm_table_index: WasmTableIndex) { + unsafe { unsafe_jit::jit_clear_func(wasm_table_index) } +} + +// Maximum number of pages per wasm module. Necessary for the following reasons: +// - There is an upper limit on the size of a single function in wasm (currently ~7MB in all browsers) +// See https://github.com/WebAssembly/design/issues/1138 +// - v8 poorly handles large br_table elements and OOMs on modules much smaller than the above limit +// See https://bugs.chromium.org/p/v8/issues/detail?id=9697 and https://bugs.chromium.org/p/v8/issues/detail?id=9141 +// Will hopefully be fixed in the near future by generating direct control flow +static mut MAX_PAGES: u32 = 3; + +static mut JIT_USE_LOOP_SAFETY: bool = true; + +pub static mut MAX_EXTRA_BASIC_BLOCKS: u32 = 250; + +pub const JIT_THRESHOLD: u32 = 200 * 1000; + +// less branches will generate if-else, more will generate brtable +pub const BRTABLE_CUTOFF: usize = 10; + +// needs to be synced to const.js +pub const WASM_TABLE_SIZE: u32 = 900; + +pub const CHECK_JIT_STATE_INVARIANTS: bool = false; + +const MAX_INSTRUCTION_LENGTH: u32 = 16; + +#[allow(non_upper_case_globals)] +static mut jit_state: NonNull = + unsafe { NonNull::new_unchecked(mem::align_of::() as *mut _) }; + +pub fn get_jit_state() -> &'static mut JitState { unsafe { jit_state.as_mut() } } + +#[no_mangle] +pub fn rust_init() { + dbg_assert!(std::mem::size_of::<[Option>; 0x100000]>() == 0x100000 * 4); + + let x = Box::new(JitState::create_and_initialise()); + unsafe { + jit_state = NonNull::new(Box::into_raw(x)).unwrap() + } + + use std::panic; + + panic::set_hook(Box::new(|panic_info| { + console_log!("{}", panic_info.to_string()); + })); +} + +struct PageInfo { + wasm_table_index: WasmTableIndex, + hidden_wasm_table_indices: Vec, + entry_points: Vec<(u16, u16)>, + state_flags: CachedStateFlags, +} + +enum CompilingPageState { + Compiling { pages: HashMap }, + CompilingWritten, +} + +pub struct JitState { + wasm_builder: WasmBuilder, + + // as an alternative to HashSet, we could use a bitmap of 4096 bits here + // (faster, but uses much more memory) + // or a compressed bitmap (likely faster) + // or HashSet rather than nested + entry_points: HashMap)>, + pages: HashMap, + wasm_table_index_free_list: Vec, + compiling: Option<(WasmTableIndex, CompilingPageState)>, +} + +pub fn check_jit_state_invariants(ctx: &mut JitState) { + if !CHECK_JIT_STATE_INVARIANTS { + return; + } + + match &ctx.compiling { + Some((_, CompilingPageState::Compiling { pages })) => { + dbg_assert!(pages.keys().all(|page| ctx.entry_points.contains_key(page))); + }, + _ => {}, + } + + let free: HashSet = + HashSet::from_iter(ctx.wasm_table_index_free_list.iter().cloned()); + let used = HashSet::from_iter(ctx.pages.values().map(|info| info.wasm_table_index)); + let compiling = HashSet::from_iter(ctx.compiling.as_ref().map(|&(index, _)| index)); + dbg_assert!(free.intersection(&used).next().is_none()); + dbg_assert!(used.intersection(&compiling).next().is_none()); + dbg_assert!(free.len() + used.len() + compiling.len() == (WASM_TABLE_SIZE - 1) as usize); + + match &ctx.compiling { + Some((_, CompilingPageState::Compiling { pages })) => { + dbg_assert!(pages.keys().all(|page| ctx.entry_points.contains_key(page))); + }, + _ => {}, + } + + for i in 0..unsafe { cpu::valid_tlb_entries_count } { + let page = unsafe { cpu::valid_tlb_entries[i as usize] }; + let entry = unsafe { cpu::tlb_data[page as usize] }; + if 0 != entry { + let tlb_physical_page = Page::of_u32( + (entry as u32 >> 12 ^ page as u32) - (unsafe { memory::mem8 } as u32 >> 12), + ); + let w = match unsafe { cpu::tlb_code[page as usize] } { + None => None, + Some(c) => unsafe { + Some(c.as_ref().wasm_table_index) + }, + }; + let tlb_has_code = entry & cpu::TLB_HAS_CODE == cpu::TLB_HAS_CODE; + let infos = ctx.pages.get(&tlb_physical_page); + let entry_points = ctx.entry_points.get(&tlb_physical_page); + dbg_assert!(tlb_has_code || !w.is_some()); + dbg_assert!(tlb_has_code || !infos.is_some()); + dbg_assert!(tlb_has_code || !entry_points.is_some()); + //dbg_assert!((w.is_some() || page.is_some() || entry_points.is_some()) == tlb_has_code); // XXX: check this + } + } +} + +impl JitState { + pub fn create_and_initialise() -> JitState { + // don't assign 0 (XXX: Check) + let wasm_table_indices = (1..=(WASM_TABLE_SIZE - 1) as u16).map(|x| WasmTableIndex(x)); + + JitState { + wasm_builder: WasmBuilder::new(), + + entry_points: HashMap::new(), + pages: HashMap::new(), + + wasm_table_index_free_list: Vec::from_iter(wasm_table_indices), + compiling: None, + } + } +} + +#[derive(PartialEq, Eq)] +pub enum BasicBlockType { + Normal { + next_block_addr: Option, + jump_offset: i32, + jump_offset_is_32: bool, + }, + ConditionalJump { + next_block_addr: Option, + next_block_branch_taken_addr: Option, + condition: u8, + jump_offset: i32, + jump_offset_is_32: bool, + }, + // Set eip to an absolute value (ret, jmp r/m, call r/m) + AbsoluteEip, + Exit, +} + +pub struct BasicBlock { + pub addr: u32, + pub virt_addr: i32, + pub last_instruction_addr: u32, + pub end_addr: u32, + pub is_entry_block: bool, + pub ty: BasicBlockType, + pub has_sti: bool, + pub number_of_instructions: u32, +} + +#[derive(Copy, Clone, PartialEq)] +pub struct CachedCode { + pub wasm_table_index: WasmTableIndex, + pub initial_state: u16, +} + +impl CachedCode { + pub const NONE: CachedCode = CachedCode { + wasm_table_index: WasmTableIndex(0), + initial_state: 0, + }; +} + +#[derive(PartialEq)] +pub enum InstructionOperandDest { + WasmLocal(WasmLocal), + Other, +} +#[derive(PartialEq)] +pub enum InstructionOperand { + WasmLocal(WasmLocal), + Immediate(i32), + Other, +} +impl InstructionOperand { + pub fn is_zero(&self) -> bool { + match self { + InstructionOperand::Immediate(0) => true, + _ => false, + } + } +} +impl Into for InstructionOperandDest { + fn into(self: InstructionOperandDest) -> InstructionOperand { + match self { + InstructionOperandDest::WasmLocal(l) => InstructionOperand::WasmLocal(l), + InstructionOperandDest::Other => InstructionOperand::Other, + } + } +} +pub enum Instruction { + Cmp { + dest: InstructionOperandDest, + source: InstructionOperand, + opsize: i32, + }, + Sub { + dest: InstructionOperandDest, + source: InstructionOperand, + opsize: i32, + is_dec: bool, + }, + Add { + dest: InstructionOperandDest, + source: InstructionOperand, + opsize: i32, + is_inc: bool, + }, + AdcSbb { + dest: InstructionOperandDest, + source: InstructionOperand, + opsize: i32, + }, + NonZeroShift { + dest: InstructionOperandDest, + opsize: i32, + }, + Bitwise { + dest: InstructionOperandDest, + opsize: i32, + }, + Other, +} + +pub struct JitContext<'a> { + pub cpu: &'a mut CpuContext, + pub builder: &'a mut WasmBuilder, + pub register_locals: &'a mut Vec, + pub start_of_current_instruction: u32, + pub exit_with_fault_label: Label, + pub exit_label: Label, + pub current_instruction: Instruction, + pub previous_instruction: Instruction, + pub instruction_counter: WasmLocal, +} +impl<'a> JitContext<'a> { + pub fn reg(&self, i: u32) -> WasmLocal { self.register_locals[i as usize].unsafe_clone() } +} + +pub const JIT_INSTR_BLOCK_BOUNDARY_FLAG: u32 = 1 << 0; + +pub fn is_near_end_of_page(address: u32) -> bool { + address & 0xFFF >= 0x1000 - MAX_INSTRUCTION_LENGTH +} + +pub fn jit_find_cache_entry(phys_address: u32, state_flags: CachedStateFlags) -> CachedCode { + // TODO: dedup with jit_find_cache_entry_in_page? + // NOTE: This is currently only used for invariant/missed-entry-point checking + let ctx = get_jit_state(); + + match ctx.pages.get(&Page::page_of(phys_address)) { + Some(PageInfo { + wasm_table_index, + state_flags: s, + entry_points, + hidden_wasm_table_indices: _, + }) => { + if *s == state_flags { + let page_offset = phys_address as u16 & 0xFFF; + if let Some(&(_, initial_state)) = + entry_points.iter().find(|(p, _)| p == &page_offset) + { + return CachedCode { + wasm_table_index: *wasm_table_index, + initial_state, + }; + } + } + }, + None => {}, + } + + return CachedCode::NONE; +} + +#[no_mangle] +pub fn jit_find_cache_entry_in_page( + virt_address: u32, + wasm_table_index: WasmTableIndex, + state_flags: u32, +) -> i32 { + // TODO: generate code for this + profiler::stat_increment(stat::INDIRECT_JUMP); + + let state_flags = CachedStateFlags::of_u32(state_flags); + + unsafe { + match cpu::tlb_code[(virt_address >> 12) as usize] { + None => {}, + Some(c) => { + let c = c.as_ref(); + if state_flags == c.state_flags && wasm_table_index == c.wasm_table_index { + let state = c.state_table[virt_address as usize & 0xFFF]; + if state != u16::MAX { + return state.into(); + } + } + }, + } + } + + profiler::stat_increment(stat::INDIRECT_JUMP_NO_ENTRY); + + return -1; +} + +fn jit_find_basic_blocks( + ctx: &mut JitState, + entry_points: HashSet, + cpu: CpuContext, +) -> Vec { + fn follow_jump( + virt_target: i32, + ctx: &mut JitState, + pages: &mut HashSet, + page_blacklist: &mut HashSet, + max_pages: u32, + marked_as_entry: &mut HashSet, + to_visit_stack: &mut Vec, + ) -> Option { + if is_near_end_of_page(virt_target as u32) { + return None; + } + let phys_target = match cpu::translate_address_read_no_side_effects(virt_target) { + Err(()) => { + dbg_log!("Not analysing {:x} (page not mapped)", virt_target); + return None; + }, + Ok(t) => t, + }; + + let phys_page = Page::page_of(phys_target); + + if !pages.contains(&phys_page) && pages.len() as u32 == max_pages + || page_blacklist.contains(&phys_page) + { + return None; + } + + if !pages.contains(&phys_page) { + // page seen for the first time, handle entry points + if let Some((hotness, entry_points)) = ctx.entry_points.get_mut(&phys_page) { + let existing_entry_points = match ctx.pages.get(&phys_page) { + Some(PageInfo { entry_points, .. }) => { + HashSet::from_iter(entry_points.iter().map(|x| x.0)) + }, + None => HashSet::new(), + }; + + if entry_points + .iter() + .all(|entry_point| existing_entry_points.contains(entry_point)) + { + page_blacklist.insert(phys_page); + return None; + } + + // XXX: Remove this paragraph + //let old_length = entry_points.len(); + //entry_points.extend(existing_entry_points); + //dbg_assert!( + // entry_points.union(&existing_entry_points).count() == entry_points.len() + //); + + *hotness = 0; + + for &addr_low in entry_points.iter() { + let addr = virt_target & !0xFFF | addr_low as i32; + to_visit_stack.push(addr); + marked_as_entry.insert(addr); + } + } + else { + // no entry points: ignore this page? + page_blacklist.insert(phys_page); + return None; + } + + pages.insert(phys_page); + dbg_assert!(pages.len() as u32 <= max_pages); + } + + to_visit_stack.push(virt_target); + Some(phys_target) + } + + let mut to_visit_stack: Vec = Vec::new(); + let mut marked_as_entry: HashSet = HashSet::new(); + let mut basic_blocks: BTreeMap = BTreeMap::new(); + let mut pages: HashSet = HashSet::new(); + let mut page_blacklist = HashSet::new(); + + // 16-bit doesn't not work correctly, most likely due to instruction pointer wrap-around + let max_pages = if cpu.state_flags.is_32() { + unsafe { MAX_PAGES } + } + else { + 1 + }; + + for virt_addr in entry_points { + let ok = follow_jump( + virt_addr, + ctx, + &mut pages, + &mut page_blacklist, + max_pages, + &mut marked_as_entry, + &mut to_visit_stack, + ); + dbg_assert!(ok.is_some()); + dbg_assert!(marked_as_entry.contains(&virt_addr)); + } + + while let Some(to_visit) = to_visit_stack.pop() { + let phys_addr = match cpu::translate_address_read_no_side_effects(to_visit) { + Err(()) => { + dbg_log!("Not analysing {:x} (page not mapped)", to_visit); + continue; + }, + Ok(phys_addr) => phys_addr, + }; + + if basic_blocks.contains_key(&phys_addr) { + continue; + } + + if is_near_end_of_page(phys_addr) { + // Empty basic block, don't insert + profiler::stat_increment(stat::COMPILE_CUT_OFF_AT_END_OF_PAGE); + continue; + } + + let mut current_address = phys_addr; + let mut current_block = BasicBlock { + addr: current_address, + virt_addr: to_visit, + last_instruction_addr: 0, + end_addr: 0, + ty: BasicBlockType::Exit, + is_entry_block: false, + has_sti: false, + number_of_instructions: 0, + }; + loop { + let addr_before_instruction = current_address; + let mut cpu = &mut CpuContext { + eip: current_address, + ..cpu + }; + let analysis = ::analysis::analyze_step(&mut cpu); + current_block.number_of_instructions += 1; + let has_next_instruction = !analysis.no_next_instruction; + current_address = cpu.eip; + + dbg_assert!(Page::page_of(current_address) == Page::page_of(addr_before_instruction)); + let current_virt_addr = to_visit & !0xFFF | current_address as i32 & 0xFFF; + + match analysis.ty { + AnalysisType::Normal | AnalysisType::STI => { + dbg_assert!(has_next_instruction); + dbg_assert!(!analysis.absolute_jump); + + if current_block.has_sti { + // Convert next instruction after STI (i.e., the current instruction) into block boundary + + marked_as_entry.insert(current_virt_addr); + to_visit_stack.push(current_virt_addr); + + current_block.last_instruction_addr = addr_before_instruction; + current_block.end_addr = current_address; + break; + } + + if analysis.ty == AnalysisType::STI { + current_block.has_sti = true; + + dbg_assert!( + !is_near_end_of_page(current_address), + "TODO: Handle STI instruction near end of page" + ); + } + else { + // Only split non-STI blocks (one instruction needs to run after STI before + // handle_irqs may be called) + + if basic_blocks.contains_key(¤t_address) { + current_block.last_instruction_addr = addr_before_instruction; + current_block.end_addr = current_address; + dbg_assert!(!is_near_end_of_page(current_address)); + current_block.ty = BasicBlockType::Normal { + next_block_addr: Some(current_address), + jump_offset: 0, + jump_offset_is_32: true, + }; + break; + } + } + }, + AnalysisType::Jump { + offset, + is_32, + condition: Some(condition), + } => { + dbg_assert!(!analysis.absolute_jump); + // conditional jump: continue at next and continue at jump target + + let jump_target = if is_32 { + current_virt_addr + offset + } + else { + cpu.cs_offset as i32 + + (current_virt_addr - cpu.cs_offset as i32 + offset & 0xFFFF) + }; + + dbg_assert!(has_next_instruction); + to_visit_stack.push(current_virt_addr); + + let next_block_addr = if is_near_end_of_page(current_address) { + None + } + else { + Some(current_address) + }; + + current_block.ty = BasicBlockType::ConditionalJump { + next_block_addr, + next_block_branch_taken_addr: follow_jump( + jump_target, + ctx, + &mut pages, + &mut page_blacklist, + max_pages, + &mut marked_as_entry, + &mut to_visit_stack, + ), + condition, + jump_offset: offset, + jump_offset_is_32: is_32, + }; + + current_block.last_instruction_addr = addr_before_instruction; + current_block.end_addr = current_address; + + break; + }, + AnalysisType::Jump { + offset, + is_32, + condition: None, + } => { + dbg_assert!(!analysis.absolute_jump); + // non-conditional jump: continue at jump target + + let jump_target = if is_32 { + current_virt_addr + offset + } + else { + cpu.cs_offset as i32 + + (current_virt_addr - cpu.cs_offset as i32 + offset & 0xFFFF) + }; + + if has_next_instruction { + // Execution will eventually come back to the next instruction (CALL) + marked_as_entry.insert(current_virt_addr); + to_visit_stack.push(current_virt_addr); + } + + current_block.ty = BasicBlockType::Normal { + next_block_addr: follow_jump( + jump_target, + ctx, + &mut pages, + &mut page_blacklist, + max_pages, + &mut marked_as_entry, + &mut to_visit_stack, + ), + jump_offset: offset, + jump_offset_is_32: is_32, + }; + current_block.last_instruction_addr = addr_before_instruction; + current_block.end_addr = current_address; + + break; + }, + AnalysisType::BlockBoundary => { + // a block boundary but not a jump, get out + + if has_next_instruction { + // block boundary, but execution will eventually come back + // to the next instruction. Create a new basic block + // starting at the next instruction and register it as an + // entry point + marked_as_entry.insert(current_virt_addr); + to_visit_stack.push(current_virt_addr); + } + + if analysis.absolute_jump { + current_block.ty = BasicBlockType::AbsoluteEip; + } + + current_block.last_instruction_addr = addr_before_instruction; + current_block.end_addr = current_address; + break; + }, + } + + if is_near_end_of_page(current_address) { + current_block.last_instruction_addr = addr_before_instruction; + current_block.end_addr = current_address; + profiler::stat_increment(stat::COMPILE_CUT_OFF_AT_END_OF_PAGE); + break; + } + } + + let previous_block = basic_blocks + .range(..current_block.addr) + .next_back() + .filter(|(_, previous_block)| (!previous_block.has_sti)) + .map(|(_, previous_block)| previous_block.clone()); + + if let Some(previous_block) = previous_block { + if current_block.addr < previous_block.end_addr { + // If this block overlaps with the previous block, re-analyze the previous block + to_visit_stack.push(previous_block.virt_addr); + + let addr = previous_block.addr; + let old_block = basic_blocks.remove(&addr); + dbg_assert!(old_block.is_some()); + + // Note that this does not ensure the invariant that two consecutive blocks don't + // overlay. For that, we also need to check the following block. + } + } + + dbg_assert!(current_block.addr < current_block.end_addr); + dbg_assert!(current_block.addr <= current_block.last_instruction_addr); + dbg_assert!(current_block.last_instruction_addr < current_block.end_addr); + + basic_blocks.insert(current_block.addr, current_block); + } + + dbg_assert!(pages.len() as u32 <= max_pages); + + for block in basic_blocks.values_mut() { + if marked_as_entry.contains(&block.virt_addr) { + block.is_entry_block = true; + } + } + + let basic_blocks: Vec = basic_blocks.into_iter().map(|(_, block)| block).collect(); + + for i in 0..basic_blocks.len() - 1 { + let next_block_addr = basic_blocks[i + 1].addr; + let next_block_end_addr = basic_blocks[i + 1].end_addr; + let next_block_is_entry = basic_blocks[i + 1].is_entry_block; + let block = &basic_blocks[i]; + dbg_assert!(block.addr < next_block_addr); + if next_block_addr < block.end_addr { + dbg_log!( + "Overlapping first=[from={:x} to={:x} is_entry={}] second=[from={:x} to={:x} is_entry={}]", + block.addr, + block.end_addr, + block.is_entry_block as u8, + next_block_addr, + next_block_end_addr, + next_block_is_entry as u8 + ); + } + } + + basic_blocks +} + +#[no_mangle] +#[cfg(debug_assertions)] +pub fn jit_force_generate_unsafe(virt_addr: i32) { + dbg_assert!( + !is_near_end_of_page(virt_addr as u32), + "cannot force compile near end of page" + ); + jit_increase_hotness_and_maybe_compile( + virt_addr, + cpu::translate_address_read(virt_addr).unwrap(), + cpu::get_seg_cs() as u32, + cpu::get_state_flags(), + JIT_THRESHOLD, + ); + dbg_assert!(get_jit_state().compiling.is_some()); +} + +#[inline(never)] +fn jit_analyze_and_generate( + ctx: &mut JitState, + virt_entry_point: i32, + phys_entry_point: u32, + cs_offset: u32, + state_flags: CachedStateFlags, +) { + let page = Page::page_of(phys_entry_point); + + dbg_assert!(ctx.compiling.is_none()); + + let (_, entry_points) = match ctx.entry_points.get(&page) { + None => return, + Some(entry_points) => entry_points, + }; + + let existing_entry_points = match ctx.pages.get(&page) { + Some(PageInfo { entry_points, .. }) => HashSet::from_iter(entry_points.iter().map(|x| x.0)), + None => HashSet::new(), + }; + + if entry_points + .iter() + .all(|entry_point| existing_entry_points.contains(entry_point)) + { + profiler::stat_increment(stat::COMPILE_SKIPPED_NO_NEW_ENTRY_POINTS); + return; + } + + // XXX: check and remove + //let old_length = entry_points.len(); + //entry_points.extend(existing_entry_points); + //dbg_log!( + // "{} + {} = {}", + // entry_points.len(), + // existing_entry_points.len(), + // entry_points.union(&existing_entry_points).count() + //); + //dbg_assert!(entry_points.union(&existing_entry_points).count() == entry_points.len()); + + profiler::stat_increment(stat::COMPILE); + + let cpu = CpuContext { + eip: 0, + prefixes: 0, + cs_offset, + state_flags, + }; + + dbg_assert!( + cpu::translate_address_read_no_side_effects(virt_entry_point).unwrap() == phys_entry_point + ); + let virt_page = Page::page_of(virt_entry_point as u32); + let entry_points: HashSet = entry_points + .iter() + .map(|e| virt_page.to_address() as i32 | *e as i32) + .collect(); + let basic_blocks = jit_find_basic_blocks(ctx, entry_points, cpu.clone()); + + let mut pages = HashSet::new(); + + for b in basic_blocks.iter() { + // Remove this assertion once page-crossing jit is enabled + dbg_assert!(Page::page_of(b.addr) == Page::page_of(b.end_addr)); + pages.insert(Page::page_of(b.addr)); + } + + let print = false; + + for b in basic_blocks.iter() { + if !print { + break; + } + let last_instruction_opcode = memory::read32s(b.last_instruction_addr); + let op = opstats::decode(last_instruction_opcode as u32); + dbg_log!( + "BB: 0x{:x} {}{:02x} {} {}", + b.addr, + if op.is_0f { "0f" } else { "" }, + op.opcode, + if b.is_entry_block { "entry" } else { "noentry" }, + match &b.ty { + BasicBlockType::ConditionalJump { + next_block_addr: Some(next_block_addr), + next_block_branch_taken_addr: Some(next_block_branch_taken_addr), + .. + } => format!( + "0x{:x} 0x{:x}", + next_block_addr, next_block_branch_taken_addr + ), + BasicBlockType::ConditionalJump { + next_block_addr: None, + next_block_branch_taken_addr: Some(next_block_branch_taken_addr), + .. + } => format!("0x{:x}", next_block_branch_taken_addr), + BasicBlockType::ConditionalJump { + next_block_addr: Some(next_block_addr), + next_block_branch_taken_addr: None, + .. + } => format!("0x{:x}", next_block_addr), + BasicBlockType::ConditionalJump { + next_block_addr: None, + next_block_branch_taken_addr: None, + .. + } => format!(""), + BasicBlockType::Normal { + next_block_addr: Some(next_block_addr), + .. + } => format!("0x{:x}", next_block_addr), + BasicBlockType::Normal { + next_block_addr: None, + .. + } => format!(""), + BasicBlockType::Exit => format!(""), + BasicBlockType::AbsoluteEip => format!(""), + } + ); + } + + let graph = control_flow::make_graph(&basic_blocks); + let mut structure = control_flow::loopify(&graph); + + if print { + dbg_log!("before blockify:"); + for group in &structure { + dbg_log!("=> Group"); + group.print(0); + } + } + + control_flow::blockify(&mut structure, &graph); + + if cfg!(debug_assertions) { + control_flow::assert_invariants(&structure); + } + + if print { + dbg_log!("after blockify:"); + for group in &structure { + dbg_log!("=> Group"); + group.print(0); + } + } + + if ctx.wasm_table_index_free_list.is_empty() { + dbg_log!("wasm_table_index_free_list empty, clearing cache"); + + // When no free slots are available, delete all cached modules. We could increase the + // size of the table, but this way the initial size acts as an upper bound for the + // number of wasm modules that we generate, which we want anyway to avoid getting our + // tab killed by browsers due to memory constraints. + jit_clear_cache(ctx); + + profiler::stat_increment(stat::INVALIDATE_ALL_MODULES_NO_FREE_WASM_INDICES); + + dbg_log!( + "after jit_clear_cache: {} free", + ctx.wasm_table_index_free_list.len(), + ); + + // This assertion can fail if all entries are pending (not possible unless + // WASM_TABLE_SIZE is set very low) + dbg_assert!(!ctx.wasm_table_index_free_list.is_empty()); + } + + // allocate an index in the wasm table + let wasm_table_index = ctx + .wasm_table_index_free_list + .pop() + .expect("allocate wasm table index"); + dbg_assert!(wasm_table_index != WasmTableIndex(0)); + + dbg_assert!(!pages.is_empty()); + dbg_assert!(pages.len() <= unsafe { MAX_PAGES } as usize); + + let basic_block_by_addr: HashMap = + basic_blocks.into_iter().map(|b| (b.addr, b)).collect(); + + let entries = jit_generate_module( + structure, + &basic_block_by_addr, + cpu, + &mut ctx.wasm_builder, + wasm_table_index, + state_flags, + ); + dbg_assert!(!entries.is_empty()); + + let mut page_info = HashMap::new(); + for &(addr, state) in &entries { + let code = page_info + .entry(Page::page_of(addr)) + .or_insert_with(|| PageInfo { + wasm_table_index, + state_flags, + entry_points: Vec::new(), + hidden_wasm_table_indices: Vec::new(), + }); + code.entry_points.push((addr as u16 & 0xFFF, state)); + } + + profiler::stat_increment_by( + stat::COMPILE_WASM_TOTAL_BYTES, + ctx.wasm_builder.get_output_len() as u64, + ); + profiler::stat_increment_by(stat::COMPILE_PAGE, pages.len() as u64); + + for &p in &pages { + ctx.entry_points + .entry(p) + .or_insert_with(|| (0, HashSet::new())); + } + + cpu::tlb_set_has_code_multiple(&pages, true); + + dbg_assert!(ctx.compiling.is_none()); + ctx.compiling = Some(( + wasm_table_index, + CompilingPageState::Compiling { pages: page_info }, + )); + + let phys_addr = page.to_address(); + + // will call codegen_finalize_finished asynchronously when finished + codegen_finalize( + wasm_table_index, + phys_addr, + state_flags, + ctx.wasm_builder.get_output_ptr() as u32, + ctx.wasm_builder.get_output_len(), + ); + + check_jit_state_invariants(ctx); +} + +#[no_mangle] +pub fn codegen_finalize_finished( + wasm_table_index: WasmTableIndex, + phys_addr: u32, + state_flags: CachedStateFlags, +) { + let ctx = get_jit_state(); + + dbg_assert!(wasm_table_index != WasmTableIndex(0)); + + dbg_log!( + "Finished compiling for page at {:x}", + Page::page_of(phys_addr).to_address() + ); + + let pages = match mem::replace(&mut ctx.compiling, None) { + None => { + dbg_assert!(false); + return; + }, + Some((in_progress_wasm_table_index, CompilingPageState::CompilingWritten)) => { + dbg_assert!(wasm_table_index == in_progress_wasm_table_index); + + profiler::stat_increment(stat::INVALIDATE_MODULE_WRITTEN_WHILE_COMPILED); + free_wasm_table_index(ctx, wasm_table_index); + check_jit_state_invariants(ctx); + return; + }, + Some((in_progress_wasm_table_index, CompilingPageState::Compiling { pages })) => { + dbg_assert!(wasm_table_index == in_progress_wasm_table_index); + dbg_assert!(!pages.is_empty()); + pages + }, + }; + + for i in 0..unsafe { cpu::valid_tlb_entries_count } { + let page = unsafe { cpu::valid_tlb_entries[i as usize] }; + let entry = unsafe { cpu::tlb_data[page as usize] }; + if 0 != entry { + let tlb_physical_page = Page::of_u32( + (entry as u32 >> 12 ^ page as u32) - (unsafe { memory::mem8 } as u32 >> 12), + ); + if let Some(info) = pages.get(&tlb_physical_page) { + set_tlb_code( + Page::of_u32(page as u32), + wasm_table_index, + &info.entry_points, + state_flags, + ); + } + } + } + + let mut check_for_unused_wasm_table_index = HashSet::new(); + + for (page, mut info) in pages { + if let Some(old_entry) = ctx.pages.remove(&page) { + info.hidden_wasm_table_indices + .extend(old_entry.hidden_wasm_table_indices); + info.hidden_wasm_table_indices + .push(old_entry.wasm_table_index); + check_for_unused_wasm_table_index.insert(old_entry.wasm_table_index); + } + ctx.pages.insert(page, info); + } + + let unused: Vec<&WasmTableIndex> = check_for_unused_wasm_table_index + .iter() + .filter(|&&i| ctx.pages.values().all(|page| page.wasm_table_index != i)) + .collect(); + + for &index in unused { + for p in ctx.pages.values_mut() { + p.hidden_wasm_table_indices.retain(|&w| w != index); + } + + dbg_log!("unused after overwrite {}", index.to_u16()); + profiler::stat_increment(stat::INVALIDATE_MODULE_UNUSED_AFTER_OVERWRITE); + free_wasm_table_index(ctx, index); + } + + check_jit_state_invariants(ctx); +} + +pub fn update_tlb_code(virt_page: Page, phys_page: Page) { + let ctx = get_jit_state(); + + match ctx.pages.get(&phys_page) { + Some(PageInfo { + wasm_table_index, + entry_points, + state_flags, + hidden_wasm_table_indices: _, + }) => set_tlb_code(virt_page, *wasm_table_index, entry_points, *state_flags), + None => cpu::clear_tlb_code(phys_page.to_u32() as i32), + }; +} + +pub fn set_tlb_code( + virt_page: Page, + wasm_table_index: WasmTableIndex, + entries: &Vec<(u16, u16)>, + state_flags: CachedStateFlags, +) { + let c = match unsafe { cpu::tlb_code[virt_page.to_u32() as usize] } { + None => { + let state_table = [u16::MAX; 0x1000]; + unsafe { + let mut c = NonNull::new_unchecked(Box::into_raw(Box::new(cpu::Code { + wasm_table_index, + state_flags, + state_table, + }))); + cpu::tlb_code[virt_page.to_u32() as usize] = Some(c); + c.as_mut() + } + }, + Some(mut c) => unsafe { + let c = c.as_mut(); + c.state_table.fill(u16::MAX); + c.state_flags = state_flags; + c.wasm_table_index = wasm_table_index; + c + }, + }; + + for &(addr, state) in entries { + dbg_assert!(state != u16::MAX); + c.state_table[addr as usize] = state; + } +} + +fn jit_generate_module( + structure: Vec, + basic_blocks: &HashMap, + mut cpu: CpuContext, + builder: &mut WasmBuilder, + wasm_table_index: WasmTableIndex, + state_flags: CachedStateFlags, +) -> Vec<(u32, u16)> { + builder.reset(); + + let mut register_locals = (0..8) + .map(|i| { + builder.load_fixed_i32(global_pointers::get_reg32_offset(i)); + builder.set_new_local() + }) + .collect(); + + builder.const_i32(0); + let instruction_counter = builder.set_new_local(); + + let exit_label = builder.block_void(); + let exit_with_fault_label = builder.block_void(); + let main_loop_label = builder.loop_void(); + if unsafe { JIT_USE_LOOP_SAFETY } { + builder.get_local(&instruction_counter); + builder.const_i32(cpu::LOOP_COUNTER); + builder.geu_i32(); + if cfg!(feature = "profiler") { + builder.if_void(); + codegen::gen_debug_track_jit_exit(builder, 0); + builder.br(exit_label); + builder.block_end(); + } + else { + builder.br_if(exit_label); + } + } + let brtable_default = builder.block_void(); + + let ctx = &mut JitContext { + cpu: &mut cpu, + builder, + register_locals: &mut register_locals, + start_of_current_instruction: 0, + exit_with_fault_label, + exit_label, + current_instruction: Instruction::Other, + previous_instruction: Instruction::Other, + instruction_counter, + }; + + let entry_blocks = { + let mut nodes = &structure; + let result; + loop { + match &nodes[0] { + WasmStructure::Dispatcher(e) => { + result = e.clone(); + break; + }, + WasmStructure::Loop { .. } => { + dbg_assert!(false); + }, + WasmStructure::BasicBlock(_) => { + dbg_assert!(false); + }, + // Note: We could use these blocks as entry points, which will yield + // more entries for free, but it requires adding those to the dispatcher + // It's to be investigated if this yields a performance improvement + // See also the comment at the bottom of this function when creating entry + // points + WasmStructure::Block(children) => { + nodes = children; + }, + } + } + result + }; + + let mut index_for_addr = HashMap::new(); + for (i, &addr) in entry_blocks.iter().enumerate() { + index_for_addr.insert(addr, i as i32); + } + for b in basic_blocks.values() { + if !index_for_addr.contains_key(&b.addr) { + let i = index_for_addr.len(); + index_for_addr.insert(b.addr, i as i32); + } + } + + let mut label_for_addr: HashMap)> = HashMap::new(); + + enum Work { + WasmStructure(WasmStructure), + BlockEnd { + label: Label, + targets: Vec, + olds: HashMap)>, + }, + LoopEnd { + label: Label, + entries: Vec, + olds: HashMap)>, + }, + } + let mut work: VecDeque = structure + .into_iter() + .map(|x| Work::WasmStructure(x)) + .collect(); + + while let Some(block) = work.pop_front() { + let next_addr: Option> = work.iter().find_map(|x| match x { + Work::WasmStructure(l) => Some(l.head().collect()), + _ => None, + }); + let target_block = &ctx.builder.arg_local_initial_state.unsafe_clone(); + + match block { + Work::WasmStructure(WasmStructure::BasicBlock(addr)) => { + let block = basic_blocks.get(&addr).unwrap(); + jit_generate_basic_block(ctx, block); + + if block.has_sti { + match block.ty { + BasicBlockType::ConditionalJump { + condition, + jump_offset, + jump_offset_is_32, + .. + } => { + codegen::gen_set_eip_low_bits( + ctx.builder, + block.end_addr as i32 & 0xFFF, + ); + codegen::gen_condition_fn(ctx, condition); + ctx.builder.if_void(); + if jump_offset_is_32 { + codegen::gen_relative_jump(ctx.builder, jump_offset); + } + else { + codegen::gen_jmp_rel16(ctx.builder, jump_offset as u16); + } + ctx.builder.block_end(); + }, + BasicBlockType::Normal { + jump_offset, + jump_offset_is_32, + .. + } => { + if jump_offset_is_32 { + codegen::gen_set_eip_low_bits_and_jump_rel32( + ctx.builder, + block.end_addr as i32 & 0xFFF, + jump_offset, + ); + } + else { + codegen::gen_set_eip_low_bits( + ctx.builder, + block.end_addr as i32 & 0xFFF, + ); + codegen::gen_jmp_rel16(ctx.builder, jump_offset as u16); + } + }, + BasicBlockType::Exit => {}, + BasicBlockType::AbsoluteEip => {}, + }; + codegen::gen_debug_track_jit_exit(ctx.builder, block.last_instruction_addr); + codegen::gen_move_registers_from_locals_to_memory(ctx); + codegen::gen_fn0_const(ctx.builder, "handle_irqs"); + codegen::gen_update_instruction_counter(ctx); + ctx.builder.return_(); + continue; + } + + match &block.ty { + BasicBlockType::Exit => { + // Exit this function + codegen::gen_debug_track_jit_exit(ctx.builder, block.last_instruction_addr); + codegen::gen_profiler_stat_increment(ctx.builder, stat::DIRECT_EXIT); + ctx.builder.br(ctx.exit_label); + }, + BasicBlockType::AbsoluteEip => { + // Check if we can stay in this module, if not exit + codegen::gen_get_eip(ctx.builder); + ctx.builder.const_i32(wasm_table_index.to_u16() as i32); + ctx.builder.const_i32(state_flags.to_u32() as i32); + ctx.builder.call_fn3_ret("jit_find_cache_entry_in_page"); + ctx.builder.tee_local(target_block); + ctx.builder.const_i32(0); + ctx.builder.ge_i32(); + // TODO: Could make this unconditional by including exit_label in the main br_table + ctx.builder.br_if(main_loop_label); + + codegen::gen_debug_track_jit_exit(ctx.builder, block.last_instruction_addr); + ctx.builder.br(ctx.exit_label); + }, + &BasicBlockType::Normal { + next_block_addr: None, + jump_offset, + jump_offset_is_32, + } => { + if jump_offset_is_32 { + codegen::gen_set_eip_low_bits_and_jump_rel32( + ctx.builder, + block.end_addr as i32 & 0xFFF, + jump_offset, + ); + } + else { + codegen::gen_set_eip_low_bits( + ctx.builder, + block.end_addr as i32 & 0xFFF, + ); + codegen::gen_jmp_rel16(ctx.builder, jump_offset as u16); + } + + codegen::gen_debug_track_jit_exit(ctx.builder, block.last_instruction_addr); + codegen::gen_profiler_stat_increment(ctx.builder, stat::DIRECT_EXIT); + ctx.builder.br(ctx.exit_label); + }, + &BasicBlockType::Normal { + next_block_addr: Some(next_block_addr), + jump_offset, + jump_offset_is_32, + } => { + // Unconditional jump to next basic block + // - All instructions that don't change eip + // - Unconditional jumps + + if Page::page_of(next_block_addr) != Page::page_of(block.addr) { + if jump_offset_is_32 { + codegen::gen_set_eip_low_bits_and_jump_rel32( + ctx.builder, + block.end_addr as i32 & 0xFFF, + jump_offset, + ); + } + else { + codegen::gen_set_eip_low_bits( + ctx.builder, + block.end_addr as i32 & 0xFFF, + ); + codegen::gen_jmp_rel16(ctx.builder, jump_offset as u16); + } + + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::NORMAL_PAGE_CHANGE, + ); + + codegen::gen_page_switch_check( + ctx, + next_block_addr, + block.last_instruction_addr, + ); + + #[cfg(debug_assertions)] + codegen::gen_fn2_const( + ctx.builder, + "check_page_switch", + block.addr, + next_block_addr, + ); + } + + if next_addr + .as_ref() + .map_or(false, |n| n.contains(&next_block_addr)) + { + // Blocks are consecutive + if next_addr.unwrap().len() > 1 { + let target_index = *index_for_addr.get(&next_block_addr).unwrap(); + if cfg!(feature = "profiler") { + ctx.builder.const_i32(target_index); + ctx.builder.call_fn1("debug_set_dispatcher_target"); + } + ctx.builder.const_i32(target_index); + ctx.builder.set_local(target_block); + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::NORMAL_FALLTHRU_WITH_TARGET_BLOCK, + ); + } + else { + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::NORMAL_FALLTHRU, + ); + } + } + else { + let &(br, target_index) = label_for_addr.get(&next_block_addr).unwrap(); + if let Some(target_index) = target_index { + if cfg!(feature = "profiler") { + ctx.builder.const_i32(target_index); + ctx.builder.call_fn1("debug_set_dispatcher_target"); + } + ctx.builder.const_i32(target_index); + ctx.builder.set_local(target_block); + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::NORMAL_BRANCH_WITH_TARGET_BLOCK, + ); + } + else { + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::NORMAL_BRANCH, + ); + } + ctx.builder.br(br); + } + }, + &BasicBlockType::ConditionalJump { + next_block_addr, + next_block_branch_taken_addr, + condition, + jump_offset, + jump_offset_is_32, + } => { + // Conditional jump to next basic block + // - jnz, jc, loop, jcxz, etc. + + // Generate: + // (1) condition() + // (2) br_if() + // (3) br() + // Except: + // If we need to update eip in case (2), it's replaced by if { update_eip(); br() } + // If case (3) can fall through to the next basic block, the branch is eliminated + // Dispatcher target writes can be generated in either case + // Condition may be inverted if it helps generate a fallthrough instead of the second branch + + codegen::gen_profiler_stat_increment(ctx.builder, stat::CONDITIONAL_JUMP); + + #[derive(PartialEq)] + enum Case { + BranchTaken, + BranchNotTaken, + } + + let mut handle_case = |case: Case, is_first| { + // first case generates condition and *has* to branch away, + // second case branches unconditionally or falls through + + if is_first { + if case == Case::BranchNotTaken { + codegen::gen_condition_fn_negated(ctx, condition); + } + else { + codegen::gen_condition_fn(ctx, condition); + } + } + + let next_block_addr = if case == Case::BranchTaken { + next_block_branch_taken_addr + } + else { + next_block_addr + }; + + if let Some(next_block_addr) = next_block_addr { + if Page::page_of(next_block_addr) != Page::page_of(block.addr) { + dbg_assert!(case == Case::BranchTaken); // currently not possible in other case + if is_first { + ctx.builder.if_i32(); + } + if jump_offset_is_32 { + codegen::gen_set_eip_low_bits_and_jump_rel32( + ctx.builder, + block.end_addr as i32 & 0xFFF, + jump_offset, + ); + } + else { + codegen::gen_set_eip_low_bits( + ctx.builder, + block.end_addr as i32 & 0xFFF, + ); + codegen::gen_jmp_rel16(ctx.builder, jump_offset as u16); + } + + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::CONDITIONAL_JUMP_PAGE_CHANGE, + ); + codegen::gen_page_switch_check( + ctx, + next_block_addr, + block.last_instruction_addr, + ); + + #[cfg(debug_assertions)] + codegen::gen_fn2_const( + ctx.builder, + "check_page_switch", + block.addr, + next_block_addr, + ); + + if is_first { + ctx.builder.const_i32(1); + ctx.builder.else_(); + ctx.builder.const_i32(0); + ctx.builder.block_end(); + } + } + + if next_addr + .as_ref() + .map_or(false, |n| n.contains(&next_block_addr)) + { + // blocks are consecutive + + // fallthrough, has to be second + dbg_assert!(!is_first); + + if next_addr.as_ref().unwrap().len() > 1 { + let target_index = + *index_for_addr.get(&next_block_addr).unwrap(); + if cfg!(feature = "profiler") { + ctx.builder.const_i32(target_index); + ctx.builder.call_fn1("debug_set_dispatcher_target"); + } + ctx.builder.const_i32(target_index); + ctx.builder.set_local(target_block); + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::CONDITIONAL_JUMP_FALLTHRU_WITH_TARGET_BLOCK, + ); + } + else { + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::CONDITIONAL_JUMP_FALLTHRU, + ); + } + } + else { + let &(br, target_index) = + label_for_addr.get(&next_block_addr).unwrap(); + if let Some(target_index) = target_index { + if cfg!(feature = "profiler") { + // Note: Currently called unconditionally, even if the + // br_if below doesn't branch + ctx.builder.const_i32(target_index); + ctx.builder.call_fn1("debug_set_dispatcher_target"); + } + ctx.builder.const_i32(target_index); + ctx.builder.set_local(target_block); + } + + if is_first { + if cfg!(feature = "profiler") { + ctx.builder.if_void(); + codegen::gen_profiler_stat_increment( + ctx.builder, + if target_index.is_some() { + stat::CONDITIONAL_JUMP_BRANCH_WITH_TARGET_BLOCK + } + else { + stat::CONDITIONAL_JUMP_BRANCH + }, + ); + ctx.builder.br(br); + ctx.builder.block_end(); + } + else { + ctx.builder.br_if(br); + } + } + else { + codegen::gen_profiler_stat_increment( + ctx.builder, + if target_index.is_some() { + stat::CONDITIONAL_JUMP_BRANCH_WITH_TARGET_BLOCK + } + else { + stat::CONDITIONAL_JUMP_BRANCH + }, + ); + ctx.builder.br(br); + } + } + } + else { + // target is outside of this module, update eip and exit + if is_first { + ctx.builder.if_void(); + } + + if case == Case::BranchTaken { + if jump_offset_is_32 { + codegen::gen_set_eip_low_bits_and_jump_rel32( + ctx.builder, + block.end_addr as i32 & 0xFFF, + jump_offset, + ); + } + else { + codegen::gen_set_eip_low_bits( + ctx.builder, + block.end_addr as i32 & 0xFFF, + ); + codegen::gen_jmp_rel16(ctx.builder, jump_offset as u16); + } + } + else { + codegen::gen_set_eip_low_bits( + ctx.builder, + block.end_addr as i32 & 0xFFF, + ); + } + + codegen::gen_debug_track_jit_exit( + ctx.builder, + block.last_instruction_addr, + ); + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::CONDITIONAL_JUMP_EXIT, + ); + ctx.builder.br(ctx.exit_label); + + if is_first { + ctx.builder.block_end(); + } + } + }; + + let branch_taken_is_fallthrough = next_block_branch_taken_addr + .map_or(false, |addr| { + next_addr.as_ref().map_or(false, |n| n.contains(&addr)) + }); + let branch_not_taken_is_fallthrough = next_block_addr + .map_or(false, |addr| { + next_addr.as_ref().map_or(false, |n| n.contains(&addr)) + }); + + if branch_not_taken_is_fallthrough && branch_taken_is_fallthrough { + let next_block_addr = next_block_addr.unwrap(); + let next_block_branch_taken_addr = + next_block_branch_taken_addr.unwrap(); + + dbg_log!( + "Conditional control flow: fallthrough in both cases, page_switch={} next_is_multi={}", + Page::page_of(next_block_branch_taken_addr) + != Page::page_of(block.addr), + next_addr.as_ref().unwrap().len() > 1, + ); + + dbg_assert!( + Page::page_of(next_block_addr) == Page::page_of(block.addr) + ); // currently not possible + + if Page::page_of(next_block_branch_taken_addr) + != Page::page_of(block.addr) + { + codegen::gen_condition_fn(ctx, condition); + ctx.builder.if_void(); + + if jump_offset_is_32 { + codegen::gen_set_eip_low_bits_and_jump_rel32( + ctx.builder, + block.end_addr as i32 & 0xFFF, + jump_offset, + ); + } + else { + codegen::gen_set_eip_low_bits( + ctx.builder, + block.end_addr as i32 & 0xFFF, + ); + codegen::gen_jmp_rel16(ctx.builder, jump_offset as u16); + } + + codegen::gen_profiler_stat_increment( + ctx.builder, + stat::CONDITIONAL_JUMP_PAGE_CHANGE, + ); + codegen::gen_page_switch_check( + ctx, + next_block_branch_taken_addr, + block.last_instruction_addr, + ); + + #[cfg(debug_assertions)] + codegen::gen_fn2_const( + ctx.builder, + "check_page_switch", + block.addr, + next_block_branch_taken_addr, + ); + + dbg_assert!(next_addr.unwrap().len() > 1); + + let target_index_taken = + *index_for_addr.get(&next_block_branch_taken_addr).unwrap(); + let target_index_not_taken = + *index_for_addr.get(&next_block_addr).unwrap(); + + ctx.builder.const_i32(target_index_taken); + ctx.builder.set_local(target_block); + + ctx.builder.else_(); + ctx.builder.const_i32(target_index_not_taken); + ctx.builder.set_local(target_block); + + ctx.builder.block_end(); + } + else if next_addr.unwrap().len() > 1 { + let target_index_taken = + *index_for_addr.get(&next_block_branch_taken_addr).unwrap(); + let target_index_not_taken = + *index_for_addr.get(&next_block_addr).unwrap(); + + codegen::gen_condition_fn(ctx, condition); + ctx.builder.if_i32(); + ctx.builder.const_i32(target_index_taken); + ctx.builder.else_(); + ctx.builder.const_i32(target_index_not_taken); + ctx.builder.block_end(); + ctx.builder.set_local(target_block); + } + } + else if branch_taken_is_fallthrough { + handle_case(Case::BranchNotTaken, true); + handle_case(Case::BranchTaken, false); + } + else { + handle_case(Case::BranchTaken, true); + handle_case(Case::BranchNotTaken, false); + } + }, + } + }, + Work::WasmStructure(WasmStructure::Dispatcher(entries)) => { + profiler::stat_increment(stat::COMPILE_DISPATCHER); + + if cfg!(feature = "profiler") { + ctx.builder.get_local(target_block); + ctx.builder.const_i32(index_for_addr.len() as i32); + ctx.builder.call_fn2("check_dispatcher_target"); + } + + if entries.len() > BRTABLE_CUTOFF { + // generate a brtable + codegen::gen_profiler_stat_increment(ctx.builder, stat::DISPATCHER_LARGE); + let mut cases = Vec::new(); + for &addr in &entries { + let &(label, target_index) = label_for_addr.get(&addr).unwrap(); + let &index = index_for_addr.get(&addr).unwrap(); + dbg_assert!(target_index.is_none() || target_index == Some(index)); + while index as usize >= cases.len() { + cases.push(brtable_default); + } + cases[index as usize] = label; + } + ctx.builder.get_local(target_block); + ctx.builder.brtable(brtable_default, &mut cases.iter()); + } + else { + // generate a if target == block.addr then br block.label ... + codegen::gen_profiler_stat_increment(ctx.builder, stat::DISPATCHER_SMALL); + let nexts: HashSet = next_addr + .as_ref() + .map_or(HashSet::new(), |nexts| nexts.iter().copied().collect()); + for &addr in &entries { + if nexts.contains(&addr) { + continue; + } + let index = *index_for_addr.get(&addr).unwrap(); + let &(label, _) = label_for_addr.get(&addr).unwrap(); + ctx.builder.get_local(target_block); + ctx.builder.const_i32(index); + ctx.builder.eq_i32(); + ctx.builder.br_if(label); + } + } + }, + Work::WasmStructure(WasmStructure::Loop(children)) => { + profiler::stat_increment(stat::COMPILE_WASM_LOOP); + + let entries: Vec = children[0].head().collect(); + let label = ctx.builder.loop_void(); + codegen::gen_profiler_stat_increment(ctx.builder, stat::LOOP); + + if entries.len() == 1 { + let addr = entries[0]; + codegen::gen_set_eip_low_bits(ctx.builder, addr as i32 & 0xFFF); + profiler::stat_increment(stat::COMPILE_WITH_LOOP_SAFETY); + codegen::gen_profiler_stat_increment(ctx.builder, stat::LOOP_SAFETY); + if unsafe { JIT_USE_LOOP_SAFETY } { + ctx.builder.get_local(&ctx.instruction_counter); + ctx.builder.const_i32(cpu::LOOP_COUNTER); + ctx.builder.geu_i32(); + if cfg!(feature = "profiler") { + ctx.builder.if_void(); + codegen::gen_debug_track_jit_exit(ctx.builder, addr); + ctx.builder.br(exit_label); + ctx.builder.block_end(); + } + else { + ctx.builder.br_if(exit_label); + } + } + } + + let mut olds = HashMap::new(); + for &target in entries.iter() { + let index = if entries.len() == 1 { + None + } + else { + Some(*index_for_addr.get(&target).unwrap()) + }; + let old = label_for_addr.insert(target, (label, index)); + if let Some(old) = old { + olds.insert(target, old); + } + } + + work.push_front(Work::LoopEnd { + label, + entries, + olds, + }); + for c in children.into_iter().rev() { + work.push_front(Work::WasmStructure(c)); + } + }, + Work::LoopEnd { + label, + entries, + olds, + } => { + for target in entries { + let old = label_for_addr.remove(&target); + dbg_assert!(old.map(|(l, _)| l) == Some(label)); + } + for (target, old) in olds { + let old = label_for_addr.insert(target, old); + dbg_assert!(old.is_none()); + } + + ctx.builder.block_end(); + }, + Work::WasmStructure(WasmStructure::Block(children)) => { + profiler::stat_increment(stat::COMPILE_WASM_BLOCK); + + let targets = next_addr.clone().unwrap(); + let label = ctx.builder.block_void(); + let mut olds = HashMap::new(); + for &target in targets.iter() { + let index = if targets.len() == 1 { + None + } + else { + Some(*index_for_addr.get(&target).unwrap()) + }; + let old = label_for_addr.insert(target, (label, index)); + if let Some(old) = old { + olds.insert(target, old); + } + } + + work.push_front(Work::BlockEnd { + label, + targets, + olds, + }); + for c in children.into_iter().rev() { + work.push_front(Work::WasmStructure(c)); + } + }, + Work::BlockEnd { + label, + targets, + olds, + } => { + for target in targets { + let old = label_for_addr.remove(&target); + dbg_assert!(old.map(|(l, _)| l) == Some(label)); + } + for (target, old) in olds { + let old = label_for_addr.insert(target, old); + dbg_assert!(old.is_none()); + } + + ctx.builder.block_end(); + }, + } + } + + dbg_assert!(label_for_addr.is_empty()); + + { + ctx.builder.block_end(); // default case for the brtable + ctx.builder.unreachable(); + } + { + ctx.builder.block_end(); // main loop + } + { + // exit-with-fault case + ctx.builder.block_end(); + codegen::gen_move_registers_from_locals_to_memory(ctx); + codegen::gen_fn0_const(ctx.builder, "trigger_fault_end_jit"); + codegen::gen_update_instruction_counter(ctx); + ctx.builder.return_(); + } + { + // exit + ctx.builder.block_end(); + codegen::gen_move_registers_from_locals_to_memory(ctx); + codegen::gen_update_instruction_counter(ctx); + } + + for local in ctx.register_locals.drain(..) { + ctx.builder.free_local(local); + } + ctx.builder + .free_local(ctx.instruction_counter.unsafe_clone()); + + ctx.builder.finish(); + + let entries = Vec::from_iter(entry_blocks.iter().map(|addr| { + let block = basic_blocks.get(&addr).unwrap(); + let index = *index_for_addr.get(&addr).unwrap(); + + profiler::stat_increment(stat::COMPILE_ENTRY_POINT); + + dbg_assert!(block.addr < block.end_addr); + // Note: We also insert blocks that weren't originally marked as entries here + // This doesn't have any downside, besides making the hash table slightly larger + + let initial_state = index.safe_to_u16(); + (block.addr, initial_state) + })); + + for b in basic_blocks.values() { + if b.is_entry_block { + dbg_assert!(entries.iter().find(|(addr, _)| *addr == b.addr).is_some()); + } + } + + return entries; +} + +fn jit_generate_basic_block(ctx: &mut JitContext, block: &BasicBlock) { + let needs_eip_updated = match block.ty { + BasicBlockType::Exit => true, + _ => false, + }; + + profiler::stat_increment(stat::COMPILE_BASIC_BLOCK); + + let start_addr = block.addr; + let last_instruction_addr = block.last_instruction_addr; + let stop_addr = block.end_addr; + + // First iteration of do-while assumes the caller confirms this condition + dbg_assert!(!is_near_end_of_page(start_addr)); + + if cfg!(feature = "profiler") { + ctx.builder.const_i32(start_addr as i32); + ctx.builder.call_fn1("enter_basic_block"); + } + + ctx.builder.get_local(&ctx.instruction_counter); + ctx.builder.const_i32(block.number_of_instructions as i32); + ctx.builder.add_i32(); + ctx.builder.set_local(&ctx.instruction_counter); + + ctx.cpu.eip = start_addr; + ctx.current_instruction = Instruction::Other; + ctx.previous_instruction = Instruction::Other; + + loop { + let mut instruction = 0; + if cfg!(feature = "profiler") { + instruction = memory::read32s(ctx.cpu.eip) as u32; + opstats::gen_opstats(ctx.builder, instruction); + opstats::record_opstat_compiled(instruction); + } + + if ctx.cpu.eip == last_instruction_addr { + // Before the last instruction: + // - Set eip to *after* the instruction + // - Set previous_eip to *before* the instruction + if needs_eip_updated { + codegen::gen_set_previous_eip_offset_from_eip_with_low_bits( + ctx.builder, + last_instruction_addr as i32 & 0xFFF, + ); + codegen::gen_set_eip_low_bits(ctx.builder, stop_addr as i32 & 0xFFF); + } + } + + let wasm_length_before = ctx.builder.instruction_body_length(); + + ctx.start_of_current_instruction = ctx.cpu.eip; + let start_eip = ctx.cpu.eip; + let mut instruction_flags = 0; + jit_instructions::jit_instruction(ctx, &mut instruction_flags); + let end_eip = ctx.cpu.eip; + + let instruction_length = end_eip - start_eip; + let was_block_boundary = instruction_flags & JIT_INSTR_BLOCK_BOUNDARY_FLAG != 0; + + let wasm_length = ctx.builder.instruction_body_length() - wasm_length_before; + opstats::record_opstat_size_wasm(instruction, wasm_length as u64); + + dbg_assert!((end_eip == stop_addr) == (start_eip == last_instruction_addr)); + dbg_assert!(instruction_length < MAX_INSTRUCTION_LENGTH); + + let end_addr = ctx.cpu.eip; + + if end_addr == stop_addr { + // no page was crossed + dbg_assert!(Page::page_of(end_addr) == Page::page_of(start_addr)); + break; + } + + if was_block_boundary || is_near_end_of_page(end_addr) || end_addr > stop_addr { + dbg_log!( + "Overlapping basic blocks start={:x} expected_end={:x} end={:x} was_block_boundary={} near_end_of_page={}", + start_addr, + stop_addr, + end_addr, + was_block_boundary, + is_near_end_of_page(end_addr) + ); + dbg_assert!(false); + break; + } + + ctx.previous_instruction = mem::replace(&mut ctx.current_instruction, Instruction::Other); + } +} + +pub fn jit_increase_hotness_and_maybe_compile( + virt_address: i32, + phys_address: u32, + cs_offset: u32, + state_flags: CachedStateFlags, + heat: u32, +) { + let ctx = get_jit_state(); + let page = Page::page_of(phys_address); + let (hotness, entry_points) = ctx.entry_points.entry(page).or_insert_with(|| { + cpu::tlb_set_has_code(page, true); + profiler::stat_increment(stat::RUN_INTERPRETED_NEW_PAGE); + (0, HashSet::new()) + }); + + if !is_near_end_of_page(phys_address) { + entry_points.insert(phys_address as u16 & 0xFFF); + } + + *hotness += heat; + if *hotness >= JIT_THRESHOLD { + if ctx.compiling.is_some() { + return; + } + // only try generating if we're in the correct address space + if cpu::translate_address_read_no_side_effects(virt_address) == Ok(phys_address) { + *hotness = 0; + jit_analyze_and_generate(ctx, virt_address, phys_address, cs_offset, state_flags) + } + else { + profiler::stat_increment(stat::COMPILE_WRONG_ADDRESS_SPACE); + } + }; +} + +fn free_wasm_table_index(ctx: &mut JitState, wasm_table_index: WasmTableIndex) { + if CHECK_JIT_STATE_INVARIANTS { + dbg_assert!(!ctx.wasm_table_index_free_list.contains(&wasm_table_index)); + + match &ctx.compiling { + Some((wasm_table_index_compiling, _)) => { + dbg_assert!( + *wasm_table_index_compiling != wasm_table_index, + "Attempt to free wasm table index that is currently being compiled" + ); + }, + _ => {}, + } + + dbg_assert!( + !ctx.pages + .values() + .any(|info| info.wasm_table_index == wasm_table_index) + ); + + dbg_assert!( + !ctx.pages + .values() + .any(|info| info.hidden_wasm_table_indices.contains(&wasm_table_index)) + ); + + for i in 0..unsafe { cpu::valid_tlb_entries_count } { + let page = unsafe { cpu::valid_tlb_entries[i as usize] }; + unsafe { + match cpu::tlb_code[page as usize] { + None => {}, + Some(c) => { + let c = c.as_ref(); + dbg_assert!(c.wasm_table_index != wasm_table_index); + }, + } + } + } + } + + ctx.wasm_table_index_free_list.push(wasm_table_index); + + // It is not strictly necessary to clear the function, but it will fail more predictably if we + // accidentally use the function and may garbage collect unused modules earlier + jit_clear_func(wasm_table_index); +} + +/// Register a write in this page: Delete all present code +pub fn jit_dirty_page(ctx: &mut JitState, page: Page) { + let mut did_have_code = false; + + if let Some(PageInfo { + wasm_table_index, + hidden_wasm_table_indices, + state_flags: _, + entry_points: _, + }) = ctx.pages.remove(&page) + { + profiler::stat_increment(stat::INVALIDATE_PAGE_HAD_CODE); + did_have_code = true; + + free(ctx, wasm_table_index); + for wasm_table_index in hidden_wasm_table_indices { + free(ctx, wasm_table_index); + } + + fn free(ctx: &mut JitState, wasm_table_index: WasmTableIndex) { + for i in 0..unsafe { cpu::valid_tlb_entries_count } { + let page = unsafe { cpu::valid_tlb_entries[i as usize] }; + let entry = unsafe { cpu::tlb_data[page as usize] }; + if 0 != entry { + let tlb_physical_page = Page::of_u32( + (entry as u32 >> 12 ^ page as u32) - (unsafe { memory::mem8 } as u32 >> 12), + ); + match unsafe { cpu::tlb_code[page as usize] } { + None => {}, + Some(c) => unsafe { + let w = c.as_ref().wasm_table_index; + if wasm_table_index == w { + drop(Box::from_raw(c.as_ptr())); + cpu::tlb_code[page as usize] = None; + if !ctx.entry_points.contains_key(&tlb_physical_page) { + cpu::tlb_data[page as usize] &= !cpu::TLB_HAS_CODE; // XXX + } + } + }, + } + } + } + + ctx.pages.retain( + | + _, + &mut PageInfo { + wasm_table_index: w, + .. + }, + | w != wasm_table_index, + ); + + for info in ctx.pages.values_mut() { + info.hidden_wasm_table_indices + .retain(|&w| w != wasm_table_index) + } + + free_wasm_table_index(ctx, wasm_table_index); + } + } + + match ctx.entry_points.remove(&page) { + None => {}, + Some(_) => { + profiler::stat_increment(stat::INVALIDATE_PAGE_HAD_ENTRY_POINTS); + did_have_code = true; + + match &ctx.compiling { + Some((index, CompilingPageState::Compiling { pages })) => { + if pages.contains_key(&page) { + ctx.compiling = Some((*index, CompilingPageState::CompilingWritten)); + } + }, + _ => {}, + } + }, + } + + match &ctx.compiling { + Some((_, CompilingPageState::Compiling { pages })) => { + dbg_assert!(!pages.contains_key(&page)); + }, + _ => {}, + } + + check_jit_state_invariants(ctx); + + dbg_assert!(!jit_page_has_code_ctx(ctx, page)); + + if did_have_code { + cpu::tlb_set_has_code(page, false); + } + + if !did_have_code { + profiler::stat_increment(stat::DIRTY_PAGE_DID_NOT_HAVE_CODE); + } +} + +#[no_mangle] +pub fn jit_dirty_cache(start_addr: u32, end_addr: u32) { + dbg_assert!(start_addr < end_addr); + + let start_page = Page::page_of(start_addr); + let end_page = Page::page_of(end_addr - 1); + + for page in start_page.to_u32()..end_page.to_u32() + 1 { + jit_dirty_page(get_jit_state(), Page::page_of(page << 12)); + } +} + +/// dirty pages in the range of start_addr and end_addr, which must span at most two pages +pub fn jit_dirty_cache_small(start_addr: u32, end_addr: u32) { + dbg_assert!(start_addr < end_addr); + + let start_page = Page::page_of(start_addr); + let end_page = Page::page_of(end_addr - 1); + + let ctx = get_jit_state(); + jit_dirty_page(ctx, start_page); + + // Note: This can't happen when paging is enabled, as writes across + // boundaries are split up on two pages + if start_page != end_page { + dbg_assert!(start_page.to_u32() + 1 == end_page.to_u32()); + jit_dirty_page(ctx, end_page); + } +} + +#[no_mangle] +pub fn jit_clear_cache_js() { jit_clear_cache(get_jit_state()) } + +pub fn jit_clear_cache(ctx: &mut JitState) { + let mut pages_with_code = HashSet::new(); + + for &p in ctx.entry_points.keys() { + pages_with_code.insert(p); + } + for &p in ctx.pages.keys() { + pages_with_code.insert(p); + } + + for page in pages_with_code { + jit_dirty_page(ctx, page); + } +} + +pub fn jit_page_has_code(page: Page) -> bool { jit_page_has_code_ctx(get_jit_state(), page) } + +pub fn jit_page_has_code_ctx(ctx: &mut JitState, page: Page) -> bool { + ctx.pages.contains_key(&page) || ctx.entry_points.contains_key(&page) +} + +#[no_mangle] +pub fn jit_get_wasm_table_index_free_list_count() -> u32 { + if cfg!(feature = "profiler") { + get_jit_state().wasm_table_index_free_list.len() as u32 + } + else { + 0 + } +} +#[no_mangle] +pub fn jit_get_cache_size() -> u32 { + if cfg!(feature = "profiler") { + get_jit_state() + .pages + .values() + .map(|p| p.entry_points.len() as u32) + .sum() + } + else { + 0 + } +} + +#[cfg(feature = "profiler")] +pub fn check_missed_entry_points(phys_address: u32, state_flags: CachedStateFlags) { + let ctx = get_jit_state(); + + if let Some(infos) = ctx.pages.get(&Page::page_of(phys_address)) { + if infos.state_flags != state_flags { + return; + } + + let last_jump_type = unsafe { cpu::debug_last_jump.name() }; + let last_jump_addr = unsafe { cpu::debug_last_jump.phys_address() }.unwrap_or(0); + let last_jump_opcode = + if last_jump_addr != 0 { memory::read32s(last_jump_addr) } else { 0 }; + + let opcode = memory::read32s(phys_address); + dbg_log!( + "Compiled exists, but no entry point, \ + phys_addr={:x} opcode={:02x} {:02x} {:02x} {:02x}. \ + Last jump at {:x} ({}) opcode={:02x} {:02x} {:02x} {:02x}", + phys_address, + opcode & 0xFF, + opcode >> 8 & 0xFF, + opcode >> 16 & 0xFF, + opcode >> 16 & 0xFF, + last_jump_addr, + last_jump_type, + last_jump_opcode & 0xFF, + last_jump_opcode >> 8 & 0xFF, + last_jump_opcode >> 16 & 0xFF, + last_jump_opcode >> 16 & 0xFF, + ); + } +} + +#[no_mangle] +#[cfg(feature = "profiler")] +pub fn debug_set_dispatcher_target(_target_index: i32) { + //dbg_log!("About to call dispatcher target_index={}", target_index); +} + +#[no_mangle] +#[cfg(feature = "profiler")] +pub fn check_dispatcher_target(target_index: i32, max: i32) { + //dbg_log!("Dispatcher called target={}", target_index); + dbg_assert!(target_index >= 0); + dbg_assert!(target_index < max); +} + +#[no_mangle] +#[cfg(feature = "profiler")] +pub fn enter_basic_block(phys_eip: u32) { + let eip = + unsafe { cpu::translate_address_read(*global_pointers::instruction_pointer).unwrap() }; + if Page::page_of(eip) != Page::page_of(phys_eip) { + dbg_log!( + "enter basic block failed block=0x{:x} actual eip=0x{:x}", + phys_eip, + eip + ); + panic!(); + } +} + +#[no_mangle] +pub unsafe fn set_jit_config(index: u32, value: u32) { + match index { + 0 => MAX_PAGES = value, + 1 => JIT_USE_LOOP_SAFETY = value != 0, + 2 => MAX_EXTRA_BASIC_BLOCKS = value, + _ => dbg_assert!(false), + } +} + +#[no_mangle] +pub unsafe fn get_jit_config(index: u32) -> u32 { + match index { + 0 => MAX_PAGES as u32, + 1 => JIT_USE_LOOP_SAFETY as u32, + 2 => MAX_EXTRA_BASIC_BLOCKS as u32, + _ => 0, + } +} diff --git a/src/rust/jit_instructions.rs b/src/rust/jit_instructions.rs new file mode 100644 index 0000000..f6d2bca --- /dev/null +++ b/src/rust/jit_instructions.rs @@ -0,0 +1,7791 @@ +#![allow(non_snake_case)] + +use codegen; +use codegen::{BitSize, ConditionNegate}; +use cpu::cpu::{ + FLAGS_ALL, FLAGS_DEFAULT, FLAGS_MASK, FLAG_ADJUST, FLAG_CARRY, FLAG_DIRECTION, FLAG_INTERRUPT, + FLAG_IOPL, FLAG_OVERFLOW, FLAG_SUB, FLAG_VM, FLAG_ZERO, OPSIZE_8, OPSIZE_16, OPSIZE_32, +}; +use cpu::global_pointers; +use jit::{Instruction, InstructionOperand, InstructionOperandDest, JitContext}; +use modrm::{jit_add_seg_offset, jit_add_seg_offset_no_override, ModrmByte}; +use prefix::SEG_PREFIX_ZERO; +use prefix::{PREFIX_66, PREFIX_67, PREFIX_F2, PREFIX_F3}; +use regs; +use regs::{AX, BP, BX, CX, DI, DX, SI, SP}; +use regs::{CS, DS, ES, FS, GS, SS}; +use regs::{EAX, EBP, EBX, ECX, EDI, EDX, ESI, ESP}; +use wasmgen::wasm_builder::{WasmBuilder, WasmLocal}; + +enum LocalOrImmediate<'a> { + WasmLocal(&'a WasmLocal), + Immediate(i32), +} + +impl<'a> LocalOrImmediate<'a> { + pub fn gen_get(&self, builder: &mut WasmBuilder) { + match self { + LocalOrImmediate::WasmLocal(l) => builder.get_local(l), + LocalOrImmediate::Immediate(i) => builder.const_i32(*i), + } + } + pub fn gen_get_mask255(&self, builder: &mut WasmBuilder) { + match self { + LocalOrImmediate::WasmLocal(l) => { + builder.get_local(l); + builder.const_i32(0xFF); + builder.and_i32() + }, + LocalOrImmediate::Immediate(i) => builder.const_i32(*i & 0xFF), + } + } + pub fn eq_local(&self, other_local: &WasmLocal) -> bool { + match self { + &LocalOrImmediate::WasmLocal(local) => local == other_local, + LocalOrImmediate::Immediate(_) => false, + } + } + pub fn is_zero(&self) -> bool { + match self { + LocalOrImmediate::Immediate(0) => true, + _ => false, + } + } + + fn to_instruction_operand(&self, ctx: &mut JitContext) -> InstructionOperand { + match self { + &LocalOrImmediate::WasmLocal(source) => { + local_to_instruction_operand(ctx, source).into() + }, + &LocalOrImmediate::Immediate(i) => InstructionOperand::Immediate(i), + } + } +} + +fn local_to_instruction_operand(ctx: &mut JitContext, local: &WasmLocal) -> InstructionOperandDest { + if ctx.register_locals.iter().any(|l| l == local) { + // safe because register locals are alive for the duration of the entire function + InstructionOperandDest::WasmLocal(local.unsafe_clone()) + } + else { + InstructionOperandDest::Other + } +} + +pub fn jit_instruction(ctx: &mut JitContext, instr_flags: &mut u32) { + ctx.cpu.prefixes = 0; + ctx.start_of_current_instruction = ctx.cpu.eip; + ::gen::jit::jit( + ctx.cpu.read_imm8() as u32 | (ctx.cpu.osize_32() as u32) << 8, + ctx, + instr_flags, + ); +} + +pub fn jit_handle_prefix(ctx: &mut JitContext, instr_flags: &mut u32) { + ::gen::jit::jit( + ctx.cpu.read_imm8() as u32 | (ctx.cpu.osize_32() as u32) << 8, + ctx, + instr_flags, + ); +} + +pub fn jit_handle_segment_prefix(segment: u32, ctx: &mut JitContext, instr_flags: &mut u32) { + dbg_assert!(segment <= 5); + ctx.cpu.prefixes |= segment + 1; + jit_handle_prefix(ctx, instr_flags) +} + +pub fn instr16_0F_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + ::gen::jit0f::jit(ctx.cpu.read_imm8() as u32, ctx, instr_flags) +} +pub fn instr32_0F_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + ::gen::jit0f::jit(ctx.cpu.read_imm8() as u32 | 0x100, ctx, instr_flags) +} +pub fn instr_26_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + jit_handle_segment_prefix(ES, ctx, instr_flags) +} +pub fn instr_2E_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + jit_handle_segment_prefix(CS, ctx, instr_flags) +} +pub fn instr_36_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + jit_handle_segment_prefix(SS, ctx, instr_flags) +} +pub fn instr_3E_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + jit_handle_segment_prefix(DS, ctx, instr_flags) +} + +pub fn instr_64_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + jit_handle_segment_prefix(FS, ctx, instr_flags) +} +pub fn instr_65_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + jit_handle_segment_prefix(GS, ctx, instr_flags) +} + +pub fn instr_66_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + ctx.cpu.prefixes |= PREFIX_66; + jit_handle_prefix(ctx, instr_flags) +} +pub fn instr_67_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + ctx.cpu.prefixes |= PREFIX_67; + jit_handle_prefix(ctx, instr_flags) +} +pub fn instr_F0_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + // lock: Ignore + jit_handle_prefix(ctx, instr_flags) +} +pub fn instr_F2_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + ctx.cpu.prefixes |= PREFIX_F2; + jit_handle_prefix(ctx, instr_flags) +} +pub fn instr_F3_jit(ctx: &mut JitContext, instr_flags: &mut u32) { + ctx.cpu.prefixes |= PREFIX_F3; + jit_handle_prefix(ctx, instr_flags) +} + +fn sse_read_f32_xmm_mem(ctx: &mut JitContext, name: &str, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.reinterpret_i32_as_f32(); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn2_f32_i32(name); +} +fn sse_read_f32_xmm_xmm(ctx: &mut JitContext, name: &str, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32); + ctx.builder.load_aligned_f32(0); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2_f32_i32(name); +} + +fn sse_read64_xmm_mem(ctx: &mut JitContext, name: &str, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn2_i64_i32(name); +} +fn sse_read64_xmm_xmm(ctx: &mut JitContext, name: &str, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32); + ctx.builder.load_aligned_i64(0); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2_i64_i32(name); +} + +fn sse_read128_xmm_mem(ctx: &mut JitContext, name: &str, modrm_byte: ModrmByte, r: u32) { + let dest = global_pointers::sse_scratch_register as u32; + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, dest); + ctx.builder.const_i32(dest as i32); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn2(name); +} +fn sse_read128_xmm_mem_imm( + ctx: &mut JitContext, + name: &str, + modrm_byte: ModrmByte, + r: u32, + imm: u32, +) { + let dest = global_pointers::sse_scratch_register as u32; + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, dest); + ctx.builder.const_i32(dest as i32); + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn3(name); +} +fn sse_read128_xmm_xmm(ctx: &mut JitContext, name: &str, r1: u32, r2: u32) { + // Make a copy to avoid aliasing problems: Called function expects a reg128, which must not + // alias with memory + codegen::gen_read_reg_xmm128_into_scratch(ctx, r1); + let dest = global_pointers::sse_scratch_register; + ctx.builder.const_i32(dest as i32); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2(name); +} +fn sse_read128_xmm_xmm_imm(ctx: &mut JitContext, name: &str, r1: u32, r2: u32, imm: u32) { + // Make a copy to avoid aliasing problems: Called function expects a reg128, which must not + // alias with memory + codegen::gen_read_reg_xmm128_into_scratch(ctx, r1); + let dest = global_pointers::sse_scratch_register; + ctx.builder.const_i32(dest as i32); + ctx.builder.const_i32(r2 as i32); + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn3(name); +} +fn sse_mov_xmm_xmm(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r2) as i32); + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32); + ctx.builder.load_aligned_i64(0); + ctx.builder.store_aligned_i64(0); + + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r2) as i32 + 8); + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32 + 8); + ctx.builder.load_aligned_i64(0); + ctx.builder.store_aligned_i64(0); +} + +fn mmx_read64_mm_mem32(ctx: &mut JitContext, name: &str, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn2(name) +} +fn mmx_read64_mm_mm32(ctx: &mut JitContext, name: &str, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_mmx_offset(r1) as i32); + ctx.builder.load_aligned_i32(0); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2(name); +} +fn mmx_read64_mm_mem(ctx: &mut JitContext, name: &str, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn2_i64_i32(name) +} +fn mmx_read64_mm_mm(ctx: &mut JitContext, name: &str, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_mmx_offset(r1) as i32); + ctx.builder.load_aligned_i64(0); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2_i64_i32(name); +} + +fn push16_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg16(ctx, r); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &value_local); + ctx.builder.free_local(value_local); +} +fn push32_reg_jit(ctx: &mut JitContext, r: u32) { + let reg = ctx.reg(r); + codegen::gen_push32(ctx, ®); +} +fn push16_imm_jit(ctx: &mut JitContext, imm: u32) { + ctx.builder.const_i32(imm as i32); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &value_local); + ctx.builder.free_local(value_local); +} +fn push32_imm_jit(ctx: &mut JitContext, imm: u32) { + ctx.builder.const_i32(imm as i32); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push32(ctx, &value_local); + ctx.builder.free_local(value_local); +} +fn push16_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &value_local); + ctx.builder.free_local(value_local); +} +fn push32_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push32(ctx, &value_local); + ctx.builder.free_local(value_local); +} + +fn pop16_reg_jit(ctx: &mut JitContext, reg: u32) { + codegen::gen_pop16(ctx); + codegen::gen_set_reg16_unmasked(ctx, reg); +} + +fn pop32_reg_jit(ctx: &mut JitContext, reg: u32) { + codegen::gen_pop32s(ctx); + codegen::gen_set_reg32(ctx, reg); +} + +fn group_arith_al_imm8( + ctx: &mut JitContext, + op: &dyn Fn(&mut JitContext, &WasmLocal, &LocalOrImmediate), + imm8: u32, +) { + op( + ctx, + &ctx.reg(regs::EAX), + &LocalOrImmediate::Immediate(imm8 as i32), + ); + codegen::gen_set_reg8_unmasked(ctx, regs::EAX); +} + +fn group_arith_ax_imm16(ctx: &mut JitContext, op: &str, imm16: u32) { + codegen::gen_get_reg16(ctx, regs::AX); + ctx.builder.const_i32(imm16 as i32); + ctx.builder.call_fn2_ret(op); + codegen::gen_set_reg16(ctx, regs::AX); +} + +fn group_arith_eax_imm32( + ctx: &mut JitContext, + op: &dyn Fn(&mut JitContext, &WasmLocal, &LocalOrImmediate), + imm32: u32, +) { + op( + ctx, + &ctx.reg(regs::EAX), + &LocalOrImmediate::Immediate(imm32 as i32), + ); +} + +macro_rules! define_instruction_read8( + ($fn:expr, $name_mem:ident, $name_reg:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read8(ctx, modrm_byte); + let dest_operand = ctx.builder.set_new_local(); + let source_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r); + $fn(ctx, &dest_operand, &LocalOrImmediate::WasmLocal(&source_operand)); + ctx.builder.free_local(dest_operand); + codegen::gen_free_reg8_or_alias(ctx, r, source_operand); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + let dest_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r1); + let source_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r2); + $fn(ctx, &dest_operand, &LocalOrImmediate::WasmLocal(&source_operand)); + codegen::gen_free_reg8_or_alias(ctx, r1, dest_operand); + codegen::gen_free_reg8_or_alias(ctx, r2, source_operand); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, $imm:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_safe_read8(ctx, modrm_byte); + let dest_operand = ctx.builder.set_new_local(); + let imm = mask_imm!(imm, $imm); + $fn(ctx, &dest_operand, &LocalOrImmediate::Immediate(imm as i32)); + ctx.builder.free_local(dest_operand); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, imm: u32) { + let imm = mask_imm!(imm, $imm); + let dest_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r1); + $fn(ctx, &dest_operand, &LocalOrImmediate::Immediate(imm as i32)); + codegen::gen_free_reg8_or_alias(ctx, r1, dest_operand); + } + ); +); + +macro_rules! define_instruction_read16( + ($fn:expr, $name_mem:ident, $name_reg:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + let dest_operand = ctx.builder.set_new_local(); + $fn( + ctx, + &dest_operand, + &LocalOrImmediate::WasmLocal(&ctx.reg(r)), + ); + ctx.builder.free_local(dest_operand); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + $fn( + ctx, + &ctx.reg(r1), + &LocalOrImmediate::WasmLocal(&ctx.reg(r2)) + ); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, $imm:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + let dest_operand = ctx.builder.set_new_local(); + let imm = mask_imm!(imm, $imm); + $fn( + ctx, + &dest_operand, + &LocalOrImmediate::Immediate(imm as i32), + ); + ctx.builder.free_local(dest_operand); + } + + pub fn $name_reg(ctx: &mut JitContext, r: u32, imm: u32) { + let imm = mask_imm!(imm, $imm); + $fn( + ctx, + &ctx.reg(r), + &LocalOrImmediate::Immediate(imm as i32), + ); + } + ); +); + +macro_rules! define_instruction_read32( + ($fn:expr, $name_mem:ident, $name_reg:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + let dest_operand = ctx.builder.set_new_local(); + $fn( + ctx, + &dest_operand, + &LocalOrImmediate::WasmLocal(&ctx.reg(r)), + ); + ctx.builder.free_local(dest_operand); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + $fn( + ctx, + &ctx.reg(r1), + &LocalOrImmediate::WasmLocal(&ctx.reg(r2)) + ); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, $imm:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + let dest_operand = ctx.builder.set_new_local(); + let imm = mask_imm!(imm, $imm); + $fn( + ctx, + &dest_operand, + &LocalOrImmediate::Immediate(imm as i32), + ); + ctx.builder.free_local(dest_operand); + } + + pub fn $name_reg(ctx: &mut JitContext, r: u32, imm: u32) { + let imm = mask_imm!(imm, $imm); + $fn( + ctx, + &ctx.reg(r), + &LocalOrImmediate::Immediate(imm as i32), + ); + } + ); +); + +macro_rules! define_instruction_write_reg8( + ($fn:expr, $name_mem:ident, $name_reg:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read8(ctx, modrm_byte); + let source_operand = ctx.builder.set_new_local(); + let dest_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r); + $fn(ctx, &dest_operand, &LocalOrImmediate::WasmLocal(&source_operand)); + codegen::gen_set_reg8_unmasked(ctx, r); + ctx.builder.free_local(source_operand); + codegen::gen_free_reg8_or_alias(ctx, r, dest_operand); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + let source_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r1); + let dest_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r2); + $fn(ctx, &dest_operand, &LocalOrImmediate::WasmLocal(&source_operand)); + codegen::gen_set_reg8_unmasked(ctx, r2); + codegen::gen_free_reg8_or_alias(ctx, r1, source_operand); + codegen::gen_free_reg8_or_alias(ctx, r2, dest_operand); + } + ) +); + +macro_rules! define_instruction_write_reg16( + ($fn:expr, $name_mem:ident, $name_reg:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_get_reg16(ctx, r); + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + ctx.builder.call_fn2_ret($fn); + codegen::gen_set_reg16(ctx, r); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r2); + codegen::gen_get_reg16(ctx, r1); + ctx.builder.call_fn2_ret($fn); + codegen::gen_set_reg16(ctx, r2); + } + ) +); + +macro_rules! define_instruction_write_reg32( + ($fn:expr, $name_mem:ident, $name_reg:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + let source_operand = ctx.builder.set_new_local(); + $fn( + ctx, + &ctx.reg(r), + &LocalOrImmediate::WasmLocal(&source_operand), + ); + ctx.builder.free_local(source_operand); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + $fn( + ctx, + &ctx.reg(r2), + &LocalOrImmediate::WasmLocal(&ctx.reg(r1)), + ); + } + ); +); + +macro_rules! mask_imm( + ($imm:expr, imm8_5bits) => { $imm & 31 }; + ($imm:expr, imm8) => { $imm }; + ($imm:expr, imm8s) => { $imm }; + ($imm:expr, imm8s_16bits) => { $imm & 0xFFFF }; + ($imm:expr, imm16) => { $imm }; + ($imm:expr, imm32) => { $imm }; +); + +macro_rules! define_instruction_read_write_mem8( + ($fn:expr, $name_mem:ident, $name_reg:ident, reg) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::BYTE, &addr, &|ref mut ctx| { + let dest_operand = ctx.builder.set_new_local(); + let source_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r); + $fn(ctx, &dest_operand, &LocalOrImmediate::WasmLocal(&source_operand)); + codegen::gen_free_reg8_or_alias(ctx, r, source_operand); + ctx.builder.free_local(dest_operand); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + let source_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r2); + let dest_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r1); + $fn(ctx, &dest_operand, &LocalOrImmediate::WasmLocal(&source_operand)); + codegen::gen_set_reg8_unmasked(ctx, r1); + codegen::gen_free_reg8_or_alias(ctx, r2, source_operand); + codegen::gen_free_reg8_or_alias(ctx, r1, dest_operand); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, constant_one) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::BYTE, &addr, &|ref mut ctx| { + ctx.builder.const_i32(1); + ctx.builder.call_fn2_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32) { + codegen::gen_get_reg8(ctx, r1); + ctx.builder.const_i32(1); + ctx.builder.call_fn2_ret($fn); + codegen::gen_set_reg8(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, cl) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::BYTE, &addr, &|ref mut ctx| { + codegen::gen_get_reg8(ctx, regs::CL); + ctx.builder.const_i32(31); + ctx.builder.and_i32(); + ctx.builder.call_fn2_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32) { + codegen::gen_get_reg8(ctx, r1); + codegen::gen_get_reg8(ctx, regs::CL); + ctx.builder.const_i32(31); + ctx.builder.and_i32(); + ctx.builder.call_fn2_ret($fn); + codegen::gen_set_reg8(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, none) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::BYTE, &addr, &|ref mut ctx| { + ctx.builder.call_fn1_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32) { + codegen::gen_get_reg8(ctx, r1); + ctx.builder.call_fn1_ret($fn); + codegen::gen_set_reg8(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, ximm8) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::BYTE, &addr, &|ref mut ctx| { + let dest_operand = ctx.builder.set_new_local(); + $fn(ctx, &dest_operand, &LocalOrImmediate::Immediate(imm as i32)); + ctx.builder.free_local(dest_operand); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, imm: u32) { + let dest_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r1); + $fn(ctx, &dest_operand, &LocalOrImmediate::Immediate(imm as i32)); + codegen::gen_set_reg8_unmasked(ctx, r1); + codegen::gen_free_reg8_or_alias(ctx, r1, dest_operand); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, $imm:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + let imm = mask_imm!(imm, $imm) as i32; + codegen::gen_safe_read_write(ctx, BitSize::BYTE, &addr, &|ref mut ctx| { + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn2_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, imm: u32) { + let imm = mask_imm!(imm, $imm); + codegen::gen_get_reg8(ctx, r1); + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn2_ret($fn); + codegen::gen_set_reg8(ctx, r1); + } + ); +); + +macro_rules! define_instruction_read_write_mem16( + ($fn:expr, $name_mem:ident, $name_reg:ident, reg) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::WORD, &addr, &|ref mut ctx| { + codegen::gen_get_reg16(ctx, r); + ctx.builder.call_fn2_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r1); + codegen::gen_get_reg16(ctx, r2); + ctx.builder.call_fn2_ret($fn); + codegen::gen_set_reg16(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, constant_one) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::WORD, &addr, &|ref mut ctx| { + ctx.builder.const_i32(1); + ctx.builder.call_fn2_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32) { + codegen::gen_get_reg16(ctx, r1); + ctx.builder.const_i32(1); + ctx.builder.call_fn2_ret($fn); + codegen::gen_set_reg16(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, cl) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::WORD, &addr, &|ref mut ctx| { + codegen::gen_get_reg8(ctx, regs::CL); + ctx.builder.const_i32(31); + ctx.builder.and_i32(); + ctx.builder.call_fn2_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32) { + codegen::gen_get_reg16(ctx, r1); + codegen::gen_get_reg8(ctx, regs::CL); + ctx.builder.const_i32(31); + ctx.builder.and_i32(); + ctx.builder.call_fn2_ret($fn); + codegen::gen_set_reg16(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, reg, cl) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::WORD, &addr, &|ref mut ctx| { + codegen::gen_get_reg16(ctx, r); + codegen::gen_get_reg8(ctx, regs::CL); + ctx.builder.const_i32(31); + ctx.builder.and_i32(); + ctx.builder.call_fn3_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r1); + codegen::gen_get_reg16(ctx, r2); + codegen::gen_get_reg8(ctx, regs::CL); + ctx.builder.const_i32(31); + ctx.builder.and_i32(); + ctx.builder.call_fn3_ret($fn); + codegen::gen_set_reg16(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, reg, $imm:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + let imm = mask_imm!(imm, $imm); + codegen::gen_safe_read_write(ctx, BitSize::WORD, &addr, &|ref mut ctx| { + codegen::gen_get_reg16(ctx, r); + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn3_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32, imm: u32) { + let imm = mask_imm!(imm, $imm); + codegen::gen_get_reg16(ctx, r1); + codegen::gen_get_reg16(ctx, r2); + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn3_ret($fn); + codegen::gen_set_reg16(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, none) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::WORD, &addr, &|ref mut ctx| { + let mut dest_operand = ctx.builder.set_new_local(); + $fn(ctx, &mut dest_operand); + ctx.builder.get_local(&dest_operand); + ctx.builder.free_local(dest_operand); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32) { + $fn(ctx, &mut ctx.reg(r1)); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, $imm:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + let imm = mask_imm!(imm, $imm) as i32; + codegen::gen_safe_read_write(ctx, BitSize::WORD, &addr, &|ref mut ctx| { + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn2_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, imm: u32) { + let imm = mask_imm!(imm, $imm); + codegen::gen_get_reg16(ctx, r1); + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn2_ret($fn); + codegen::gen_set_reg16(ctx, r1); + } + ); +); + +macro_rules! define_instruction_read_write_mem32( + ($fn:expr, $name_mem:ident, $name_reg:ident, reg) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &addr, &|ref mut ctx| { + let dest_operand = ctx.builder.set_new_local(); + $fn( + ctx, + &dest_operand, + &LocalOrImmediate::WasmLocal(&ctx.reg(r)), + ); + ctx.builder.get_local(&dest_operand); + ctx.builder.free_local(dest_operand); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + $fn( + ctx, + &ctx.reg(r1), + &LocalOrImmediate::WasmLocal(&ctx.reg(r2)), + ); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, constant_one) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &addr, &|ref mut ctx| { + let dest_operand = ctx.builder.set_new_local(); + $fn(ctx, &dest_operand, &LocalOrImmediate::Immediate(1)); + ctx.builder.get_local(&dest_operand); + ctx.builder.free_local(dest_operand); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32) { + $fn(ctx, &ctx.reg(r1), &LocalOrImmediate::Immediate(1)); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, cl) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &addr, &|ref mut ctx| { + let dest_operand = ctx.builder.set_new_local(); + $fn( + ctx, + &dest_operand, + &LocalOrImmediate::WasmLocal(&ctx.reg(regs::ECX)), + ); + ctx.builder.get_local(&dest_operand); + ctx.builder.free_local(dest_operand); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32) { + $fn( + ctx, + &ctx.reg(r1), + &LocalOrImmediate::WasmLocal(&ctx.reg(regs::ECX)), + ); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, reg, cl) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &addr, &|ref mut ctx| { + codegen::gen_get_reg32(ctx, r); + codegen::gen_get_reg8(ctx, regs::CL); + ctx.builder.const_i32(31); + ctx.builder.and_i32(); + ctx.builder.call_fn3_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg32(ctx, r1); + codegen::gen_get_reg32(ctx, r2); + codegen::gen_get_reg8(ctx, regs::CL); + ctx.builder.const_i32(31); + ctx.builder.and_i32(); + ctx.builder.call_fn3_ret($fn); + codegen::gen_set_reg32(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, reg, $imm:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + let imm = mask_imm!(imm, $imm) as i32; + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &addr, &|ref mut ctx| { + codegen::gen_get_reg32(ctx, r); + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn3_ret($fn); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32, imm: u32) { + let imm = mask_imm!(imm, $imm); + codegen::gen_get_reg32(ctx, r1); + codegen::gen_get_reg32(ctx, r2); + ctx.builder.const_i32(imm as i32); + ctx.builder.call_fn3_ret($fn); + codegen::gen_set_reg32(ctx, r1); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, none) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &addr, &|ref mut ctx| { + let mut dest_operand = ctx.builder.set_new_local(); + $fn(ctx, &mut dest_operand); + ctx.builder.get_local(&dest_operand); + ctx.builder.free_local(dest_operand); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32) { + $fn(ctx, &mut ctx.reg(r1)); + } + ); + + ($fn:expr, $name_mem:ident, $name_reg:ident, $imm:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + let imm = mask_imm!(imm, $imm); + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &addr, &|ref mut ctx| { + let dest_operand = ctx.builder.set_new_local(); + $fn( + ctx, + &dest_operand, + &LocalOrImmediate::Immediate(imm as i32), + ); + ctx.builder.get_local(&dest_operand); + ctx.builder.free_local(dest_operand); + }); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, imm: u32) { + let imm = mask_imm!(imm, $imm); + $fn( + ctx, + &ctx.reg(r1), + &LocalOrImmediate::Immediate(imm as i32), + ); + } + ); +); + +fn gen_add8(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Add { + opsize: OPSIZE_8, + dest: local_to_instruction_operand(ctx, dest_operand), + source: if source_operand.eq_local(dest_operand) { + InstructionOperand::Other // aliasing + } + else { + source_operand.to_instruction_operand(ctx) + }, + is_inc: false, + }; + + ctx.builder.const_i32(global_pointers::last_op1 as i32); + ctx.builder.get_local(dest_operand); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + ctx.builder.store_aligned_i32(0); + + ctx.builder.const_i32(global_pointers::last_result as i32); + ctx.builder.get_local(dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.add_i32(); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + ctx.builder.store_aligned_i32(0); + + codegen::gen_set_last_op_size_and_flags_changed(ctx.builder, OPSIZE_8, FLAGS_ALL); + + ctx.builder + .load_fixed_u8(global_pointers::last_result as u32); +} +fn gen_add32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Add { + opsize: OPSIZE_32, + dest: local_to_instruction_operand(ctx, dest_operand), + source: if source_operand.eq_local(dest_operand) { + InstructionOperand::Other // aliasing + } + else { + source_operand.to_instruction_operand(ctx) + }, + is_inc: false, + }; + + codegen::gen_set_last_op1(ctx.builder, &dest_operand); + + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.add_i32(); + ctx.builder.set_local(dest_operand); + + codegen::gen_set_last_result(ctx.builder, &dest_operand); + codegen::gen_set_last_op_size_and_flags_changed(ctx.builder, OPSIZE_32, FLAGS_ALL); +} + +fn gen_sub8(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Sub { + opsize: OPSIZE_8, + dest: local_to_instruction_operand(ctx, dest_operand), + source: if source_operand.eq_local(dest_operand) { + InstructionOperand::Other // aliasing + } + else { + source_operand.to_instruction_operand(ctx) + }, + is_dec: false, + }; + + ctx.builder.const_i32(global_pointers::last_op1 as i32); + ctx.builder.get_local(dest_operand); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + ctx.builder.store_aligned_i32(0); + + ctx.builder.const_i32(global_pointers::last_result as i32); + ctx.builder.get_local(dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.sub_i32(); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + ctx.builder.store_aligned_i32(0); + + codegen::gen_set_last_op_size_and_flags_changed(ctx.builder, OPSIZE_8, FLAGS_ALL | FLAG_SUB); + + ctx.builder + .load_fixed_u8(global_pointers::last_result as u32); +} +fn gen_sub32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Sub { + opsize: OPSIZE_32, + dest: local_to_instruction_operand(ctx, dest_operand), + source: if source_operand.eq_local(dest_operand) { + InstructionOperand::Other // aliasing + } + else { + source_operand.to_instruction_operand(ctx) + }, + is_dec: false, + }; + + codegen::gen_set_last_op1(ctx.builder, &dest_operand); + + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.sub_i32(); + ctx.builder.set_local(dest_operand); + + codegen::gen_set_last_result(ctx.builder, &dest_operand); + codegen::gen_set_last_op_size_and_flags_changed(ctx.builder, OPSIZE_32, FLAGS_ALL | FLAG_SUB); +} + +fn gen_cmp( + ctx: &mut JitContext, + dest_operand: &WasmLocal, + source_operand: &LocalOrImmediate, + size: i32, +) { + ctx.current_instruction = Instruction::Cmp { + dest: local_to_instruction_operand(ctx, dest_operand), + source: source_operand.to_instruction_operand(ctx), + opsize: size, + }; + + ctx.builder.const_i32(global_pointers::last_result as i32); + if source_operand.is_zero() { + ctx.builder.get_local(&dest_operand); + } + else { + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.sub_i32(); + } + if size == OPSIZE_8 || size == OPSIZE_16 { + ctx.builder + .const_i32(if size == OPSIZE_8 { 0xFF } else { 0xFFFF }); + ctx.builder.and_i32(); + } + ctx.builder.store_aligned_i32(0); + + ctx.builder.const_i32(global_pointers::last_op1 as i32); + ctx.builder.get_local(&dest_operand); + if size == OPSIZE_8 || size == OPSIZE_16 { + ctx.builder + .const_i32(if size == OPSIZE_8 { 0xFF } else { 0xFFFF }); + ctx.builder.and_i32(); + } + ctx.builder.store_aligned_i32(0); + codegen::gen_set_last_op_size_and_flags_changed(ctx.builder, size, FLAGS_ALL | FLAG_SUB); +} +fn gen_cmp8(ctx: &mut JitContext, dest: &WasmLocal, source: &LocalOrImmediate) { + gen_cmp(ctx, dest, source, OPSIZE_8) +} +fn gen_cmp16(ctx: &mut JitContext, dest: &WasmLocal, source: &LocalOrImmediate) { + gen_cmp(ctx, dest, source, OPSIZE_16) +} +fn gen_cmp32(ctx: &mut JitContext, dest: &WasmLocal, source: &LocalOrImmediate) { + gen_cmp(ctx, dest, source, OPSIZE_32) +} + +fn gen_adc8(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.builder.get_local(dest_operand); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + source_operand.gen_get_mask255(ctx.builder); + ctx.builder.call_fn2_ret("adc8"); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + + ctx.current_instruction = Instruction::AdcSbb { + opsize: OPSIZE_8, + dest: local_to_instruction_operand(ctx, dest_operand), + source: if source_operand.eq_local(dest_operand) { + InstructionOperand::Other // aliasing + } + else { + source_operand.to_instruction_operand(ctx) + }, + }; +} +fn gen_adc32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.add_i32(); + codegen::gen_getcf(ctx, ConditionNegate::False); + ctx.builder.add_i32(); + let res = ctx.builder.set_new_local(); + + codegen::gen_set_last_result(ctx.builder, &res); + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_32, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW & !FLAG_ADJUST, + ); + + ctx.builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(ctx.builder); + ctx.builder + .const_i32(!FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW); + ctx.builder.and_i32(); + + // cf: (dest_operand ^ ((dest_operand ^ source_operand) & (source_operand ^ res))) >> op_size & FLAG_CARRY + ctx.builder.get_local(&dest_operand); + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.xor_i32(); + source_operand.gen_get(ctx.builder); + ctx.builder.get_local(&res); + ctx.builder.xor_i32(); + ctx.builder.and_i32(); + ctx.builder.xor_i32(); + ctx.builder.const_i32(31); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(FLAG_CARRY); + ctx.builder.and_i32(); + ctx.builder.or_i32(); + + // af: (dest_operand ^ source_operand ^ res) & FLAG_ADJUST + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.get_local(&res); + ctx.builder.xor_i32(); + ctx.builder.xor_i32(); + ctx.builder.const_i32(FLAG_ADJUST); + ctx.builder.and_i32(); + ctx.builder.or_i32(); + + // of: ((source_operand ^ res) & (dest_operand ^ res)) >> op_size << 11 & FLAG_OVERFLOW + source_operand.gen_get(ctx.builder); + ctx.builder.get_local(&res); + ctx.builder.xor_i32(); + ctx.builder.get_local(&dest_operand); + ctx.builder.get_local(&res); + ctx.builder.xor_i32(); + ctx.builder.and_i32(); + ctx.builder.const_i32(31 - 11); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(FLAG_OVERFLOW); + ctx.builder.and_i32(); + ctx.builder.or_i32(); + + ctx.builder.store_aligned_i32(0); + + ctx.builder.get_local(&res); + ctx.builder.set_local(dest_operand); + ctx.builder.free_local(res); + + ctx.current_instruction = Instruction::AdcSbb { + opsize: OPSIZE_32, + dest: local_to_instruction_operand(ctx, dest_operand), + source: if source_operand.eq_local(dest_operand) { + InstructionOperand::Other // aliasing + } + else { + source_operand.to_instruction_operand(ctx) + }, + }; +} + +fn gen_sbb8(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.builder.get_local(dest_operand); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + source_operand.gen_get_mask255(ctx.builder); + ctx.builder.call_fn2_ret("sbb8"); + ctx.builder.const_i32(0xFF); + ctx.builder.and_i32(); + + ctx.current_instruction = Instruction::AdcSbb { + opsize: OPSIZE_8, + dest: local_to_instruction_operand(ctx, dest_operand), + source: if source_operand.eq_local(dest_operand) { + InstructionOperand::Other // aliasing + } + else { + source_operand.to_instruction_operand(ctx) + }, + }; +} +fn gen_sbb32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.sub_i32(); + codegen::gen_getcf(ctx, ConditionNegate::False); + ctx.builder.sub_i32(); + let res = ctx.builder.set_new_local(); + + codegen::gen_set_last_result(ctx.builder, &res); + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_32, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW & !FLAG_ADJUST, + ); + + ctx.builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(ctx.builder); + ctx.builder + .const_i32(!FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW); + ctx.builder.and_i32(); + + // cf: (res ^ ((res ^ source_operand) & (source_operand ^ dest_operand))) >> op_size & FLAG_CARRY + ctx.builder.get_local(&res); + ctx.builder.get_local(&res); + source_operand.gen_get(ctx.builder); + ctx.builder.xor_i32(); + source_operand.gen_get(ctx.builder); + ctx.builder.get_local(&dest_operand); + ctx.builder.xor_i32(); + ctx.builder.and_i32(); + ctx.builder.xor_i32(); + ctx.builder.const_i32(31); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(FLAG_CARRY); + ctx.builder.and_i32(); + ctx.builder.or_i32(); + + // af: (dest_operand ^ source_operand ^ res) & FLAG_ADJUST + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.get_local(&res); + ctx.builder.xor_i32(); + ctx.builder.xor_i32(); + ctx.builder.const_i32(FLAG_ADJUST); + ctx.builder.and_i32(); + ctx.builder.or_i32(); + + // of: ((source_operand ^ dest_operand) & (res ^ dest_operand)) >> op_size << 11 & FLAG_OVERFLOW + source_operand.gen_get(ctx.builder); + ctx.builder.get_local(&dest_operand); + ctx.builder.xor_i32(); + ctx.builder.get_local(&res); + ctx.builder.get_local(&dest_operand); + ctx.builder.xor_i32(); + ctx.builder.and_i32(); + ctx.builder.const_i32(31 - 11); + ctx.builder.shr_u_i32(); + ctx.builder.const_i32(FLAG_OVERFLOW); + ctx.builder.and_i32(); + ctx.builder.or_i32(); + + ctx.builder.store_aligned_i32(0); + + ctx.builder.get_local(&res); + ctx.builder.set_local(dest_operand); + ctx.builder.free_local(res); + + ctx.current_instruction = Instruction::AdcSbb { + opsize: OPSIZE_32, + dest: local_to_instruction_operand(ctx, dest_operand), + source: if source_operand.eq_local(dest_operand) { + InstructionOperand::Other // aliasing + } + else { + source_operand.to_instruction_operand(ctx) + }, + }; +} + +fn gen_and8(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Bitwise { + opsize: OPSIZE_8, + dest: local_to_instruction_operand(ctx, dest_operand), + }; + + ctx.builder.const_i32(global_pointers::last_result as i32); + ctx.builder.get_local(dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.and_i32(); + ctx.builder.store_aligned_i32(0); + + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_8, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW & !FLAG_ADJUST, + ); + codegen::gen_clear_flags_bits(ctx.builder, FLAG_CARRY | FLAG_OVERFLOW | FLAG_ADJUST); + + ctx.builder + .load_fixed_u8(global_pointers::last_result as u32); +} +fn gen_and32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Bitwise { + opsize: OPSIZE_32, + dest: local_to_instruction_operand(ctx, dest_operand), + }; + + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.and_i32(); + ctx.builder.set_local(dest_operand); + + codegen::gen_set_last_result(ctx.builder, &dest_operand); + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_32, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW & !FLAG_ADJUST, + ); + codegen::gen_clear_flags_bits(ctx.builder, FLAG_CARRY | FLAG_OVERFLOW | FLAG_ADJUST); +} + +fn gen_test( + ctx: &mut JitContext, + dest_operand: &WasmLocal, + source_operand: &LocalOrImmediate, + size: i32, +) { + let is_self_test = source_operand.eq_local(dest_operand); + ctx.current_instruction = Instruction::Bitwise { + opsize: size, + dest: if is_self_test { + local_to_instruction_operand(ctx, dest_operand) + } + else { + InstructionOperandDest::Other + }, + }; + + ctx.builder.const_i32(global_pointers::last_result as i32); + if is_self_test { + ctx.builder.get_local(&dest_operand); + } + else { + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.and_i32(); + } + ctx.builder.store_aligned_i32(0); + + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + size, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW & !FLAG_ADJUST, + ); + codegen::gen_clear_flags_bits(ctx.builder, FLAG_CARRY | FLAG_OVERFLOW | FLAG_ADJUST); +} +fn gen_test8(ctx: &mut JitContext, dest: &WasmLocal, source: &LocalOrImmediate) { + gen_test(ctx, dest, source, OPSIZE_8) +} +fn gen_test16(ctx: &mut JitContext, dest: &WasmLocal, source: &LocalOrImmediate) { + gen_test(ctx, dest, source, OPSIZE_16) +} +fn gen_test32(ctx: &mut JitContext, dest: &WasmLocal, source: &LocalOrImmediate) { + gen_test(ctx, dest, source, OPSIZE_32) +} + +fn gen_or8(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Bitwise { + opsize: OPSIZE_8, + dest: local_to_instruction_operand(ctx, dest_operand), + }; + + ctx.builder.const_i32(global_pointers::last_result as i32); + ctx.builder.get_local(dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.or_i32(); + ctx.builder.store_aligned_i32(0); + + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_8, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW & !FLAG_ADJUST, + ); + codegen::gen_clear_flags_bits(ctx.builder, FLAG_CARRY | FLAG_OVERFLOW | FLAG_ADJUST); + + ctx.builder + .load_fixed_u8(global_pointers::last_result as u32); +} +fn gen_or32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Bitwise { + opsize: OPSIZE_32, + dest: local_to_instruction_operand(ctx, dest_operand), + }; + + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.or_i32(); + ctx.builder.set_local(dest_operand); + + codegen::gen_set_last_result(ctx.builder, &dest_operand); + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_32, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW & !FLAG_ADJUST, + ); + codegen::gen_clear_flags_bits(ctx.builder, FLAG_CARRY | FLAG_OVERFLOW | FLAG_ADJUST); +} + +fn gen_xor8(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Bitwise { + opsize: OPSIZE_8, + dest: local_to_instruction_operand(ctx, dest_operand), + }; + + ctx.builder.const_i32(global_pointers::last_result as i32); + ctx.builder.get_local(dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.xor_i32(); + ctx.builder.store_aligned_i32(0); + + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_8, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW & !FLAG_ADJUST, + ); + codegen::gen_clear_flags_bits(ctx.builder, FLAG_CARRY | FLAG_OVERFLOW | FLAG_ADJUST); + + ctx.builder + .load_fixed_u8(global_pointers::last_result as u32); +} +fn gen_xor32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.current_instruction = Instruction::Bitwise { + opsize: OPSIZE_32, + dest: local_to_instruction_operand(ctx, dest_operand), + }; + + if source_operand.eq_local(dest_operand) { + ctx.builder.const_i32(0); + ctx.builder.set_local(dest_operand); + // TODO: + // - Set last_result to zero rather than reading from local + // - Skip setting opsize (not relevant for SF, ZF, and PF on zero) + } + else { + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.xor_i32(); + ctx.builder.set_local(dest_operand); + } + + codegen::gen_set_last_result(ctx.builder, &dest_operand); + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_32, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW & !FLAG_ADJUST, + ); + codegen::gen_clear_flags_bits(ctx.builder, FLAG_CARRY | FLAG_OVERFLOW | FLAG_ADJUST); +} + +fn gen_rol32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + let builder = &mut ctx.builder; + builder.get_local(dest_operand); + match source_operand { + LocalOrImmediate::WasmLocal(l) => { + builder.get_local(l); + builder.const_i32(31); + builder.and_i32(); + }, + LocalOrImmediate::Immediate(i) => { + builder.const_i32(*i & 31); + }, + } + builder.const_i32(31); + builder.and_i32(); + builder.call_fn2_ret("rol32"); + builder.set_local(dest_operand); +} +fn gen_ror32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + let builder = &mut ctx.builder; + builder.get_local(dest_operand); + match source_operand { + LocalOrImmediate::WasmLocal(l) => { + builder.get_local(l); + builder.const_i32(31); + builder.and_i32(); + }, + LocalOrImmediate::Immediate(i) => { + builder.const_i32(*i & 31); + }, + } + builder.const_i32(31); + builder.and_i32(); + builder.call_fn2_ret("ror32"); + builder.set_local(dest_operand); +} + +fn gen_rcl32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + let builder = &mut ctx.builder; + builder.get_local(dest_operand); + match source_operand { + LocalOrImmediate::WasmLocal(l) => { + builder.get_local(l); + builder.const_i32(31); + builder.and_i32(); + }, + LocalOrImmediate::Immediate(i) => { + builder.const_i32(*i & 31); + }, + } + builder.const_i32(31); + builder.and_i32(); + builder.call_fn2_ret("rcl32"); + builder.set_local(dest_operand); +} +fn gen_rcr32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + let builder = &mut ctx.builder; + builder.get_local(dest_operand); + match source_operand { + LocalOrImmediate::WasmLocal(l) => { + builder.get_local(l); + builder.const_i32(31); + builder.and_i32(); + }, + LocalOrImmediate::Immediate(i) => { + builder.const_i32(*i & 31); + }, + } + builder.const_i32(31); + builder.and_i32(); + builder.call_fn2_ret("rcr32"); + builder.set_local(dest_operand); +} + +enum ShiftCount { + Local(WasmLocal), + Immediate(i32), +} +impl ShiftCount { + pub fn gen_get(builder: &mut WasmBuilder, count: &ShiftCount) { + match &count { + ShiftCount::Local(l) => builder.get_local(l), + ShiftCount::Immediate(i) => builder.const_i32(*i), + } + } + pub fn gen_get_thirtytwo_minus(builder: &mut WasmBuilder, count: &ShiftCount) { + match &count { + ShiftCount::Local(l) => { + builder.const_i32(32); + builder.get_local(l); + builder.sub_i32(); + }, + ShiftCount::Immediate(i) => builder.const_i32(32 - *i), + } + } + pub fn gen_get_minus_one(builder: &mut WasmBuilder, count: &ShiftCount) { + match &count { + ShiftCount::Local(l) => { + builder.get_local(l); + builder.const_i32(1); + builder.sub_i32() + }, + ShiftCount::Immediate(i) => builder.const_i32(*i - 1), + } + } +} + +fn gen_shl32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + if let &LocalOrImmediate::Immediate(1..=31) = source_operand { + ctx.current_instruction = Instruction::NonZeroShift { + dest: local_to_instruction_operand(ctx, dest_operand), + opsize: OPSIZE_32, + }; + } + let builder = &mut ctx.builder; + let count = match source_operand { + LocalOrImmediate::WasmLocal(l) => { + let exit = builder.block_void(); + builder.get_local(l); + builder.const_i32(31); // Note: mask can probably be avoided since wasm has the same semantics on shl_i32 + builder.and_i32(); + let count = builder.tee_new_local(); + builder.eqz_i32(); + builder.br_if(exit); + ShiftCount::Local(count) + }, + LocalOrImmediate::Immediate(i) => { + if *i & 31 == 0 { + return; + } + ShiftCount::Immediate(*i & 31) + }, + }; + + builder.get_local(&dest_operand); + ShiftCount::gen_get_thirtytwo_minus(builder, &count); + builder.shr_u_i32(); + builder.const_i32(1); + builder.and_i32(); + let b = builder.set_new_local(); + + builder.get_local(dest_operand); + ShiftCount::gen_get(builder, &count); + builder.shl_i32(); + builder.set_local(dest_operand); + + codegen::gen_set_last_result(builder, dest_operand); + codegen::gen_set_last_op_size_and_flags_changed( + builder, + OPSIZE_32, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW, + ); + + builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(builder); + builder.const_i32(!(FLAG_CARRY | FLAG_OVERFLOW)); + builder.and_i32(); + builder.get_local(&b); + builder.or_i32(); + { + builder.get_local(&b); + builder.get_local(&dest_operand); + builder.const_i32(31); + builder.shr_u_i32(); + builder.xor_i32(); + builder.const_i32(11); + builder.shl_i32(); + builder.const_i32(FLAG_OVERFLOW); + builder.and_i32(); + builder.or_i32(); + } + builder.store_aligned_i32(0); + + builder.free_local(b); + + if let ShiftCount::Local(l) = count { + builder.block_end(); + builder.free_local(l); + } +} +fn gen_shr32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + if let &LocalOrImmediate::Immediate(1..=31) = source_operand { + ctx.current_instruction = Instruction::NonZeroShift { + dest: local_to_instruction_operand(ctx, dest_operand), + opsize: OPSIZE_32, + }; + } + let builder = &mut ctx.builder; + let count = match source_operand { + LocalOrImmediate::WasmLocal(l) => { + let exit = builder.block_void(); + builder.get_local(l); + builder.const_i32(31); // Note: mask can probably be avoided since wasm has the same semantics on shl_i32 + builder.and_i32(); + let count = builder.tee_new_local(); + builder.eqz_i32(); + builder.br_if(exit); + ShiftCount::Local(count) + }, + LocalOrImmediate::Immediate(i) => { + if *i & 31 == 0 { + return; + } + ShiftCount::Immediate(*i & 31) + }, + }; + + builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(builder); + builder.const_i32(!(FLAG_CARRY | FLAG_OVERFLOW)); + builder.and_i32(); + { + builder.get_local(dest_operand); + ShiftCount::gen_get_minus_one(builder, &count); + builder.shr_u_i32(); + builder.const_i32(1); + builder.and_i32(); + builder.or_i32() + } + { + builder.get_local(dest_operand); + builder.const_i32(20); + builder.shr_u_i32(); + builder.const_i32(FLAG_OVERFLOW); + builder.and_i32(); + builder.or_i32() + } + builder.store_aligned_i32(0); + + builder.get_local(dest_operand); + ShiftCount::gen_get(builder, &count); + builder.shr_u_i32(); + builder.set_local(dest_operand); + + codegen::gen_set_last_result(builder, dest_operand); + codegen::gen_set_last_op_size_and_flags_changed( + builder, + OPSIZE_32, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW, + ); + + if let ShiftCount::Local(l) = count { + builder.block_end(); + builder.free_local(l); + } +} +fn gen_sar32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + if let &LocalOrImmediate::Immediate(1..=31) = source_operand { + ctx.current_instruction = Instruction::NonZeroShift { + dest: local_to_instruction_operand(ctx, dest_operand), + opsize: OPSIZE_32, + }; + } + let builder = &mut ctx.builder; + let count = match source_operand { + LocalOrImmediate::WasmLocal(l) => { + let exit = builder.block_void(); + builder.get_local(l); + builder.const_i32(31); // Note: mask can probably be avoided since wasm has the same semantics on shl_i32 + builder.and_i32(); + let count = builder.tee_new_local(); + builder.eqz_i32(); + builder.br_if(exit); + ShiftCount::Local(count) + }, + LocalOrImmediate::Immediate(i) => { + if *i & 31 == 0 { + return; + } + ShiftCount::Immediate(*i & 31) + }, + }; + + builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(builder); + builder.const_i32(!(FLAG_CARRY | FLAG_OVERFLOW)); + builder.and_i32(); + { + builder.get_local(dest_operand); + ShiftCount::gen_get_minus_one(builder, &count); + builder.shr_u_i32(); + builder.const_i32(1); + builder.and_i32(); + builder.or_i32() + } + builder.store_aligned_i32(0); + + builder.get_local(dest_operand); + ShiftCount::gen_get(builder, &count); + builder.shr_s_i32(); + builder.set_local(dest_operand); + + codegen::gen_set_last_result(builder, dest_operand); + codegen::gen_set_last_op_size_and_flags_changed( + builder, + OPSIZE_32, + FLAGS_ALL & !FLAG_CARRY & !FLAG_OVERFLOW, + ); + + if let ShiftCount::Local(l) = count { + builder.block_end(); + builder.free_local(l); + } +} + +fn gen_xadd32(ctx: &mut JitContext, dest_operand: &WasmLocal, r: u32) { + ctx.builder.get_local(&ctx.register_locals[r as usize]); + let tmp = ctx.builder.set_new_local(); + + ctx.builder.get_local(&dest_operand); + codegen::gen_set_reg32(ctx, r); + + gen_add32(ctx, &dest_operand, &LocalOrImmediate::WasmLocal(&tmp)); + + ctx.builder.free_local(tmp); +} + +fn gen_cmpxchg32(ctx: &mut JitContext, r: u32) { + let source = ctx.builder.set_new_local(); + + ctx.builder.const_i32(global_pointers::last_result as i32); + codegen::gen_get_reg32(ctx, regs::EAX); + ctx.builder.get_local(&source); + ctx.builder.sub_i32(); + ctx.builder.store_aligned_i32(0); + + ctx.builder.const_i32(global_pointers::last_op1 as i32); + codegen::gen_get_reg32(ctx, regs::EAX); + ctx.builder.store_aligned_i32(0); + codegen::gen_set_last_op_size_and_flags_changed(ctx.builder, OPSIZE_32, FLAGS_ALL | FLAG_SUB); + + codegen::gen_get_reg32(ctx, regs::EAX); + ctx.builder.get_local(&source); + ctx.builder.eq_i32(); + ctx.builder.if_i32(); + codegen::gen_get_reg32(ctx, r); + ctx.builder.else_(); + ctx.builder.get_local(&source); + codegen::gen_set_reg32(ctx, regs::EAX); + ctx.builder.get_local(&source); + ctx.builder.block_end(); + + ctx.builder.free_local(source); +} + +fn gen_mul32(ctx: &mut JitContext) { + ctx.builder.extend_unsigned_i32_to_i64(); + + codegen::gen_get_reg32(ctx, regs::EAX); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder.mul_i64(); + + let result = ctx.builder.tee_new_local_i64(); + ctx.builder.const_i64(32); + ctx.builder.shr_u_i64(); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EDX); + + ctx.builder.get_local_i64(&result); + ctx.builder.free_local_i64(result); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EAX); + + codegen::gen_get_reg32(ctx, regs::EDX); + ctx.builder.if_void(); + codegen::gen_set_flags_bits(ctx.builder, 1 | FLAG_OVERFLOW); + ctx.builder.else_(); + codegen::gen_clear_flags_bits(ctx.builder, 1 | FLAG_OVERFLOW); + ctx.builder.block_end(); + + codegen::gen_set_last_result(ctx.builder, &ctx.register_locals[regs::EAX as usize]); + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_32, + FLAGS_ALL & !1 & !FLAG_OVERFLOW, + ); +} + +fn gen_imul32(ctx: &mut JitContext) { + ctx.builder.extend_signed_i32_to_i64(); + + codegen::gen_get_reg32(ctx, regs::EAX); + ctx.builder.extend_signed_i32_to_i64(); + ctx.builder.mul_i64(); + + let result = ctx.builder.tee_new_local_i64(); + ctx.builder.const_i64(32); + ctx.builder.shr_u_i64(); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EDX); + + ctx.builder.get_local_i64(&result); + ctx.builder.free_local_i64(result); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EAX); + + codegen::gen_get_reg32(ctx, regs::EDX); + codegen::gen_get_reg32(ctx, regs::EAX); + ctx.builder.const_i32(31); + ctx.builder.shr_s_i32(); + ctx.builder.eq_i32(); + ctx.builder.if_void(); + codegen::gen_clear_flags_bits(ctx.builder, 1 | FLAG_OVERFLOW); + ctx.builder.else_(); + codegen::gen_set_flags_bits(ctx.builder, 1 | FLAG_OVERFLOW); + ctx.builder.block_end(); + + codegen::gen_set_last_result(ctx.builder, &ctx.register_locals[regs::EAX as usize]); + codegen::gen_set_last_op_size_and_flags_changed( + ctx.builder, + OPSIZE_32, + FLAGS_ALL & !1 & !FLAG_OVERFLOW, + ); +} + +fn gen_imul_reg32( + ctx: &mut JitContext, + dest_operand: &WasmLocal, + source_operand: &LocalOrImmediate, +) { + gen_imul3_reg32(ctx.builder, dest_operand, dest_operand, source_operand); +} + +fn gen_imul3_reg32( + builder: &mut WasmBuilder, + dest_operand: &WasmLocal, + source_operand1: &WasmLocal, + source_operand2: &LocalOrImmediate, +) { + builder.get_local(&source_operand1); + builder.extend_signed_i32_to_i64(); + source_operand2.gen_get(builder); + builder.extend_signed_i32_to_i64(); + builder.mul_i64(); + + let result = builder.tee_new_local_i64(); + builder.wrap_i64_to_i32(); + builder.set_local(&dest_operand); + + codegen::gen_set_last_result(builder, &dest_operand); + codegen::gen_set_last_op_size_and_flags_changed( + builder, + OPSIZE_32, + FLAGS_ALL & !1 & !FLAG_OVERFLOW, + ); + + builder.const_i32(global_pointers::flags as i32); + builder.get_local_i64(&result); + builder.wrap_i64_to_i32(); + builder.extend_signed_i32_to_i64(); + builder.get_local_i64(&result); + builder.ne_i64(); + builder.const_i32(1 | FLAG_OVERFLOW); + builder.mul_i32(); + codegen::gen_get_flags(builder); + builder.const_i32(!1 & !FLAG_OVERFLOW); + builder.and_i32(); + builder.or_i32(); + builder.store_aligned_i32(0); + + builder.free_local_i64(result); +} + +fn gen_div32(ctx: &mut JitContext, source: &WasmLocal) { + let done = ctx.builder.block_void(); + { + let exception = ctx.builder.block_void(); + { + ctx.builder.get_local(source); + ctx.builder.eqz_i32(); + ctx.builder.br_if(exception); + + codegen::gen_get_reg32(ctx, regs::EDX); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder.const_i64(32); + ctx.builder.shl_i64(); + codegen::gen_get_reg32(ctx, regs::EAX); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder.or_i64(); + let dest_operand = ctx.builder.tee_new_local_i64(); + + ctx.builder.get_local(source); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder.div_i64(); + let result = ctx.builder.tee_new_local_i64(); + ctx.builder.const_i64(0xFFFF_FFFF); + ctx.builder.gtu_i64(); + ctx.builder.br_if(exception); + + ctx.builder.get_local_i64(&dest_operand); + ctx.builder.get_local(source); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder.rem_i64(); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EDX); + + ctx.builder.get_local_i64(&result); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EAX); + ctx.builder.br(done); + + ctx.builder.free_local_i64(dest_operand); + ctx.builder.free_local_i64(result); + } + ctx.builder.block_end(); + + codegen::gen_trigger_de(ctx); + } + ctx.builder.block_end(); +} + +fn gen_bt( + builder: &mut WasmBuilder, + bit_base: &WasmLocal, + bit_offset: &LocalOrImmediate, + offset_mask: u32, +) { + builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(builder); + builder.const_i32(!1); + builder.and_i32(); + builder.get_local(bit_base); + match bit_offset { + LocalOrImmediate::WasmLocal(l) => { + builder.get_local(l); + builder.const_i32(offset_mask as i32); + builder.and_i32(); + }, + LocalOrImmediate::Immediate(imm) => builder.const_i32(imm & offset_mask as i32), + } + builder.shr_u_i32(); + builder.const_i32(1); + builder.and_i32(); + builder.or_i32(); + builder.store_aligned_i32(0); + + codegen::gen_clear_flags_changed_bits(builder, 1); +} +fn gen_bts( + builder: &mut WasmBuilder, + dest_bit_base: &WasmLocal, + bit_offset: &LocalOrImmediate, + offset_mask: u32, +) { + gen_bt(builder, dest_bit_base, bit_offset, offset_mask); + + builder.get_local(dest_bit_base); + match bit_offset { + LocalOrImmediate::WasmLocal(l) => { + builder.const_i32(1); + builder.get_local(l); + builder.const_i32(offset_mask as i32); + builder.and_i32(); + builder.shl_i32(); + }, + LocalOrImmediate::Immediate(imm) => builder.const_i32(1 << (imm & offset_mask as i32)), + } + builder.or_i32(); + builder.set_local(dest_bit_base); +} +fn gen_btc( + builder: &mut WasmBuilder, + dest_bit_base: &WasmLocal, + bit_offset: &LocalOrImmediate, + offset_mask: u32, +) { + gen_bt(builder, dest_bit_base, bit_offset, offset_mask); + + builder.get_local(dest_bit_base); + match bit_offset { + LocalOrImmediate::WasmLocal(l) => { + builder.const_i32(1); + builder.get_local(l); + builder.const_i32(offset_mask as i32); + builder.and_i32(); + builder.shl_i32(); + }, + LocalOrImmediate::Immediate(imm) => builder.const_i32(1 << (imm & offset_mask as i32)), + } + builder.xor_i32(); + builder.set_local(dest_bit_base); +} +fn gen_btr( + builder: &mut WasmBuilder, + dest_bit_base: &WasmLocal, + bit_offset: &LocalOrImmediate, + offset_mask: u32, +) { + gen_bt(builder, dest_bit_base, bit_offset, offset_mask); + + builder.get_local(dest_bit_base); + match bit_offset { + LocalOrImmediate::WasmLocal(l) => { + builder.const_i32(1); + builder.get_local(l); + builder.const_i32(offset_mask as i32); + builder.and_i32(); + builder.shl_i32(); + builder.const_i32(-1); + builder.xor_i32(); + }, + LocalOrImmediate::Immediate(imm) => builder.const_i32(!(1 << (imm & offset_mask as i32))), + } + builder.and_i32(); + builder.set_local(dest_bit_base); +} + +fn gen_bit_rmw( + ctx: &mut JitContext, + modrm_byte: ModrmByte, + op: &dyn Fn(&mut WasmBuilder, &WasmLocal, &LocalOrImmediate, u32), + source_operand: &LocalOrImmediate, + opsize: i32, +) { + dbg_assert!(opsize == 16 || opsize == 32); + codegen::gen_modrm_resolve(ctx, modrm_byte); + match source_operand { + LocalOrImmediate::WasmLocal(l) => { + ctx.builder.get_local(l); + if opsize == 16 { + codegen::sign_extend_i16(ctx.builder); + } + ctx.builder.const_i32(3); + ctx.builder.shr_s_i32(); + ctx.builder.add_i32(); + }, + &LocalOrImmediate::Immediate(imm8) => { + let offset = (imm8 as i32 & (opsize - 1)) >> 3; + if offset != 0 { + ctx.builder.const_i32(offset); + ctx.builder.add_i32(); + } + }, + } + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read_write(ctx, BitSize::BYTE, &address_local, &|ref mut ctx| { + let value_local = ctx.builder.set_new_local(); + op(ctx.builder, &value_local, source_operand, 7); + ctx.builder.get_local(&value_local); + ctx.builder.free_local(value_local); + }); + ctx.builder.free_local(address_local); +} + +fn gen_bsf32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.call_fn2_ret("bsf32"); + ctx.builder.set_local(dest_operand); +} + +fn gen_bsr32(ctx: &mut JitContext, dest_operand: &WasmLocal, source_operand: &LocalOrImmediate) { + ctx.builder.get_local(&dest_operand); + source_operand.gen_get(ctx.builder); + ctx.builder.call_fn2_ret("bsr32"); + ctx.builder.set_local(dest_operand); +} + +fn gen_bswap(ctx: &mut JitContext, reg: i32) { + let l = &ctx.register_locals[reg as usize]; + + ctx.builder.get_local(l); + ctx.builder.const_i32(8); + ctx.builder.rotl_i32(); + ctx.builder.const_i32(0xFF00FF); + ctx.builder.and_i32(); + + ctx.builder.get_local(l); + ctx.builder.const_i32(24); + ctx.builder.rotl_i32(); + ctx.builder.const_i32(0xFF00FF00u32 as i32); + ctx.builder.and_i32(); + + ctx.builder.or_i32(); + + ctx.builder.set_local(l); +} + +define_instruction_read_write_mem8!(gen_add8, instr_00_mem_jit, instr_00_reg_jit, reg); +define_instruction_read_write_mem16!("add16", instr16_01_mem_jit, instr16_01_reg_jit, reg); +define_instruction_read_write_mem32!(gen_add32, instr32_01_mem_jit, instr32_01_reg_jit, reg); + +define_instruction_write_reg8!(gen_add8, instr_02_mem_jit, instr_02_reg_jit); +define_instruction_write_reg16!("add16", instr16_03_mem_jit, instr16_03_reg_jit); +define_instruction_write_reg32!(gen_add32, instr32_03_mem_jit, instr32_03_reg_jit); + +pub fn instr_04_jit(ctx: &mut JitContext, imm8: u32) { group_arith_al_imm8(ctx, &gen_add8, imm8); } +pub fn instr16_05_jit(ctx: &mut JitContext, imm16: u32) { + group_arith_ax_imm16(ctx, "add16", imm16); +} +pub fn instr32_05_jit(ctx: &mut JitContext, imm32: u32) { + group_arith_eax_imm32(ctx, &gen_add32, imm32); +} + +define_instruction_read_write_mem8!(gen_or8, instr_08_mem_jit, instr_08_reg_jit, reg); +define_instruction_read_write_mem16!("or16", instr16_09_mem_jit, instr16_09_reg_jit, reg); +define_instruction_read_write_mem32!(gen_or32, instr32_09_mem_jit, instr32_09_reg_jit, reg); + +define_instruction_write_reg8!(gen_or8, instr_0A_mem_jit, instr_0A_reg_jit); +define_instruction_write_reg16!("or16", instr16_0B_mem_jit, instr16_0B_reg_jit); +define_instruction_write_reg32!(gen_or32, instr32_0B_mem_jit, instr32_0B_reg_jit); + +pub fn instr_0C_jit(ctx: &mut JitContext, imm8: u32) { group_arith_al_imm8(ctx, &gen_or8, imm8); } +pub fn instr16_0D_jit(ctx: &mut JitContext, imm16: u32) { + group_arith_ax_imm16(ctx, "or16", imm16); +} +pub fn instr32_0D_jit(ctx: &mut JitContext, imm32: u32) { + group_arith_eax_imm32(ctx, &gen_or32, imm32); +} + +define_instruction_read_write_mem8!(gen_adc8, instr_10_mem_jit, instr_10_reg_jit, reg); +define_instruction_read_write_mem16!("adc16", instr16_11_mem_jit, instr16_11_reg_jit, reg); +define_instruction_read_write_mem32!(gen_adc32, instr32_11_mem_jit, instr32_11_reg_jit, reg); + +define_instruction_write_reg8!(gen_adc8, instr_12_mem_jit, instr_12_reg_jit); +define_instruction_write_reg16!("adc16", instr16_13_mem_jit, instr16_13_reg_jit); +define_instruction_write_reg32!(gen_adc32, instr32_13_mem_jit, instr32_13_reg_jit); + +pub fn instr_14_jit(ctx: &mut JitContext, imm8: u32) { group_arith_al_imm8(ctx, &gen_adc8, imm8); } +pub fn instr16_15_jit(ctx: &mut JitContext, imm16: u32) { + group_arith_ax_imm16(ctx, "adc16", imm16); +} +pub fn instr32_15_jit(ctx: &mut JitContext, imm32: u32) { + group_arith_eax_imm32(ctx, &gen_adc32, imm32); +} + +define_instruction_read_write_mem8!(gen_sbb8, instr_18_mem_jit, instr_18_reg_jit, reg); +define_instruction_read_write_mem16!("sbb16", instr16_19_mem_jit, instr16_19_reg_jit, reg); +define_instruction_read_write_mem32!(gen_sbb32, instr32_19_mem_jit, instr32_19_reg_jit, reg); + +define_instruction_write_reg8!(gen_sbb8, instr_1A_mem_jit, instr_1A_reg_jit); +define_instruction_write_reg16!("sbb16", instr16_1B_mem_jit, instr16_1B_reg_jit); +define_instruction_write_reg32!(gen_sbb32, instr32_1B_mem_jit, instr32_1B_reg_jit); + +pub fn instr_1C_jit(ctx: &mut JitContext, imm8: u32) { group_arith_al_imm8(ctx, &gen_sbb8, imm8); } +pub fn instr16_1D_jit(ctx: &mut JitContext, imm16: u32) { + group_arith_ax_imm16(ctx, "sbb16", imm16); +} +pub fn instr32_1D_jit(ctx: &mut JitContext, imm32: u32) { + group_arith_eax_imm32(ctx, &gen_sbb32, imm32); +} + +define_instruction_read_write_mem8!(gen_and8, instr_20_mem_jit, instr_20_reg_jit, reg); +define_instruction_read_write_mem16!("and16", instr16_21_mem_jit, instr16_21_reg_jit, reg); +define_instruction_read_write_mem32!(gen_and32, instr32_21_mem_jit, instr32_21_reg_jit, reg); + +define_instruction_write_reg8!(gen_and8, instr_22_mem_jit, instr_22_reg_jit); +define_instruction_write_reg16!("and16", instr16_23_mem_jit, instr16_23_reg_jit); +define_instruction_write_reg32!(gen_and32, instr32_23_mem_jit, instr32_23_reg_jit); + +pub fn instr_24_jit(ctx: &mut JitContext, imm8: u32) { group_arith_al_imm8(ctx, &gen_and8, imm8); } +pub fn instr16_25_jit(ctx: &mut JitContext, imm16: u32) { + group_arith_ax_imm16(ctx, "and16", imm16); +} +pub fn instr32_25_jit(ctx: &mut JitContext, imm32: u32) { + group_arith_eax_imm32(ctx, &gen_and32, imm32); +} + +define_instruction_read_write_mem8!(gen_sub8, instr_28_mem_jit, instr_28_reg_jit, reg); +define_instruction_read_write_mem16!("sub16", instr16_29_mem_jit, instr16_29_reg_jit, reg); +define_instruction_read_write_mem32!(gen_sub32, instr32_29_mem_jit, instr32_29_reg_jit, reg); + +define_instruction_write_reg8!(gen_sub8, instr_2A_mem_jit, instr_2A_reg_jit); +define_instruction_write_reg16!("sub16", instr16_2B_mem_jit, instr16_2B_reg_jit); +define_instruction_write_reg32!(gen_sub32, instr32_2B_mem_jit, instr32_2B_reg_jit); + +pub fn instr_2C_jit(ctx: &mut JitContext, imm8: u32) { group_arith_al_imm8(ctx, &gen_sub8, imm8); } +pub fn instr16_2D_jit(ctx: &mut JitContext, imm16: u32) { + group_arith_ax_imm16(ctx, "sub16", imm16); +} +pub fn instr32_2D_jit(ctx: &mut JitContext, imm32: u32) { + group_arith_eax_imm32(ctx, &gen_sub32, imm32); +} + +define_instruction_read_write_mem8!(gen_xor8, instr_30_mem_jit, instr_30_reg_jit, reg); +define_instruction_read_write_mem16!("xor16", instr16_31_mem_jit, instr16_31_reg_jit, reg); +define_instruction_read_write_mem32!(gen_xor32, instr32_31_mem_jit, instr32_31_reg_jit, reg); + +define_instruction_write_reg8!(gen_xor8, instr_32_mem_jit, instr_32_reg_jit); +define_instruction_write_reg16!("xor16", instr16_33_mem_jit, instr16_33_reg_jit); +define_instruction_write_reg32!(gen_xor32, instr32_33_mem_jit, instr32_33_reg_jit); + +pub fn instr_34_jit(ctx: &mut JitContext, imm8: u32) { group_arith_al_imm8(ctx, &gen_xor8, imm8); } +pub fn instr16_35_jit(ctx: &mut JitContext, imm16: u32) { + group_arith_ax_imm16(ctx, "xor16", imm16); +} +pub fn instr32_35_jit(ctx: &mut JitContext, imm32: u32) { + group_arith_eax_imm32(ctx, &gen_xor32, imm32); +} + +define_instruction_read8!(gen_cmp8, instr_38_mem_jit, instr_38_reg_jit); +define_instruction_read16!(gen_cmp16, instr16_39_mem_jit, instr16_39_reg_jit); +define_instruction_read32!(gen_cmp32, instr32_39_mem_jit, instr32_39_reg_jit); + +pub fn instr_3A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + let dest_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r); + codegen::gen_modrm_resolve_safe_read8(ctx, modrm_byte); + let source_operand = ctx.builder.set_new_local(); + gen_cmp8( + ctx, + &dest_operand, + &LocalOrImmediate::WasmLocal(&source_operand), + ); + codegen::gen_free_reg8_or_alias(ctx, r, dest_operand); + ctx.builder.free_local(source_operand); +} + +pub fn instr_3A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + let dest_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r2); + let source_operand = codegen::gen_get_reg8_or_alias_to_reg32(ctx, r1); + gen_cmp8( + ctx, + &dest_operand, + &LocalOrImmediate::WasmLocal(&source_operand), + ); + codegen::gen_free_reg8_or_alias(ctx, r2, dest_operand); + codegen::gen_free_reg8_or_alias(ctx, r1, source_operand); +} + +pub fn instr16_3B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + let source_operand = ctx.builder.set_new_local(); + gen_cmp16( + ctx, + &ctx.reg(r), + &LocalOrImmediate::WasmLocal(&source_operand), + ); + ctx.builder.free_local(source_operand); +} + +pub fn instr16_3B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_cmp16( + ctx, + &ctx.reg(r2), + &LocalOrImmediate::WasmLocal(&ctx.reg(r1)), + ); +} + +pub fn instr32_3B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + let source_operand = ctx.builder.set_new_local(); + gen_cmp32( + ctx, + &ctx.reg(r), + &LocalOrImmediate::WasmLocal(&source_operand), + ); + ctx.builder.free_local(source_operand); +} + +pub fn instr32_3B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_cmp32( + ctx, + &ctx.reg(r2), + &LocalOrImmediate::WasmLocal(&ctx.reg(r1)), + ); +} + +pub fn instr_3C_jit(ctx: &mut JitContext, imm8: u32) { + gen_cmp8(ctx, &ctx.reg(0), &LocalOrImmediate::Immediate(imm8 as i32)); +} + +pub fn instr16_3D_jit(ctx: &mut JitContext, imm16: u32) { + gen_cmp16(ctx, &ctx.reg(0), &LocalOrImmediate::Immediate(imm16 as i32)); +} + +pub fn instr32_3D_jit(ctx: &mut JitContext, imm32: u32) { + gen_cmp32(ctx, &ctx.reg(0), &LocalOrImmediate::Immediate(imm32 as i32)); +} + +fn gen_inc(ctx: &mut JitContext, dest_operand: &WasmLocal, size: i32) { + ctx.builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(ctx.builder); + ctx.builder.const_i32(!1); + ctx.builder.and_i32(); + codegen::gen_getcf(ctx, ConditionNegate::False); + ctx.builder.or_i32(); + ctx.builder.store_aligned_i32(0); + + ctx.builder.const_i32(global_pointers::last_op1 as i32); + ctx.builder.get_local(&dest_operand); + if size == OPSIZE_8 || size == OPSIZE_16 { + ctx.builder + .const_i32(if size == OPSIZE_8 { 0xFF } else { 0xFFFF }); + ctx.builder.and_i32(); + } + ctx.builder.store_aligned_i32(0); + + ctx.builder.get_local(dest_operand); + ctx.builder.const_i32(1); + ctx.builder.add_i32(); + if size == OPSIZE_16 { + codegen::gen_set_reg16_local(ctx.builder, dest_operand); + } + else { + ctx.builder.set_local(dest_operand); + } + + ctx.builder.const_i32(global_pointers::last_result as i32); + ctx.builder.get_local(&dest_operand); + if size == OPSIZE_16 { + ctx.builder.const_i32(0xFFFF); + ctx.builder.and_i32(); + } + ctx.builder.store_aligned_i32(0); + codegen::gen_set_last_op_size_and_flags_changed(ctx.builder, size, FLAGS_ALL & !1); + ctx.current_instruction = Instruction::Add { + opsize: size, + dest: local_to_instruction_operand(ctx, dest_operand), + source: InstructionOperand::Immediate(1), + is_inc: true, + }; +} +fn gen_inc16(ctx: &mut JitContext, dest_operand: &WasmLocal) { + gen_inc(ctx, dest_operand, OPSIZE_16); +} +fn gen_inc32(ctx: &mut JitContext, dest_operand: &WasmLocal) { + gen_inc(ctx, dest_operand, OPSIZE_32); +} + +fn gen_dec(ctx: &mut JitContext, dest_operand: &WasmLocal, size: i32) { + ctx.builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(ctx.builder); + ctx.builder.const_i32(!1); + ctx.builder.and_i32(); + codegen::gen_getcf(ctx, ConditionNegate::False); + ctx.builder.or_i32(); + ctx.builder.store_aligned_i32(0); + + ctx.builder.const_i32(global_pointers::last_op1 as i32); + ctx.builder.get_local(&dest_operand); + if size == OPSIZE_8 || size == OPSIZE_16 { + ctx.builder + .const_i32(if size == OPSIZE_8 { 0xFF } else { 0xFFFF }); + ctx.builder.and_i32(); + } + ctx.builder.store_aligned_i32(0); + + ctx.builder.get_local(dest_operand); + ctx.builder.const_i32(1); + ctx.builder.sub_i32(); + if size == OPSIZE_16 { + codegen::gen_set_reg16_local(ctx.builder, dest_operand); + } + else { + ctx.builder.set_local(dest_operand); + } + + ctx.builder.const_i32(global_pointers::last_result as i32); + ctx.builder.get_local(&dest_operand); + if size == OPSIZE_16 { + ctx.builder.const_i32(0xFFFF); + ctx.builder.and_i32(); + } + ctx.builder.store_aligned_i32(0); + codegen::gen_set_last_op_size_and_flags_changed(ctx.builder, size, FLAGS_ALL & !1 | FLAG_SUB); + ctx.current_instruction = Instruction::Sub { + opsize: size, + dest: local_to_instruction_operand(ctx, dest_operand), + source: InstructionOperand::Immediate(1), + is_dec: true, + }; +} +fn gen_dec16(ctx: &mut JitContext, dest_operand: &WasmLocal) { + gen_dec(ctx, dest_operand, OPSIZE_16) +} +fn gen_dec32(ctx: &mut JitContext, dest_operand: &WasmLocal) { + gen_dec(ctx, dest_operand, OPSIZE_32) +} + +fn gen_inc16_r(ctx: &mut JitContext, r: u32) { gen_inc16(ctx, &mut ctx.reg(r)) } +fn gen_inc32_r(ctx: &mut JitContext, r: u32) { gen_inc32(ctx, &mut ctx.reg(r)) } +fn gen_dec16_r(ctx: &mut JitContext, r: u32) { gen_dec16(ctx, &mut ctx.reg(r)) } +fn gen_dec32_r(ctx: &mut JitContext, r: u32) { gen_dec32(ctx, &mut ctx.reg(r)) } + +fn gen_not16(ctx: &mut JitContext, dest_operand: &WasmLocal) { + let builder = &mut ctx.builder; + builder.get_local(dest_operand); + builder.const_i32(-1); + builder.xor_i32(); + codegen::gen_set_reg16_local(builder, dest_operand); +} +fn gen_not32(ctx: &mut JitContext, dest_operand: &WasmLocal) { + let builder = &mut ctx.builder; + builder.get_local(dest_operand); + builder.const_i32(-1); + builder.xor_i32(); + builder.set_local(dest_operand); +} + +fn gen_neg16(ctx: &mut JitContext, dest_operand: &WasmLocal) { + let builder = &mut ctx.builder; + builder.get_local(dest_operand); + builder.call_fn1_ret("neg16"); + codegen::gen_set_reg16_local(builder, dest_operand); +} +fn gen_neg32(ctx: &mut JitContext, dest_operand: &WasmLocal) { + let builder = &mut ctx.builder; + builder.const_i32(global_pointers::last_op1 as i32); + builder.const_i32(0); + builder.store_aligned_i32(0); + + builder.const_i32(0); + builder.get_local(&dest_operand); + builder.sub_i32(); + builder.set_local(dest_operand); + + codegen::gen_set_last_result(builder, &dest_operand); + codegen::gen_set_last_op_size_and_flags_changed(builder, OPSIZE_32, FLAGS_ALL | FLAG_SUB); +} + +pub fn instr16_06_jit(ctx: &mut JitContext) { + codegen::gen_get_sreg(ctx, regs::ES); + let sreg = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &sreg); + ctx.builder.free_local(sreg); +} +pub fn instr32_06_jit(ctx: &mut JitContext) { codegen::gen_push32_sreg(ctx, regs::ES) } + +pub fn instr16_0E_jit(ctx: &mut JitContext) { + codegen::gen_get_sreg(ctx, regs::CS); + let sreg = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &sreg); + ctx.builder.free_local(sreg); +} +pub fn instr32_0E_jit(ctx: &mut JitContext) { codegen::gen_push32_sreg(ctx, regs::CS) } + +pub fn instr16_16_jit(ctx: &mut JitContext) { + codegen::gen_get_sreg(ctx, regs::SS); + let sreg = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &sreg); + ctx.builder.free_local(sreg); +} +pub fn instr32_16_jit(ctx: &mut JitContext) { codegen::gen_push32_sreg(ctx, regs::SS) } + +pub fn instr16_1E_jit(ctx: &mut JitContext) { + codegen::gen_get_sreg(ctx, regs::DS); + let sreg = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &sreg); + ctx.builder.free_local(sreg); +} +pub fn instr32_1E_jit(ctx: &mut JitContext) { codegen::gen_push32_sreg(ctx, regs::DS) } + +pub fn instr16_40_jit(ctx: &mut JitContext) { gen_inc16_r(ctx, AX); } +pub fn instr32_40_jit(ctx: &mut JitContext) { gen_inc32_r(ctx, EAX); } +pub fn instr16_41_jit(ctx: &mut JitContext) { gen_inc16_r(ctx, CX); } +pub fn instr32_41_jit(ctx: &mut JitContext) { gen_inc32_r(ctx, ECX); } +pub fn instr16_42_jit(ctx: &mut JitContext) { gen_inc16_r(ctx, DX); } +pub fn instr32_42_jit(ctx: &mut JitContext) { gen_inc32_r(ctx, EDX); } +pub fn instr16_43_jit(ctx: &mut JitContext) { gen_inc16_r(ctx, BX); } +pub fn instr32_43_jit(ctx: &mut JitContext) { gen_inc32_r(ctx, EBX); } +pub fn instr16_44_jit(ctx: &mut JitContext) { gen_inc16_r(ctx, SP); } +pub fn instr32_44_jit(ctx: &mut JitContext) { gen_inc32_r(ctx, ESP); } +pub fn instr16_45_jit(ctx: &mut JitContext) { gen_inc16_r(ctx, BP); } +pub fn instr32_45_jit(ctx: &mut JitContext) { gen_inc32_r(ctx, EBP); } +pub fn instr16_46_jit(ctx: &mut JitContext) { gen_inc16_r(ctx, SI); } +pub fn instr32_46_jit(ctx: &mut JitContext) { gen_inc32_r(ctx, ESI); } +pub fn instr16_47_jit(ctx: &mut JitContext) { gen_inc16_r(ctx, DI); } +pub fn instr32_47_jit(ctx: &mut JitContext) { gen_inc32_r(ctx, EDI); } + +pub fn instr16_48_jit(ctx: &mut JitContext) { gen_dec16_r(ctx, AX); } +pub fn instr32_48_jit(ctx: &mut JitContext) { gen_dec32_r(ctx, EAX); } +pub fn instr16_49_jit(ctx: &mut JitContext) { gen_dec16_r(ctx, CX); } +pub fn instr32_49_jit(ctx: &mut JitContext) { gen_dec32_r(ctx, ECX); } +pub fn instr16_4A_jit(ctx: &mut JitContext) { gen_dec16_r(ctx, DX); } +pub fn instr32_4A_jit(ctx: &mut JitContext) { gen_dec32_r(ctx, EDX); } +pub fn instr16_4B_jit(ctx: &mut JitContext) { gen_dec16_r(ctx, BX); } +pub fn instr32_4B_jit(ctx: &mut JitContext) { gen_dec32_r(ctx, EBX); } +pub fn instr16_4C_jit(ctx: &mut JitContext) { gen_dec16_r(ctx, SP); } +pub fn instr32_4C_jit(ctx: &mut JitContext) { gen_dec32_r(ctx, ESP); } +pub fn instr16_4D_jit(ctx: &mut JitContext) { gen_dec16_r(ctx, BP); } +pub fn instr32_4D_jit(ctx: &mut JitContext) { gen_dec32_r(ctx, EBP); } +pub fn instr16_4E_jit(ctx: &mut JitContext) { gen_dec16_r(ctx, SI); } +pub fn instr32_4E_jit(ctx: &mut JitContext) { gen_dec32_r(ctx, ESI); } +pub fn instr16_4F_jit(ctx: &mut JitContext) { gen_dec16_r(ctx, DI); } +pub fn instr32_4F_jit(ctx: &mut JitContext) { gen_dec32_r(ctx, EDI); } + +pub fn instr16_50_jit(ctx: &mut JitContext) { push16_reg_jit(ctx, AX); } +pub fn instr32_50_jit(ctx: &mut JitContext) { push32_reg_jit(ctx, EAX); } +pub fn instr16_51_jit(ctx: &mut JitContext) { push16_reg_jit(ctx, CX); } +pub fn instr32_51_jit(ctx: &mut JitContext) { push32_reg_jit(ctx, ECX); } +pub fn instr16_52_jit(ctx: &mut JitContext) { push16_reg_jit(ctx, DX); } +pub fn instr32_52_jit(ctx: &mut JitContext) { push32_reg_jit(ctx, EDX); } +pub fn instr16_53_jit(ctx: &mut JitContext) { push16_reg_jit(ctx, BX); } +pub fn instr32_53_jit(ctx: &mut JitContext) { push32_reg_jit(ctx, EBX); } +pub fn instr16_54_jit(ctx: &mut JitContext) { push16_reg_jit(ctx, SP); } +pub fn instr32_54_jit(ctx: &mut JitContext) { push32_reg_jit(ctx, ESP); } +pub fn instr16_55_jit(ctx: &mut JitContext) { push16_reg_jit(ctx, BP); } +pub fn instr32_55_jit(ctx: &mut JitContext) { push32_reg_jit(ctx, EBP); } +pub fn instr16_56_jit(ctx: &mut JitContext) { push16_reg_jit(ctx, SI); } +pub fn instr32_56_jit(ctx: &mut JitContext) { push32_reg_jit(ctx, ESI); } +pub fn instr16_57_jit(ctx: &mut JitContext) { push16_reg_jit(ctx, DI); } +pub fn instr32_57_jit(ctx: &mut JitContext) { push32_reg_jit(ctx, EDI); } + +pub fn instr16_58_jit(ctx: &mut JitContext) { pop16_reg_jit(ctx, AX); } +pub fn instr32_58_jit(ctx: &mut JitContext) { pop32_reg_jit(ctx, EAX); } +pub fn instr16_59_jit(ctx: &mut JitContext) { pop16_reg_jit(ctx, CX); } +pub fn instr32_59_jit(ctx: &mut JitContext) { pop32_reg_jit(ctx, ECX); } +pub fn instr16_5A_jit(ctx: &mut JitContext) { pop16_reg_jit(ctx, DX); } +pub fn instr32_5A_jit(ctx: &mut JitContext) { pop32_reg_jit(ctx, EDX); } +pub fn instr16_5B_jit(ctx: &mut JitContext) { pop16_reg_jit(ctx, BX); } +pub fn instr32_5B_jit(ctx: &mut JitContext) { pop32_reg_jit(ctx, EBX); } +pub fn instr16_5C_jit(ctx: &mut JitContext) { pop16_reg_jit(ctx, SP); } +pub fn instr32_5C_jit(ctx: &mut JitContext) { pop32_reg_jit(ctx, ESP); } +pub fn instr16_5D_jit(ctx: &mut JitContext) { pop16_reg_jit(ctx, BP); } +pub fn instr32_5D_jit(ctx: &mut JitContext) { pop32_reg_jit(ctx, EBP); } +pub fn instr16_5E_jit(ctx: &mut JitContext) { pop16_reg_jit(ctx, SI); } +pub fn instr32_5E_jit(ctx: &mut JitContext) { pop32_reg_jit(ctx, ESI); } +pub fn instr16_5F_jit(ctx: &mut JitContext) { pop16_reg_jit(ctx, DI); } +pub fn instr32_5F_jit(ctx: &mut JitContext) { pop32_reg_jit(ctx, EDI); } + +pub fn instr16_68_jit(ctx: &mut JitContext, imm16: u32) { push16_imm_jit(ctx, imm16) } +pub fn instr32_68_jit(ctx: &mut JitContext, imm32: u32) { push32_imm_jit(ctx, imm32) } +pub fn instr16_6A_jit(ctx: &mut JitContext, imm16: u32) { push16_imm_jit(ctx, imm16) } +pub fn instr32_6A_jit(ctx: &mut JitContext, imm32: u32) { push32_imm_jit(ctx, imm32) } + +pub fn instr16_69_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm16: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + ctx.builder.const_i32(imm16 as i32); + ctx.builder.call_fn2_ret("imul_reg16"); + codegen::gen_set_reg16(ctx, r); +} +pub fn instr16_69_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm16: u32) { + codegen::gen_get_reg16(ctx, r1); + ctx.builder.const_i32(imm16 as i32); + ctx.builder.call_fn2_ret("imul_reg16"); + codegen::gen_set_reg16(ctx, r2); +} + +pub fn instr32_69_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm32: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + let value_local = ctx.builder.set_new_local(); + gen_imul3_reg32( + ctx.builder, + &ctx.register_locals[r as usize], + &value_local, + &LocalOrImmediate::Immediate(imm32 as i32), + ); + ctx.builder.free_local(value_local); +} +pub fn instr32_69_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm32: u32) { + gen_imul3_reg32( + ctx.builder, + &ctx.register_locals[r2 as usize], + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::Immediate(imm32 as i32), + ); +} + +pub fn instr16_6B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8s: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + ctx.builder.const_i32(imm8s as i32); + ctx.builder.call_fn2_ret("imul_reg16"); + codegen::gen_set_reg16(ctx, r); +} +pub fn instr16_6B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8s: u32) { + codegen::gen_get_reg16(ctx, r1); + ctx.builder.const_i32(imm8s as i32); + ctx.builder.call_fn2_ret("imul_reg16"); + codegen::gen_set_reg16(ctx, r2); +} + +pub fn instr32_6B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8s: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + let value_local = ctx.builder.set_new_local(); + gen_imul3_reg32( + ctx.builder, + &ctx.register_locals[r as usize], + &value_local, + &LocalOrImmediate::Immediate(imm8s as i32), + ); + ctx.builder.free_local(value_local); +} +pub fn instr32_6B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8s: u32) { + gen_imul3_reg32( + ctx.builder, + &ctx.register_locals[r2 as usize], + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::Immediate(imm8s as i32), + ); +} + +// Code for conditional jumps is generated automatically by the basic block codegen +pub fn instr16_70_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_70_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_71_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_71_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_72_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_72_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_73_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_73_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_74_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_74_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_75_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_75_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_76_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_76_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_77_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_77_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_78_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_78_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_79_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_79_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_7A_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_7A_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_7B_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_7B_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_7C_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_7C_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_7D_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_7D_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_7E_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_7E_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_7F_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_7F_jit(_ctx: &mut JitContext, _imm: u32) {} + +// loop/loopz/loopnz/jcxz: Conditional jump is generated in main loop +pub fn instr16_E0_jit(ctx: &mut JitContext, _imm: u32) { codegen::decr_exc_asize(ctx) } +pub fn instr32_E0_jit(ctx: &mut JitContext, _imm: u32) { codegen::decr_exc_asize(ctx) } +pub fn instr16_E1_jit(ctx: &mut JitContext, _imm: u32) { codegen::decr_exc_asize(ctx) } +pub fn instr32_E1_jit(ctx: &mut JitContext, _imm: u32) { codegen::decr_exc_asize(ctx) } +pub fn instr16_E2_jit(ctx: &mut JitContext, _imm: u32) { codegen::decr_exc_asize(ctx) } +pub fn instr32_E2_jit(ctx: &mut JitContext, _imm: u32) { codegen::decr_exc_asize(ctx) } +pub fn instr16_E3_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_E3_jit(_ctx: &mut JitContext, _imm: u32) {} + +define_instruction_read_write_mem8!(gen_add8, instr_80_0_mem_jit, instr_80_0_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_or8, instr_80_1_mem_jit, instr_80_1_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_adc8, instr_80_2_mem_jit, instr_80_2_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_sbb8, instr_80_3_mem_jit, instr_80_3_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_and8, instr_80_4_mem_jit, instr_80_4_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_sub8, instr_80_5_mem_jit, instr_80_5_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_xor8, instr_80_6_mem_jit, instr_80_6_reg_jit, ximm8); + +define_instruction_read_write_mem8!(gen_add8, instr_82_0_mem_jit, instr_82_0_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_or8, instr_82_1_mem_jit, instr_82_1_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_adc8, instr_82_2_mem_jit, instr_82_2_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_sbb8, instr_82_3_mem_jit, instr_82_3_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_and8, instr_82_4_mem_jit, instr_82_4_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_sub8, instr_82_5_mem_jit, instr_82_5_reg_jit, ximm8); +define_instruction_read_write_mem8!(gen_xor8, instr_82_6_mem_jit, instr_82_6_reg_jit, ximm8); + +define_instruction_read_write_mem16!("add16", instr16_81_0_mem_jit, instr16_81_0_reg_jit, imm16); +define_instruction_read_write_mem32!(gen_add32, instr32_81_0_mem_jit, instr32_81_0_reg_jit, imm32); + +define_instruction_read_write_mem16!("or16", instr16_81_1_mem_jit, instr16_81_1_reg_jit, imm16); +define_instruction_read_write_mem32!(gen_or32, instr32_81_1_mem_jit, instr32_81_1_reg_jit, imm32); + +define_instruction_read_write_mem16!("adc16", instr16_81_2_mem_jit, instr16_81_2_reg_jit, imm16); +define_instruction_read_write_mem32!(gen_adc32, instr32_81_2_mem_jit, instr32_81_2_reg_jit, imm32); + +define_instruction_read_write_mem16!("sbb16", instr16_81_3_mem_jit, instr16_81_3_reg_jit, imm16); +define_instruction_read_write_mem32!(gen_sbb32, instr32_81_3_mem_jit, instr32_81_3_reg_jit, imm32); + +define_instruction_read_write_mem16!("and16", instr16_81_4_mem_jit, instr16_81_4_reg_jit, imm16); +define_instruction_read_write_mem32!(gen_and32, instr32_81_4_mem_jit, instr32_81_4_reg_jit, imm32); + +define_instruction_read_write_mem16!("sub16", instr16_81_5_mem_jit, instr16_81_5_reg_jit, imm16); +define_instruction_read_write_mem32!(gen_sub32, instr32_81_5_mem_jit, instr32_81_5_reg_jit, imm32); + +define_instruction_read_write_mem16!("xor16", instr16_81_6_mem_jit, instr16_81_6_reg_jit, imm16); +define_instruction_read_write_mem32!(gen_xor32, instr32_81_6_mem_jit, instr32_81_6_reg_jit, imm32); + +define_instruction_read_write_mem16!( + "add16", + instr16_83_0_mem_jit, + instr16_83_0_reg_jit, + imm8s_16bits +); +define_instruction_read_write_mem32!(gen_add32, instr32_83_0_mem_jit, instr32_83_0_reg_jit, imm8s); + +define_instruction_read_write_mem16!( + "or16", + instr16_83_1_mem_jit, + instr16_83_1_reg_jit, + imm8s_16bits +); +define_instruction_read_write_mem32!(gen_or32, instr32_83_1_mem_jit, instr32_83_1_reg_jit, imm8s); + +define_instruction_read_write_mem16!( + "adc16", + instr16_83_2_mem_jit, + instr16_83_2_reg_jit, + imm8s_16bits +); +define_instruction_read_write_mem32!(gen_adc32, instr32_83_2_mem_jit, instr32_83_2_reg_jit, imm8s); + +define_instruction_read_write_mem16!( + "sbb16", + instr16_83_3_mem_jit, + instr16_83_3_reg_jit, + imm8s_16bits +); +define_instruction_read_write_mem32!(gen_sbb32, instr32_83_3_mem_jit, instr32_83_3_reg_jit, imm8s); + +define_instruction_read_write_mem16!( + "and16", + instr16_83_4_mem_jit, + instr16_83_4_reg_jit, + imm8s_16bits +); +define_instruction_read_write_mem32!(gen_and32, instr32_83_4_mem_jit, instr32_83_4_reg_jit, imm8s); + +define_instruction_read_write_mem16!( + "sub16", + instr16_83_5_mem_jit, + instr16_83_5_reg_jit, + imm8s_16bits +); +define_instruction_read_write_mem32!(gen_sub32, instr32_83_5_mem_jit, instr32_83_5_reg_jit, imm8s); + +define_instruction_read_write_mem16!( + "xor16", + instr16_83_6_mem_jit, + instr16_83_6_reg_jit, + imm8s_16bits +); +define_instruction_read_write_mem32!(gen_xor32, instr32_83_6_mem_jit, instr32_83_6_reg_jit, imm8s); + +define_instruction_read8!(gen_cmp8, instr_80_7_mem_jit, instr_80_7_reg_jit, imm8); +define_instruction_read16!(gen_cmp16, instr16_81_7_mem_jit, instr16_81_7_reg_jit, imm16); +define_instruction_read32!(gen_cmp32, instr32_81_7_mem_jit, instr32_81_7_reg_jit, imm32); + +define_instruction_read8!(gen_cmp8, instr_82_7_mem_jit, instr_82_7_reg_jit, imm8); + +define_instruction_read16!( + gen_cmp16, + instr16_83_7_mem_jit, + instr16_83_7_reg_jit, + imm8s_16bits +); +define_instruction_read32!(gen_cmp32, instr32_83_7_mem_jit, instr32_83_7_reg_jit, imm8s); + +define_instruction_read8!(gen_test8, instr_84_mem_jit, instr_84_reg_jit); +define_instruction_read16!(gen_test16, instr16_85_mem_jit, instr16_85_reg_jit); +define_instruction_read32!(gen_test32, instr32_85_mem_jit, instr32_85_reg_jit); + +pub fn instr_86_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::BYTE, &addr, &|ref mut ctx| { + codegen::gen_get_reg8(ctx, r); + let tmp = ctx.builder.set_new_local(); + codegen::gen_set_reg8(ctx, r); + ctx.builder.get_local(&tmp); + ctx.builder.free_local(tmp); + }); + }); +} +pub fn instr_86_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg8(ctx, r2); + let tmp = ctx.builder.set_new_local(); + codegen::gen_get_reg8(ctx, r1); + codegen::gen_set_reg8(ctx, r2); + ctx.builder.get_local(&tmp); + codegen::gen_set_reg8(ctx, r1); + ctx.builder.free_local(tmp); +} +pub fn instr16_87_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::WORD, &addr, &|ref mut ctx| { + codegen::gen_get_reg16(ctx, r); + let tmp = ctx.builder.set_new_local(); + codegen::gen_set_reg16(ctx, r); + ctx.builder.get_local(&tmp); + ctx.builder.free_local(tmp); + }); + }); +} +pub fn instr32_87_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &addr, &|ref mut ctx| { + codegen::gen_get_reg32(ctx, r); + let tmp = ctx.builder.set_new_local(); + codegen::gen_set_reg32(ctx, r); + ctx.builder.get_local(&tmp); + ctx.builder.free_local(tmp); + }); + }); +} +pub fn instr16_87_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r2); + let tmp = ctx.builder.set_new_local(); + codegen::gen_get_reg16(ctx, r1); + codegen::gen_set_reg16(ctx, r2); + ctx.builder.get_local(&tmp); + codegen::gen_set_reg16(ctx, r1); + ctx.builder.free_local(tmp); +} +pub fn instr32_87_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg32(ctx, r2); + let tmp = ctx.builder.set_new_local(); + codegen::gen_get_reg32(ctx, r1); + codegen::gen_set_reg32(ctx, r2); + ctx.builder.get_local(&tmp); + codegen::gen_set_reg32(ctx, r1); + ctx.builder.free_local(tmp); +} + +pub fn instr_88_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_get_reg8(ctx, r); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write8(ctx, &addr, &value_local); + ctx.builder.free_local(value_local); + }); +} +pub fn instr_88_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_set_reg8_r(ctx, r1, r2); +} + +pub fn instr16_89_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_write16(ctx, addr, &ctx.reg(r)); + }); +} +pub fn instr16_89_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_set_reg16_r(ctx, r1, r2); +} +pub fn instr32_89_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_safe_write32(ctx, &addr, &ctx.reg(r)); + }); +} +pub fn instr32_89_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_set_reg32_r(ctx, r1, r2); +} + +pub fn instr_8A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + // Pseudo: reg8[r] = safe_read8(modrm_resolve(modrm_byte)); + codegen::gen_modrm_resolve_safe_read8(ctx, modrm_byte); + codegen::gen_set_reg8_unmasked(ctx, r); +} +pub fn instr_8A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_set_reg8_r(ctx, r2, r1); +} + +pub fn instr16_8B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::gen_set_reg16_unmasked(ctx, r); +} +pub fn instr16_8B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_set_reg16_r(ctx, r2, r1); +} +pub fn instr32_8B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + codegen::gen_set_reg32(ctx, r); +} +pub fn instr32_8B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_set_reg32_r(ctx, r2, r1); +} + +pub fn instr16_8C_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + if r >= 6 { + codegen::gen_trigger_ud(ctx); + } + else { + codegen::gen_get_sreg(ctx, r); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write16(ctx, &address_local, &value_local); + ctx.builder.free_local(value_local); + } + ctx.builder.free_local(address_local); +} +pub fn instr32_8C_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + if r >= 6 { + codegen::gen_trigger_ud(ctx); + } + else { + codegen::gen_get_sreg(ctx, r); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write16(ctx, &address_local, &value_local); + ctx.builder.free_local(value_local); + } + ctx.builder.free_local(address_local); +} +pub fn instr16_8C_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + if r2 >= 6 { + codegen::gen_trigger_ud(ctx); + } + else { + codegen::gen_get_sreg(ctx, r2); + codegen::gen_set_reg16(ctx, r1); + } +} +pub fn instr32_8C_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + if r2 >= 6 { + codegen::gen_trigger_ud(ctx); + } + else { + codegen::gen_get_sreg(ctx, r2); + codegen::gen_set_reg32(ctx, r1); + } +} + +pub fn instr16_8D_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, reg: u32) { + ctx.cpu.prefixes |= SEG_PREFIX_ZERO; + codegen::gen_modrm_resolve(ctx, modrm_byte); + codegen::gen_set_reg16(ctx, reg); +} +pub fn instr32_8D_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, reg: u32) { + if !modrm_byte.is_nop(reg) { + ctx.cpu.prefixes |= SEG_PREFIX_ZERO; + codegen::gen_modrm_resolve(ctx, modrm_byte); + codegen::gen_set_reg32(ctx, reg); + } +} + +pub fn instr16_8D_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} + +pub fn instr32_8D_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} + +pub fn instr16_8F_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + // before gen_modrm_resolve, update esp to the new value + codegen::gen_adjust_stack_reg(ctx, 2); + + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + + // pop takes care of updating esp, so undo the previous change + codegen::gen_adjust_stack_reg(ctx, (-2i32) as u32); + codegen::gen_pop16(ctx); + let value_local = ctx.builder.set_new_local(); + + // undo the esp change of pop, as safe_write16 can fail + codegen::gen_adjust_stack_reg(ctx, (-2i32) as u32); + + codegen::gen_safe_write16(ctx, &address_local, &value_local); + + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); + + // finally, actually update esp + codegen::gen_adjust_stack_reg(ctx, 2); +} +pub fn instr16_8F_0_reg_jit(ctx: &mut JitContext, r: u32) { pop16_reg_jit(ctx, r); } +pub fn instr32_8F_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_adjust_stack_reg(ctx, 4); + + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + + codegen::gen_adjust_stack_reg(ctx, (-4i32) as u32); + codegen::gen_pop32s(ctx); + let value_local = ctx.builder.set_new_local(); + codegen::gen_adjust_stack_reg(ctx, (-4i32) as u32); + + codegen::gen_safe_write32(ctx, &address_local, &value_local); + + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); + + codegen::gen_adjust_stack_reg(ctx, 4); +} +pub fn instr32_8F_0_reg_jit(ctx: &mut JitContext, r: u32) { pop32_reg_jit(ctx, r); } + +define_instruction_read_write_mem16!( + "rol16", + instr16_C1_0_mem_jit, + instr16_C1_0_reg_jit, + imm8_5bits +); +define_instruction_read_write_mem32!( + gen_rol32, + instr32_C1_0_mem_jit, + instr32_C1_0_reg_jit, + imm8_5bits +); + +define_instruction_read_write_mem16!( + "ror16", + instr16_C1_1_mem_jit, + instr16_C1_1_reg_jit, + imm8_5bits +); +define_instruction_read_write_mem32!( + gen_ror32, + instr32_C1_1_mem_jit, + instr32_C1_1_reg_jit, + imm8_5bits +); + +define_instruction_read_write_mem16!( + "rcl16", + instr16_C1_2_mem_jit, + instr16_C1_2_reg_jit, + imm8_5bits +); +define_instruction_read_write_mem32!( + gen_rcl32, + instr32_C1_2_mem_jit, + instr32_C1_2_reg_jit, + imm8_5bits +); + +define_instruction_read_write_mem16!( + "rcr16", + instr16_C1_3_mem_jit, + instr16_C1_3_reg_jit, + imm8_5bits +); +define_instruction_read_write_mem32!( + gen_rcr32, + instr32_C1_3_mem_jit, + instr32_C1_3_reg_jit, + imm8_5bits +); + +define_instruction_read_write_mem16!( + "shl16", + instr16_C1_4_mem_jit, + instr16_C1_4_reg_jit, + imm8_5bits +); +define_instruction_read_write_mem32!( + gen_shl32, + instr32_C1_4_mem_jit, + instr32_C1_4_reg_jit, + imm8_5bits +); + +define_instruction_read_write_mem16!( + "shr16", + instr16_C1_5_mem_jit, + instr16_C1_5_reg_jit, + imm8_5bits +); +define_instruction_read_write_mem32!( + gen_shr32, + instr32_C1_5_mem_jit, + instr32_C1_5_reg_jit, + imm8_5bits +); + +define_instruction_read_write_mem16!( + "shl16", + instr16_C1_6_mem_jit, + instr16_C1_6_reg_jit, + imm8_5bits +); +define_instruction_read_write_mem32!( + gen_shl32, + instr32_C1_6_mem_jit, + instr32_C1_6_reg_jit, + imm8_5bits +); + +define_instruction_read_write_mem16!( + "sar16", + instr16_C1_7_mem_jit, + instr16_C1_7_reg_jit, + imm8_5bits +); +define_instruction_read_write_mem32!( + gen_sar32, + instr32_C1_7_mem_jit, + instr32_C1_7_reg_jit, + imm8_5bits +); + +pub fn instr16_E8_jit(ctx: &mut JitContext, _imm: u32) { + codegen::gen_get_real_eip(ctx); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &value_local); + ctx.builder.free_local(value_local); +} +pub fn instr32_E8_jit(ctx: &mut JitContext, _imm: u32) { + codegen::gen_get_real_eip(ctx); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push32(ctx, &value_local); + ctx.builder.free_local(value_local); +} + +pub fn instr16_E9_jit(_ctx: &mut JitContext, _imm: u32) { + // +} +pub fn instr32_E9_jit(_ctx: &mut JitContext, _imm: u32) { + // +} + +pub fn instr16_C2_jit(ctx: &mut JitContext, imm16: u32) { + ctx.builder.const_i32(0); + codegen::gen_pop16(ctx); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); + codegen::gen_adjust_stack_reg(ctx, imm16); +} + +pub fn instr32_C2_jit(ctx: &mut JitContext, imm16: u32) { + ctx.builder.const_i32(0); + codegen::gen_pop32s(ctx); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); + codegen::gen_adjust_stack_reg(ctx, imm16); +} + +pub fn instr16_C3_jit(ctx: &mut JitContext) { + ctx.builder.const_i32(0); + codegen::gen_pop16(ctx); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); +} + +pub fn instr32_C3_jit(ctx: &mut JitContext) { + ctx.builder.const_i32(0); + codegen::gen_pop32s(ctx); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); +} + +pub fn instr16_C9_jit(ctx: &mut JitContext) { codegen::gen_leave(ctx, false); } +pub fn instr32_C9_jit(ctx: &mut JitContext) { codegen::gen_leave(ctx, true); } + +pub fn gen_mov_reg8_imm(ctx: &mut JitContext, r: u32, imm: u32) { + ctx.builder.const_i32(imm as i32); + codegen::gen_set_reg8_unmasked(ctx, r); +} + +pub fn instr_B0_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg8_imm(ctx, 0, imm) } +pub fn instr_B1_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg8_imm(ctx, 1, imm) } +pub fn instr_B2_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg8_imm(ctx, 2, imm) } +pub fn instr_B3_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg8_imm(ctx, 3, imm) } +pub fn instr_B4_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg8_imm(ctx, 4, imm) } +pub fn instr_B5_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg8_imm(ctx, 5, imm) } +pub fn instr_B6_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg8_imm(ctx, 6, imm) } +pub fn instr_B7_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg8_imm(ctx, 7, imm) } + +pub fn gen_mov_reg16_imm(ctx: &mut JitContext, r: u32, imm: u32) { + ctx.builder.const_i32(imm as i32); + codegen::gen_set_reg16_unmasked(ctx, r); +} + +pub fn instr16_B8_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg16_imm(ctx, 0, imm) } +pub fn instr16_B9_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg16_imm(ctx, 1, imm) } +pub fn instr16_BA_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg16_imm(ctx, 2, imm) } +pub fn instr16_BB_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg16_imm(ctx, 3, imm) } +pub fn instr16_BC_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg16_imm(ctx, 4, imm) } +pub fn instr16_BD_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg16_imm(ctx, 5, imm) } +pub fn instr16_BE_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg16_imm(ctx, 6, imm) } +pub fn instr16_BF_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg16_imm(ctx, 7, imm) } + +pub fn gen_mov_reg32_imm(ctx: &mut JitContext, r: u32, imm: u32) { + ctx.builder.const_i32(imm as i32); + codegen::gen_set_reg32(ctx, r); +} + +pub fn instr32_B8_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg32_imm(ctx, 0, imm) } +pub fn instr32_B9_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg32_imm(ctx, 1, imm) } +pub fn instr32_BA_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg32_imm(ctx, 2, imm) } +pub fn instr32_BB_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg32_imm(ctx, 3, imm) } +pub fn instr32_BC_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg32_imm(ctx, 4, imm) } +pub fn instr32_BD_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg32_imm(ctx, 5, imm) } +pub fn instr32_BE_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg32_imm(ctx, 6, imm) } +pub fn instr32_BF_jit(ctx: &mut JitContext, imm: u32) { gen_mov_reg32_imm(ctx, 7, imm) } + +define_instruction_read_write_mem8!("rol8", instr_C0_0_mem_jit, instr_C0_0_reg_jit, imm8_5bits); +define_instruction_read_write_mem8!("ror8", instr_C0_1_mem_jit, instr_C0_1_reg_jit, imm8_5bits); +define_instruction_read_write_mem8!("rcl8", instr_C0_2_mem_jit, instr_C0_2_reg_jit, imm8_5bits); +define_instruction_read_write_mem8!("rcr8", instr_C0_3_mem_jit, instr_C0_3_reg_jit, imm8_5bits); +define_instruction_read_write_mem8!("shl8", instr_C0_4_mem_jit, instr_C0_4_reg_jit, imm8_5bits); +define_instruction_read_write_mem8!("shr8", instr_C0_5_mem_jit, instr_C0_5_reg_jit, imm8_5bits); +define_instruction_read_write_mem8!("shl8", instr_C0_6_mem_jit, instr_C0_6_reg_jit, imm8_5bits); +define_instruction_read_write_mem8!("sar8", instr_C0_7_mem_jit, instr_C0_7_reg_jit, imm8_5bits); + +define_instruction_read_write_mem8!("rol8", instr_D0_0_mem_jit, instr_D0_0_reg_jit, constant_one); +define_instruction_read_write_mem8!("ror8", instr_D0_1_mem_jit, instr_D0_1_reg_jit, constant_one); +define_instruction_read_write_mem8!("rcl8", instr_D0_2_mem_jit, instr_D0_2_reg_jit, constant_one); +define_instruction_read_write_mem8!("rcr8", instr_D0_3_mem_jit, instr_D0_3_reg_jit, constant_one); +define_instruction_read_write_mem8!("shl8", instr_D0_4_mem_jit, instr_D0_4_reg_jit, constant_one); +define_instruction_read_write_mem8!("shr8", instr_D0_5_mem_jit, instr_D0_5_reg_jit, constant_one); +define_instruction_read_write_mem8!("shl8", instr_D0_6_mem_jit, instr_D0_6_reg_jit, constant_one); +define_instruction_read_write_mem8!("sar8", instr_D0_7_mem_jit, instr_D0_7_reg_jit, constant_one); + +define_instruction_read_write_mem16!( + "rol16", + instr16_D1_0_mem_jit, + instr16_D1_0_reg_jit, + constant_one +); +define_instruction_read_write_mem32!( + gen_rol32, + instr32_D1_0_mem_jit, + instr32_D1_0_reg_jit, + constant_one +); + +define_instruction_read_write_mem16!( + "ror16", + instr16_D1_1_mem_jit, + instr16_D1_1_reg_jit, + constant_one +); +define_instruction_read_write_mem32!( + gen_ror32, + instr32_D1_1_mem_jit, + instr32_D1_1_reg_jit, + constant_one +); + +define_instruction_read_write_mem16!( + "rcl16", + instr16_D1_2_mem_jit, + instr16_D1_2_reg_jit, + constant_one +); +define_instruction_read_write_mem32!( + gen_rcl32, + instr32_D1_2_mem_jit, + instr32_D1_2_reg_jit, + constant_one +); + +define_instruction_read_write_mem16!( + "rcr16", + instr16_D1_3_mem_jit, + instr16_D1_3_reg_jit, + constant_one +); +define_instruction_read_write_mem32!( + gen_rcr32, + instr32_D1_3_mem_jit, + instr32_D1_3_reg_jit, + constant_one +); + +define_instruction_read_write_mem16!( + "shl16", + instr16_D1_4_mem_jit, + instr16_D1_4_reg_jit, + constant_one +); +define_instruction_read_write_mem32!( + gen_shl32, + instr32_D1_4_mem_jit, + instr32_D1_4_reg_jit, + constant_one +); + +define_instruction_read_write_mem16!( + "shr16", + instr16_D1_5_mem_jit, + instr16_D1_5_reg_jit, + constant_one +); +define_instruction_read_write_mem32!( + gen_shr32, + instr32_D1_5_mem_jit, + instr32_D1_5_reg_jit, + constant_one +); + +define_instruction_read_write_mem16!( + "shl16", + instr16_D1_6_mem_jit, + instr16_D1_6_reg_jit, + constant_one +); +define_instruction_read_write_mem32!( + gen_shl32, + instr32_D1_6_mem_jit, + instr32_D1_6_reg_jit, + constant_one +); + +define_instruction_read_write_mem16!( + "sar16", + instr16_D1_7_mem_jit, + instr16_D1_7_reg_jit, + constant_one +); +define_instruction_read_write_mem32!( + gen_sar32, + instr32_D1_7_mem_jit, + instr32_D1_7_reg_jit, + constant_one +); + +define_instruction_read_write_mem8!("rol8", instr_D2_0_mem_jit, instr_D2_0_reg_jit, cl); +define_instruction_read_write_mem8!("ror8", instr_D2_1_mem_jit, instr_D2_1_reg_jit, cl); +define_instruction_read_write_mem8!("rcl8", instr_D2_2_mem_jit, instr_D2_2_reg_jit, cl); +define_instruction_read_write_mem8!("rcr8", instr_D2_3_mem_jit, instr_D2_3_reg_jit, cl); +define_instruction_read_write_mem8!("shl8", instr_D2_4_mem_jit, instr_D2_4_reg_jit, cl); +define_instruction_read_write_mem8!("shr8", instr_D2_5_mem_jit, instr_D2_5_reg_jit, cl); +define_instruction_read_write_mem8!("shl8", instr_D2_6_mem_jit, instr_D2_6_reg_jit, cl); +define_instruction_read_write_mem8!("sar8", instr_D2_7_mem_jit, instr_D2_7_reg_jit, cl); + +define_instruction_read_write_mem16!("rol16", instr16_D3_0_mem_jit, instr16_D3_0_reg_jit, cl); +define_instruction_read_write_mem32!(gen_rol32, instr32_D3_0_mem_jit, instr32_D3_0_reg_jit, cl); + +define_instruction_read_write_mem16!("ror16", instr16_D3_1_mem_jit, instr16_D3_1_reg_jit, cl); +define_instruction_read_write_mem32!(gen_ror32, instr32_D3_1_mem_jit, instr32_D3_1_reg_jit, cl); + +define_instruction_read_write_mem16!("rcl16", instr16_D3_2_mem_jit, instr16_D3_2_reg_jit, cl); +define_instruction_read_write_mem32!(gen_rcl32, instr32_D3_2_mem_jit, instr32_D3_2_reg_jit, cl); + +define_instruction_read_write_mem16!("rcr16", instr16_D3_3_mem_jit, instr16_D3_3_reg_jit, cl); +define_instruction_read_write_mem32!(gen_rcr32, instr32_D3_3_mem_jit, instr32_D3_3_reg_jit, cl); + +define_instruction_read_write_mem16!("shl16", instr16_D3_4_mem_jit, instr16_D3_4_reg_jit, cl); +define_instruction_read_write_mem32!(gen_shl32, instr32_D3_4_mem_jit, instr32_D3_4_reg_jit, cl); + +define_instruction_read_write_mem16!("shr16", instr16_D3_5_mem_jit, instr16_D3_5_reg_jit, cl); +define_instruction_read_write_mem32!(gen_shr32, instr32_D3_5_mem_jit, instr32_D3_5_reg_jit, cl); + +define_instruction_read_write_mem16!("shl16", instr16_D3_6_mem_jit, instr16_D3_6_reg_jit, cl); +define_instruction_read_write_mem32!(gen_shl32, instr32_D3_6_mem_jit, instr32_D3_6_reg_jit, cl); + +define_instruction_read_write_mem16!("sar16", instr16_D3_7_mem_jit, instr16_D3_7_reg_jit, cl); +define_instruction_read_write_mem32!(gen_sar32, instr32_D3_7_mem_jit, instr32_D3_7_reg_jit, cl); + +pub fn instr_D7_jit(ctx: &mut JitContext) { + if ctx.cpu.asize_32() { + codegen::gen_get_reg32(ctx, regs::EBX); + } + else { + codegen::gen_get_reg16(ctx, regs::BX); + } + codegen::gen_get_reg8(ctx, regs::AL); + ctx.builder.add_i32(); + if !ctx.cpu.asize_32() { + ctx.builder.const_i32(0xFFFF); + ctx.builder.and_i32(); + } + jit_add_seg_offset(ctx, regs::DS); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read8(ctx, &address_local); + ctx.builder.free_local(address_local); + codegen::gen_set_reg8(ctx, regs::AL); +} + +fn instr_group_D8_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, op: &str) { + ctx.builder.const_i32(0); + codegen::gen_fpu_load_m32(ctx, modrm_byte); + ctx.builder.call_fn3_i32_i64_i32(op) +} +fn instr_group_D8_reg_jit(ctx: &mut JitContext, r: u32, op: &str) { + ctx.builder.const_i32(0); + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn3_i32_i64_i32(op) +} + +pub fn instr_D8_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_D8_mem_jit(ctx, modrm_byte, "fpu_fadd") +} +pub fn instr_D8_0_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_D8_reg_jit(ctx, r, "fpu_fadd") +} +pub fn instr_D8_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_D8_mem_jit(ctx, modrm_byte, "fpu_fmul") +} +pub fn instr_D8_1_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_D8_reg_jit(ctx, r, "fpu_fmul") +} +pub fn instr_D8_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_m32(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_fcom") +} +pub fn instr_D8_2_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn2_i64_i32("fpu_fcom") +} +pub fn instr_D8_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_m32(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_fcomp") +} +pub fn instr_D8_3_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn2_i64_i32("fpu_fcomp") +} +pub fn instr_D8_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_D8_mem_jit(ctx, modrm_byte, "fpu_fsub") +} +pub fn instr_D8_4_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_D8_reg_jit(ctx, r, "fpu_fsub") +} +pub fn instr_D8_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_D8_mem_jit(ctx, modrm_byte, "fpu_fsubr") +} +pub fn instr_D8_5_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_D8_reg_jit(ctx, r, "fpu_fsubr") +} +pub fn instr_D8_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_D8_mem_jit(ctx, modrm_byte, "fpu_fdiv") +} +pub fn instr_D8_6_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_D8_reg_jit(ctx, r, "fpu_fdiv") +} +pub fn instr_D8_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_D8_mem_jit(ctx, modrm_byte, "fpu_fdivr") +} +pub fn instr_D8_7_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_D8_reg_jit(ctx, r, "fpu_fdivr") +} + +pub fn instr16_D9_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_m32(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_push"); +} +pub fn instr16_D9_0_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn2_i64_i32("fpu_push"); +} +pub fn instr32_D9_0_reg_jit(ctx: &mut JitContext, r: u32) { instr16_D9_0_reg_jit(ctx, r) } +pub fn instr32_D9_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_D9_0_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_D9_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + codegen::gen_trigger_ud(ctx); +} +pub fn instr16_D9_1_reg_jit(ctx: &mut JitContext, r: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn1("fpu_fxch"); +} +pub fn instr32_D9_1_reg_jit(ctx: &mut JitContext, r: u32) { instr16_D9_1_reg_jit(ctx, r) } +pub fn instr32_D9_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_D9_1_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_D9_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_fpu_get_sti(ctx, 0); + ctx.builder.call_fn2_i64_i32_ret("f80_to_f32"); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); +} +pub fn instr16_D9_2_reg_jit(ctx: &mut JitContext, r: u32) { + if r != 0 { + codegen::gen_trigger_ud(ctx); + } +} +pub fn instr32_D9_2_reg_jit(ctx: &mut JitContext, r: u32) { instr16_D9_2_reg_jit(ctx, r) } +pub fn instr32_D9_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_D9_2_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_D9_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_fpu_get_sti(ctx, 0); + ctx.builder.call_fn2_i64_i32_ret("f80_to_f32"); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); + codegen::gen_fn0_const(ctx.builder, "fpu_pop"); +} +pub fn instr16_D9_3_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "fpu_fstp", r); +} +pub fn instr32_D9_3_reg_jit(ctx: &mut JitContext, r: u32) { instr16_D9_3_reg_jit(ctx, r) } +pub fn instr32_D9_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_D9_3_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_D9_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + + codegen::gen_set_previous_eip_offset_from_eip_with_low_bits( + ctx.builder, + ctx.start_of_current_instruction as i32 & 0xFFF, + ); + + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1("fpu_fldenv32"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + + codegen::gen_get_page_fault(ctx.builder); + ctx.builder.if_void(); + codegen::gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.br(ctx.exit_label); + ctx.builder.block_end(); +} +pub fn instr16_D9_4_reg_jit(ctx: &mut JitContext, r: u32) { + match r { + 0 | 1 | 4 | 5 => { + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn1("instr16_D9_4_reg"); + }, + _ => codegen::gen_trigger_ud(ctx), + } +} +pub fn instr32_D9_4_reg_jit(ctx: &mut JitContext, r: u32) { instr16_D9_4_reg_jit(ctx, r) } +pub fn instr32_D9_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_D9_4_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_D9_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + ctx.builder.call_fn1("set_control_word"); +} +pub fn instr16_D9_5_reg_jit(ctx: &mut JitContext, r: u32) { + if r == 7 { + codegen::gen_trigger_ud(ctx); + } + else { + codegen::gen_fn1_const(ctx.builder, "instr16_D9_5_reg", r); + } +} +pub fn instr32_D9_5_reg_jit(ctx: &mut JitContext, r: u32) { instr16_D9_5_reg_jit(ctx, r) } +pub fn instr32_D9_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_D9_5_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_D9_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + + codegen::gen_set_previous_eip_offset_from_eip_with_low_bits( + ctx.builder, + ctx.start_of_current_instruction as i32 & 0xFFF, + ); + + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1("fpu_fstenv32"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + + codegen::gen_get_page_fault(ctx.builder); + ctx.builder.if_void(); + codegen::gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.br(ctx.exit_label); + ctx.builder.block_end(); +} +pub fn instr16_D9_6_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "instr16_D9_6_reg", r); +} +pub fn instr32_D9_6_reg_jit(ctx: &mut JitContext, r: u32) { instr16_D9_6_reg_jit(ctx, r) } +pub fn instr32_D9_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_D9_6_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_D9_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + ctx.builder + .const_i32(global_pointers::fpu_control_word as i32); + ctx.builder.load_aligned_u16(0); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write16(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); +} +pub fn instr16_D9_7_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "instr16_D9_7_reg", r); +} +pub fn instr32_D9_7_reg_jit(ctx: &mut JitContext, r: u32) { instr16_D9_7_reg_jit(ctx, r) } +pub fn instr32_D9_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_D9_7_mem_jit(ctx, modrm_byte) +} + +pub fn instr_DA_0_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "instr_DA_0_reg", r); +} +pub fn instr_DA_1_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "instr_DA_1_reg", r); +} +pub fn instr_DA_2_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "instr_DA_2_reg", r); +} +pub fn instr_DA_3_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "instr_DA_3_reg", r); +} +pub fn instr_DA_4_reg_jit(ctx: &mut JitContext, _r: u32) { codegen::gen_trigger_ud(ctx) } +pub fn instr_DA_5_reg_jit(ctx: &mut JitContext, r: u32) { + if r == 1 { + codegen::gen_fn0_const(ctx.builder, "fpu_fucompp") + } + else { + codegen::gen_trigger_ud(ctx) + } +} +pub fn instr_DA_6_reg_jit(ctx: &mut JitContext, _r: u32) { codegen::gen_trigger_ud(ctx) } +pub fn instr_DA_7_reg_jit(ctx: &mut JitContext, _r: u32) { codegen::gen_trigger_ud(ctx) } + +pub fn instr_group_DA_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, op: &str) { + ctx.builder.const_i32(0); + codegen::gen_fpu_load_i32(ctx, modrm_byte); + ctx.builder.call_fn3_i32_i64_i32(op) +} +pub fn instr_DA_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DA_mem_jit(ctx, modrm_byte, "fpu_fadd") +} +pub fn instr_DA_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DA_mem_jit(ctx, modrm_byte, "fpu_fmul") +} +pub fn instr_DA_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_i32(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_fcom") +} +pub fn instr_DA_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_i32(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_fcomp") +} +pub fn instr_DA_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DA_mem_jit(ctx, modrm_byte, "fpu_fsub") +} +pub fn instr_DA_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DA_mem_jit(ctx, modrm_byte, "fpu_fsubr") +} +pub fn instr_DA_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DA_mem_jit(ctx, modrm_byte, "fpu_fdiv") +} +pub fn instr_DA_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DA_mem_jit(ctx, modrm_byte, "fpu_fdivr") +} + +pub fn instr_DB_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_i32(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_push"); +} +pub fn instr_DB_0_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "instr_DB_0_reg", r); +} + +pub fn instr_DB_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_fpu_get_sti(ctx, 0); + ctx.builder.call_fn2_i64_i32_ret("fpu_convert_to_i32"); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); +} +pub fn instr_DB_2_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "instr_DB_2_reg", r); +} +pub fn instr_DB_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_fpu_get_sti(ctx, 0); + ctx.builder.call_fn2_i64_i32_ret("fpu_convert_to_i32"); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); + codegen::gen_fn0_const(ctx.builder, "fpu_pop"); +} +pub fn instr_DB_3_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "instr_DB_3_reg", r); +} + +pub fn instr_DB_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + + codegen::gen_set_previous_eip_offset_from_eip_with_low_bits( + ctx.builder, + ctx.start_of_current_instruction as i32 & 0xFFF, + ); + + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1("fpu_fldm80"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + + codegen::gen_get_page_fault(ctx.builder); + ctx.builder.if_void(); + codegen::gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.br(ctx.exit_label); + ctx.builder.block_end(); +} +pub fn instr_DB_5_reg_jit(ctx: &mut JitContext, r: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn1("fpu_fucomi"); +} + +pub fn instr_DB_6_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_DB_6_reg_jit(ctx: &mut JitContext, r: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn1("fpu_fcomi"); +} + +fn instr_group_DC_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, op: &str) { + ctx.builder.const_i32(0); + codegen::gen_fpu_load_m64(ctx, modrm_byte); + ctx.builder.call_fn3_i32_i64_i32(op) +} +fn instr_group_DC_reg_jit(ctx: &mut JitContext, r: u32, op: &str) { + ctx.builder.const_i32(r as i32); + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn3_i32_i64_i32(op) +} + +pub fn instr_DC_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DC_mem_jit(ctx, modrm_byte, "fpu_fadd") +} +pub fn instr_DC_0_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DC_reg_jit(ctx, r, "fpu_fadd") +} +pub fn instr_DC_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DC_mem_jit(ctx, modrm_byte, "fpu_fmul") +} +pub fn instr_DC_1_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DC_reg_jit(ctx, r, "fpu_fmul") +} +pub fn instr_DC_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_m64(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_fcom") +} +pub fn instr_DC_2_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn2_i64_i32("fpu_fcom") +} +pub fn instr_DC_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_m64(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_fcomp") +} +pub fn instr_DC_3_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn2_i64_i32("fpu_fcomp") +} +pub fn instr_DC_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DC_mem_jit(ctx, modrm_byte, "fpu_fsub") +} +pub fn instr_DC_4_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DC_reg_jit(ctx, r, "fpu_fsub") +} +pub fn instr_DC_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DC_mem_jit(ctx, modrm_byte, "fpu_fsubr") +} +pub fn instr_DC_5_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DC_reg_jit(ctx, r, "fpu_fsubr") +} +pub fn instr_DC_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DC_mem_jit(ctx, modrm_byte, "fpu_fdiv") +} +pub fn instr_DC_6_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DC_reg_jit(ctx, r, "fpu_fdiv") +} +pub fn instr_DC_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DC_mem_jit(ctx, modrm_byte, "fpu_fdivr") +} +pub fn instr_DC_7_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DC_reg_jit(ctx, r, "fpu_fdivr") +} + +pub fn instr16_DD_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_m64(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_push"); +} +pub fn instr16_DD_0_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "fpu_ffree", r); +} +pub fn instr32_DD_0_reg_jit(ctx: &mut JitContext, r: u32) { instr16_DD_0_reg_jit(ctx, r) } +pub fn instr32_DD_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_DD_0_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_DD_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_fpu_get_sti(ctx, 0); + ctx.builder.call_fn2_i64_i32_ret_i64("f80_to_f64"); + let value_local = ctx.builder.set_new_local_i64(); + codegen::gen_safe_write64(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local_i64(value_local); +} +pub fn instr16_DD_2_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "fpu_fst", r); +} +pub fn instr32_DD_2_reg_jit(ctx: &mut JitContext, r: u32) { instr16_DD_2_reg_jit(ctx, r) } +pub fn instr32_DD_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_DD_2_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_DD_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_fpu_get_sti(ctx, 0); + ctx.builder.call_fn2_i64_i32_ret_i64("f80_to_f64"); + let value_local = ctx.builder.set_new_local_i64(); + codegen::gen_safe_write64(ctx, &address_local, &value_local); + codegen::gen_fn0_const(ctx.builder, "fpu_pop"); + ctx.builder.free_local(address_local); + ctx.builder.free_local_i64(value_local); +} +pub fn instr16_DD_3_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "fpu_fstp", r); +} +pub fn instr32_DD_3_reg_jit(ctx: &mut JitContext, r: u32) { instr16_DD_3_reg_jit(ctx, r) } +pub fn instr32_DD_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_DD_3_mem_jit(ctx, modrm_byte) +} + +pub fn instr16_DD_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + codegen::gen_trigger_ud(ctx); +} +pub fn instr16_DD_5_reg_jit(ctx: &mut JitContext, r: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn1("fpu_fucomp"); +} +pub fn instr32_DD_5_reg_jit(ctx: &mut JitContext, r: u32) { instr16_DD_5_reg_jit(ctx, r) } +pub fn instr32_DD_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_DD_5_mem_jit(ctx, modrm_byte) +} + +fn instr_group_DE_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, op: &str) { + ctx.builder.const_i32(0); + codegen::gen_fpu_load_i16(ctx, modrm_byte); + ctx.builder.call_fn3_i32_i64_i32(op) +} +fn instr_group_DE_reg_jit(ctx: &mut JitContext, r: u32, op: &str) { + ctx.builder.const_i32(r as i32); + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn3_i32_i64_i32(op); + codegen::gen_fn0_const(ctx.builder, "fpu_pop") +} + +pub fn instr_DE_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DE_mem_jit(ctx, modrm_byte, "fpu_fadd") +} +pub fn instr_DE_0_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DE_reg_jit(ctx, r, "fpu_fadd") +} +pub fn instr_DE_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DE_mem_jit(ctx, modrm_byte, "fpu_fmul") +} +pub fn instr_DE_1_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DE_reg_jit(ctx, r, "fpu_fmul") +} +pub fn instr_DE_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_i16(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_fcom") +} +pub fn instr_DE_2_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn2_i64_i32("fpu_fcom"); + codegen::gen_fn0_const(ctx.builder, "fpu_pop") +} +pub fn instr_DE_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_i16(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_fcomp") +} +pub fn instr_DE_3_reg_jit(ctx: &mut JitContext, r: u32) { + if r == 1 { + codegen::gen_fpu_get_sti(ctx, r); + ctx.builder.call_fn2_i64_i32("fpu_fcomp"); + codegen::gen_fn0_const(ctx.builder, "fpu_pop") + } + else { + codegen::gen_trigger_ud(ctx); + } +} +pub fn instr_DE_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DE_mem_jit(ctx, modrm_byte, "fpu_fsub") +} +pub fn instr_DE_4_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DE_reg_jit(ctx, r, "fpu_fsub") +} +pub fn instr_DE_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DE_mem_jit(ctx, modrm_byte, "fpu_fsubr") +} +pub fn instr_DE_5_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DE_reg_jit(ctx, r, "fpu_fsubr") +} +pub fn instr_DE_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DE_mem_jit(ctx, modrm_byte, "fpu_fdiv") +} +pub fn instr_DE_6_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DE_reg_jit(ctx, r, "fpu_fdiv") +} +pub fn instr_DE_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr_group_DE_mem_jit(ctx, modrm_byte, "fpu_fdivr") +} +pub fn instr_DE_7_reg_jit(ctx: &mut JitContext, r: u32) { + instr_group_DE_reg_jit(ctx, r, "fpu_fdivr") +} + +pub fn instr_DF_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_fpu_get_sti(ctx, 0); + ctx.builder.call_fn2_i64_i32_ret("fpu_convert_to_i16"); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write16(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); +} +pub fn instr_DF_2_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "fpu_fstp", r); +} +pub fn instr_DF_3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_fpu_get_sti(ctx, 0); + ctx.builder.call_fn2_i64_i32_ret("fpu_convert_to_i16"); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write16(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); + codegen::gen_fn0_const(ctx.builder, "fpu_pop"); +} +pub fn instr_DF_3_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "fpu_fstp", r); +} + +pub fn instr_DF_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + dbg_log!("fbld"); + codegen::gen_modrm_resolve(ctx, modrm_byte); + codegen::gen_trigger_ud(ctx); +} +pub fn instr_DF_4_reg_jit(ctx: &mut JitContext, r: u32) { + if r == 0 { + ctx.builder.call_fn0_ret("fpu_load_status_word"); + codegen::gen_set_reg16(ctx, regs::AX); + } + else { + codegen::gen_trigger_ud(ctx); + }; +} + +pub fn instr_DF_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_fpu_load_i64(ctx, modrm_byte); + ctx.builder.call_fn2_i64_i32("fpu_push"); +} +pub fn instr_DF_5_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_fn1_const(ctx.builder, "fpu_fucomip", r); +} + +pub fn instr_DF_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + + codegen::gen_set_previous_eip_offset_from_eip_with_low_bits( + ctx.builder, + ctx.start_of_current_instruction as i32 & 0xFFF, + ); + + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1("fpu_fbstp"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + + codegen::gen_get_page_fault(ctx.builder); + ctx.builder.if_void(); + codegen::gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.br(ctx.exit_label); + ctx.builder.block_end(); +} +pub fn instr_DF_6_reg_jit(ctx: &mut JitContext, r: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn1("fpu_fcomip"); +} + +pub fn instr_DF_7_reg_jit(ctx: &mut JitContext, _r: u32) { codegen::gen_trigger_ud(ctx); } +pub fn instr_DF_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_fpu_get_sti(ctx, 0); + ctx.builder.call_fn2_i64_i32_ret_i64("fpu_convert_to_i64"); + let value_local = ctx.builder.set_new_local_i64(); + codegen::gen_safe_write64(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local_i64(value_local); + codegen::gen_fn0_const(ctx.builder, "fpu_pop"); +} + +pub fn instr16_EB_jit(_ctx: &mut JitContext, _imm8: u32) { + // +} + +pub fn instr32_EB_jit(_ctx: &mut JitContext, _imm8: u32) { + // jmp near +} + +define_instruction_read8!(gen_test8, instr_F6_0_mem_jit, instr_F6_0_reg_jit, imm8); +define_instruction_read16!( + gen_test16, + instr16_F7_0_mem_jit, + instr16_F7_0_reg_jit, + imm16 +); +define_instruction_read32!( + gen_test32, + instr32_F7_0_mem_jit, + instr32_F7_0_reg_jit, + imm32 +); + +pub fn instr_F6_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + instr_F6_0_mem_jit(ctx, modrm_byte, imm) +} +pub fn instr_F6_1_reg_jit(ctx: &mut JitContext, r: u32, imm: u32) { + instr_F6_0_reg_jit(ctx, r, imm) +} +pub fn instr16_F7_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + instr16_F7_0_mem_jit(ctx, modrm_byte, imm) +} +pub fn instr16_F7_1_reg_jit(ctx: &mut JitContext, r: u32, imm: u32) { + instr16_F7_0_reg_jit(ctx, r, imm) +} +pub fn instr32_F7_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + instr32_F7_0_mem_jit(ctx, modrm_byte, imm) +} +pub fn instr32_F7_1_reg_jit(ctx: &mut JitContext, r: u32, imm: u32) { + instr32_F7_0_reg_jit(ctx, r, imm) +} + +define_instruction_read_write_mem8!("not8", instr_F6_2_mem_jit, instr_F6_2_reg_jit, none); +define_instruction_read_write_mem8!("neg8", instr_F6_3_mem_jit, instr_F6_3_reg_jit, none); + +define_instruction_read_write_mem16!(gen_not16, instr16_F7_2_mem_jit, instr16_F7_2_reg_jit, none); +define_instruction_read_write_mem32!(gen_not32, instr32_F7_2_mem_jit, instr32_F7_2_reg_jit, none); +define_instruction_read_write_mem16!(gen_neg16, instr16_F7_3_mem_jit, instr16_F7_3_reg_jit, none); +define_instruction_read_write_mem32!(gen_neg32, instr32_F7_3_mem_jit, instr32_F7_3_reg_jit, none); + +pub fn instr16_F7_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1("mul16"); + codegen::gen_move_registers_from_memory_to_locals(ctx); +} +pub fn instr16_F7_4_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg16(ctx, r); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1("mul16"); + codegen::gen_move_registers_from_memory_to_locals(ctx); +} +pub fn instr32_F7_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + gen_mul32(ctx); +} +pub fn instr32_F7_4_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg32(ctx, r); + gen_mul32(ctx); +} + +pub fn instr16_F7_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::sign_extend_i16(ctx.builder); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1("imul16"); + codegen::gen_move_registers_from_memory_to_locals(ctx); +} +pub fn instr16_F7_5_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg16(ctx, r); + codegen::sign_extend_i16(ctx.builder); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1("imul16"); + codegen::gen_move_registers_from_memory_to_locals(ctx); +} +pub fn instr32_F7_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + gen_imul32(ctx); +} +pub fn instr32_F7_5_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg32(ctx, r); + gen_imul32(ctx); +} + +pub fn instr16_F7_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1_ret("div16_without_fault"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_de(ctx); + ctx.builder.block_end(); +} +pub fn instr16_F7_6_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg16(ctx, r); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1_ret("div16_without_fault"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_de(ctx); + ctx.builder.block_end(); +} + +pub fn instr32_F7_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + if false { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1_ret("div32_without_fault"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_de(ctx); + ctx.builder.block_end(); + } + else { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + let source_operand = ctx.builder.set_new_local(); + gen_div32(ctx, &source_operand); + ctx.builder.free_local(source_operand); + } +} +pub fn instr32_F7_6_reg_jit(ctx: &mut JitContext, r: u32) { + if false { + codegen::gen_get_reg32(ctx, r); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1_ret("div32_without_fault"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_de(ctx); + ctx.builder.block_end(); + } + else { + gen_div32(ctx, &ctx.reg(r)); + } +} + +pub fn instr16_F7_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::sign_extend_i16(ctx.builder); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1_ret("idiv16_without_fault"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_de(ctx); + ctx.builder.block_end(); +} +pub fn instr16_F7_7_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg16(ctx, r); + codegen::sign_extend_i16(ctx.builder); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1_ret("idiv16_without_fault"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_de(ctx); + ctx.builder.block_end(); +} +pub fn instr32_F7_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1_ret("idiv32_without_fault"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_de(ctx); + ctx.builder.block_end(); +} +pub fn instr32_F7_7_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg32(ctx, r); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn1_ret("idiv32_without_fault"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_de(ctx); + ctx.builder.block_end(); +} + +pub fn instr_F8_jit(ctx: &mut JitContext) { + codegen::gen_clear_flags_changed_bits(ctx.builder, 1); + codegen::gen_clear_flags_bits(ctx.builder, 1); +} +pub fn instr_F9_jit(ctx: &mut JitContext) { + codegen::gen_clear_flags_changed_bits(ctx.builder, 1); + codegen::gen_set_flags_bits(ctx.builder, 1); +} + +pub fn instr_FA_jit(ctx: &mut JitContext) { + ctx.builder.call_fn0_ret("instr_FA_without_fault"); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_gp(ctx, 0); + ctx.builder.block_end(); +} + +pub fn instr_FB_jit(ctx: &mut JitContext) { + ctx.builder.call_fn0_ret("instr_FB_without_fault"); + ctx.builder.eqz_i32(); + ctx.builder.if_void(); + codegen::gen_trigger_gp(ctx, 0); + ctx.builder.block_end(); + // handle_irqs is specially handled in jit to be called one instruction after this one +} + +pub fn instr_FC_jit(ctx: &mut JitContext) { + ctx.builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(ctx.builder); + ctx.builder.const_i32(!FLAG_DIRECTION); + ctx.builder.and_i32(); + ctx.builder.store_aligned_i32(0); +} + +pub fn instr_FD_jit(ctx: &mut JitContext) { + ctx.builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_DIRECTION); + ctx.builder.or_i32(); + ctx.builder.store_aligned_i32(0); +} + +define_instruction_read_write_mem8!("inc8", instr_FE_0_mem_jit, instr_FE_0_reg_jit, none); +define_instruction_read_write_mem8!("dec8", instr_FE_1_mem_jit, instr_FE_1_reg_jit, none); + +define_instruction_read_write_mem16!(gen_inc16, instr16_FF_0_mem_jit, instr16_FF_0_reg_jit, none); +define_instruction_read_write_mem32!(gen_inc32, instr32_FF_0_mem_jit, instr32_FF_0_reg_jit, none); + +define_instruction_read_write_mem16!(gen_dec16, instr16_FF_1_mem_jit, instr16_FF_1_reg_jit, none); +define_instruction_read_write_mem32!(gen_dec32, instr32_FF_1_mem_jit, instr32_FF_1_reg_jit, none); + +pub fn instr16_FF_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::gen_add_cs_offset(ctx); + let new_eip = ctx.builder.set_new_local(); + + codegen::gen_get_real_eip(ctx); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &value_local); + ctx.builder.free_local(value_local); + + ctx.builder.const_i32(0); + ctx.builder.get_local(&new_eip); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); + ctx.builder.free_local(new_eip); +} +pub fn instr16_FF_2_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_real_eip(ctx); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &value_local); + ctx.builder.free_local(value_local); + + ctx.builder.const_i32(0); + codegen::gen_get_reg16(ctx, r); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); +} +pub fn instr32_FF_2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + codegen::gen_add_cs_offset(ctx); + let new_eip = ctx.builder.set_new_local(); + + codegen::gen_get_real_eip(ctx); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push32(ctx, &value_local); + ctx.builder.free_local(value_local); + + ctx.builder.const_i32(0); + ctx.builder.get_local(&new_eip); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); + ctx.builder.free_local(new_eip); +} +pub fn instr32_FF_2_reg_jit(ctx: &mut JitContext, r: u32) { + codegen::gen_get_real_eip(ctx); + let value_local = ctx.builder.set_new_local(); + codegen::gen_push32(ctx, &value_local); + ctx.builder.free_local(value_local); + + ctx.builder.const_i32(0); + codegen::gen_get_reg32(ctx, r); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); +} + +pub fn instr16_FF_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + ctx.builder.const_i32(0); + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); +} +pub fn instr16_FF_4_reg_jit(ctx: &mut JitContext, r: u32) { + ctx.builder.const_i32(0); + codegen::gen_get_reg16(ctx, r); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); +} +pub fn instr32_FF_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + ctx.builder.const_i32(0); + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); +} +pub fn instr32_FF_4_reg_jit(ctx: &mut JitContext, r: u32) { + ctx.builder.const_i32(0); + codegen::gen_get_reg32(ctx, r); + codegen::gen_add_cs_offset(ctx); + ctx.builder + .store_aligned_i32(global_pointers::instruction_pointer as u32); +} + +pub fn instr16_FF_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + push16_mem_jit(ctx, modrm_byte) +} +pub fn instr16_FF_6_reg_jit(ctx: &mut JitContext, r: u32) { push16_reg_jit(ctx, r) } +pub fn instr32_FF_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + push32_mem_jit(ctx, modrm_byte) +} +pub fn instr32_FF_6_reg_jit(ctx: &mut JitContext, r: u32) { push32_reg_jit(ctx, r) } + +// Code for conditional jumps is generated automatically by the basic block codegen +pub fn instr16_0F80_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F81_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F82_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F83_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F84_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F85_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F86_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F87_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F88_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F89_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F8A_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F8B_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F8C_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F8D_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F8E_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr16_0F8F_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F80_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F81_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F82_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F83_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F84_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F85_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F86_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F87_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F88_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F89_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F8A_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F8B_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F8C_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F8D_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F8E_jit(_ctx: &mut JitContext, _imm: u32) {} +pub fn instr32_0F8F_jit(_ctx: &mut JitContext, _imm: u32) {} + +pub fn instr_90_jit(_ctx: &mut JitContext) {} + +fn gen_xchg_reg16(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg16(ctx, r); + let tmp = ctx.builder.set_new_local(); + codegen::gen_get_reg16(ctx, regs::AX); + codegen::gen_set_reg16(ctx, r); + ctx.builder.get_local(&tmp); + codegen::gen_set_reg16(ctx, regs::AX); + ctx.builder.free_local(tmp); +} + +fn gen_xchg_reg32(ctx: &mut JitContext, r: u32) { + codegen::gen_get_reg32(ctx, r); + let tmp = ctx.builder.set_new_local(); + codegen::gen_get_reg32(ctx, regs::EAX); + codegen::gen_set_reg32(ctx, r); + ctx.builder.get_local(&tmp); + codegen::gen_set_reg32(ctx, regs::EAX); + ctx.builder.free_local(tmp); +} + +pub fn instr16_91_jit(ctx: &mut JitContext) { gen_xchg_reg16(ctx, regs::CX); } +pub fn instr16_92_jit(ctx: &mut JitContext) { gen_xchg_reg16(ctx, regs::DX); } +pub fn instr16_93_jit(ctx: &mut JitContext) { gen_xchg_reg16(ctx, regs::BX); } +pub fn instr16_94_jit(ctx: &mut JitContext) { gen_xchg_reg16(ctx, regs::SP); } +pub fn instr16_95_jit(ctx: &mut JitContext) { gen_xchg_reg16(ctx, regs::BP); } +pub fn instr16_96_jit(ctx: &mut JitContext) { gen_xchg_reg16(ctx, regs::SI); } +pub fn instr16_97_jit(ctx: &mut JitContext) { gen_xchg_reg16(ctx, regs::DI); } + +pub fn instr32_91_jit(ctx: &mut JitContext) { gen_xchg_reg32(ctx, regs::CX); } +pub fn instr32_92_jit(ctx: &mut JitContext) { gen_xchg_reg32(ctx, regs::DX); } +pub fn instr32_93_jit(ctx: &mut JitContext) { gen_xchg_reg32(ctx, regs::BX); } +pub fn instr32_94_jit(ctx: &mut JitContext) { gen_xchg_reg32(ctx, regs::SP); } +pub fn instr32_95_jit(ctx: &mut JitContext) { gen_xchg_reg32(ctx, regs::BP); } +pub fn instr32_96_jit(ctx: &mut JitContext) { gen_xchg_reg32(ctx, regs::SI); } +pub fn instr32_97_jit(ctx: &mut JitContext) { gen_xchg_reg32(ctx, regs::DI); } + +pub fn instr16_98_jit(ctx: &mut JitContext) { + codegen::gen_get_reg32(ctx, regs::EAX); + codegen::sign_extend_i8(ctx.builder); + codegen::gen_set_reg16(ctx, regs::AX); +} +pub fn instr32_98_jit(ctx: &mut JitContext) { + codegen::gen_get_reg32(ctx, regs::EAX); + codegen::sign_extend_i16(ctx.builder); + codegen::gen_set_reg32(ctx, regs::EAX); +} + +pub fn instr16_99_jit(ctx: &mut JitContext) { + codegen::gen_get_reg16(ctx, regs::AX); + ctx.builder.const_i32(16); + ctx.builder.shl_i32(); + ctx.builder.const_i32(31); + ctx.builder.shr_s_i32(); + codegen::gen_set_reg16(ctx, regs::DX); +} +pub fn instr32_99_jit(ctx: &mut JitContext) { + codegen::gen_get_reg32(ctx, regs::EAX); + ctx.builder.const_i32(31); + ctx.builder.shr_s_i32(); + codegen::gen_set_reg32(ctx, regs::EDX); +} + +fn gen_pushf_popf_check(ctx: &mut JitContext) { + // 0 != *flags & FLAG_VM && getiopl() < 3 + codegen::gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_VM); + ctx.builder.and_i32(); + ctx.builder.const_i32(FLAG_VM); + ctx.builder.eq_i32(); + codegen::gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_IOPL); + ctx.builder.and_i32(); + ctx.builder.const_i32(FLAG_IOPL); + ctx.builder.ne_i32(); + ctx.builder.and_i32(); +} + +pub fn instr16_9C_jit(ctx: &mut JitContext) { + gen_pushf_popf_check(ctx); + ctx.builder.if_void(); + codegen::gen_trigger_gp(ctx, 0); + ctx.builder.else_(); + ctx.builder.call_fn0_ret("get_eflags"); + let value = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &value); + ctx.builder.block_end(); + ctx.builder.free_local(value); +} +pub fn instr32_9C_jit(ctx: &mut JitContext) { + gen_pushf_popf_check(ctx); + ctx.builder.if_void(); + codegen::gen_trigger_gp(ctx, 0); + ctx.builder.else_(); + ctx.builder.call_fn0_ret("get_eflags"); + ctx.builder.const_i32(0xFCFFFF); + ctx.builder.and_i32(); + let value = ctx.builder.set_new_local(); + codegen::gen_push32(ctx, &value); + ctx.builder.block_end(); + ctx.builder.free_local(value); +} + +fn gen_popf(ctx: &mut JitContext, is_32: bool) { + gen_pushf_popf_check(ctx); + ctx.builder.if_void(); + codegen::gen_trigger_gp(ctx, 0); + ctx.builder.else_(); + + codegen::gen_get_flags(ctx.builder); + let old_eflags = ctx.builder.set_new_local(); + + if is_32 { + codegen::gen_pop32s(ctx); + } + else { + ctx.builder.get_local(&old_eflags); + ctx.builder.const_i32(!0xFFFF); + ctx.builder.and_i32(); + codegen::gen_pop16(ctx); + ctx.builder.or_i32(); + } + + ctx.builder.call_fn1("update_eflags"); + + ctx.builder.get_local(&old_eflags); + ctx.builder.free_local(old_eflags); + ctx.builder.const_i32(FLAG_INTERRUPT); + ctx.builder.and_i32(); + ctx.builder.eqz_i32(); + + codegen::gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_INTERRUPT); + ctx.builder.and_i32(); + ctx.builder.eqz_i32(); + ctx.builder.eqz_i32(); + + ctx.builder.and_i32(); + ctx.builder.if_void(); + { + codegen::gen_set_eip_to_after_current_instruction(ctx); + codegen::gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + codegen::gen_move_registers_from_locals_to_memory(ctx); + codegen::gen_fn0_const(ctx.builder, "handle_irqs"); + + codegen::gen_update_instruction_counter(ctx); + ctx.builder.return_(); + } + ctx.builder.block_end(); + + ctx.builder.block_end(); +} + +pub fn instr16_9D_jit(ctx: &mut JitContext) { gen_popf(ctx, false) } +pub fn instr32_9D_jit(ctx: &mut JitContext) { gen_popf(ctx, true) } + +pub fn instr_9E_jit(ctx: &mut JitContext) { + ctx.builder.const_i32(global_pointers::flags as i32); + codegen::gen_get_flags(ctx.builder); + ctx.builder.const_i32(!0xFF); + ctx.builder.and_i32(); + codegen::gen_get_reg8(ctx, regs::AH); + ctx.builder.or_i32(); + ctx.builder.const_i32(FLAGS_MASK); + ctx.builder.and_i32(); + ctx.builder.const_i32(FLAGS_DEFAULT); + ctx.builder.or_i32(); + ctx.builder.store_aligned_i32(0); + + codegen::gen_clear_flags_changed_bits(ctx.builder, 0xFF); +} + +pub fn instr_9F_jit(ctx: &mut JitContext) { + ctx.builder.call_fn0_ret("get_eflags"); + codegen::gen_set_reg8(ctx, regs::AH); +} + +pub fn instr_A0_jit(ctx: &mut JitContext, immaddr: u32) { + ctx.builder.const_i32(immaddr as i32); + jit_add_seg_offset(ctx, regs::DS); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read8(ctx, &address_local); + ctx.builder.free_local(address_local); + codegen::gen_set_reg8(ctx, regs::AL); +} +pub fn instr16_A1_jit(ctx: &mut JitContext, immaddr: u32) { + ctx.builder.const_i32(immaddr as i32); + jit_add_seg_offset(ctx, regs::DS); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read16(ctx, &address_local); + ctx.builder.free_local(address_local); + codegen::gen_set_reg16(ctx, regs::AX); +} +pub fn instr32_A1_jit(ctx: &mut JitContext, immaddr: u32) { + ctx.builder.const_i32(immaddr as i32); + jit_add_seg_offset(ctx, regs::DS); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read32(ctx, &address_local); + ctx.builder.free_local(address_local); + codegen::gen_set_reg32(ctx, regs::EAX); +} + +pub fn instr_A2_jit(ctx: &mut JitContext, immaddr: u32) { + ctx.builder.const_i32(immaddr as i32); + jit_add_seg_offset(ctx, regs::DS); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_write8(ctx, &address_local, &ctx.reg(regs::EAX)); + ctx.builder.free_local(address_local); +} +pub fn instr16_A3_jit(ctx: &mut JitContext, immaddr: u32) { + ctx.builder.const_i32(immaddr as i32); + jit_add_seg_offset(ctx, regs::DS); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_write16(ctx, &address_local, &ctx.reg(regs::EAX)); + ctx.builder.free_local(address_local); +} +pub fn instr32_A3_jit(ctx: &mut JitContext, immaddr: u32) { + ctx.builder.const_i32(immaddr as i32); + jit_add_seg_offset(ctx, regs::DS); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &address_local, &ctx.reg(regs::EAX)); + ctx.builder.free_local(address_local); +} + +pub fn instr_A8_jit(ctx: &mut JitContext, imm8: u32) { + gen_test8(ctx, &ctx.reg(0), &LocalOrImmediate::Immediate(imm8 as i32)); +} + +pub fn instr16_A9_jit(ctx: &mut JitContext, imm16: u32) { + gen_test16(ctx, &ctx.reg(0), &LocalOrImmediate::Immediate(imm16 as i32)); +} + +pub fn instr32_A9_jit(ctx: &mut JitContext, imm32: u32) { + gen_test32(ctx, &ctx.reg(0), &LocalOrImmediate::Immediate(imm32 as i32)); +} + +#[derive(PartialEq)] +enum String { + INS, + OUTS, + MOVS, + CMPS, + STOS, + LODS, + SCAS, +} +fn gen_string_ins(ctx: &mut JitContext, ins: String, size: u8, prefix: u8) { + dbg_assert!(prefix == 0 || prefix == 0xF2 || prefix == 0xF3); + dbg_assert!(size == 8 || size == 16 || size == 32); + + if prefix == 0 { + fn get_direction(ctx: &mut JitContext, size: u8) { + let bytes: i32 = (size / 8).into(); + dbg_assert!(bytes == 1 || bytes == 2 || bytes == 4); + ctx.builder.const_i32(-bytes); + ctx.builder.const_i32(bytes); + codegen::gen_get_flags(ctx.builder); + ctx.builder.const_i32(FLAG_DIRECTION); + ctx.builder.and_i32(); + ctx.builder.select(); + } + + match &ins { + String::LODS => { + if ctx.cpu.asize_32() { + codegen::gen_get_reg32(ctx, regs::ESI); + } + else { + codegen::gen_get_reg16(ctx, regs::ESI); + } + jit_add_seg_offset(ctx, regs::DS); + let address_local = ctx.builder.set_new_local(); + if size == 8 { + codegen::gen_safe_read8(ctx, &address_local); + ctx.builder.free_local(address_local); + codegen::gen_set_reg8_unmasked(ctx, regs::AL); + } + else if size == 16 { + codegen::gen_safe_read16(ctx, &address_local); + ctx.builder.free_local(address_local); + codegen::gen_set_reg16(ctx, regs::AX); + } + else { + codegen::gen_safe_read32(ctx, &address_local); + ctx.builder.free_local(address_local); + codegen::gen_set_reg32(ctx, regs::EAX); + } + + codegen::gen_get_reg32(ctx, regs::ESI); + get_direction(ctx, size); + ctx.builder.add_i32(); + if ctx.cpu.asize_32() { + codegen::gen_set_reg32(ctx, regs::ESI); + } + else { + codegen::gen_set_reg16(ctx, regs::ESI); + } + return; + }, + String::SCAS => { + if ctx.cpu.asize_32() { + codegen::gen_get_reg32(ctx, regs::EDI); + } + else { + codegen::gen_get_reg16(ctx, regs::EDI); + } + jit_add_seg_offset_no_override(ctx, regs::ES); + let address_local = ctx.builder.set_new_local(); + if size == 8 { + codegen::gen_safe_read8(ctx, &address_local); + ctx.builder.free_local(address_local); + let value = ctx.builder.set_new_local(); + gen_cmp8( + ctx, + &ctx.reg(regs::EAX), + &LocalOrImmediate::WasmLocal(&value), + ); + ctx.builder.free_local(value); + } + else if size == 16 { + codegen::gen_safe_read16(ctx, &address_local); + ctx.builder.free_local(address_local); + let value = ctx.builder.set_new_local(); + gen_cmp16( + ctx, + &ctx.reg(regs::EAX), + &LocalOrImmediate::WasmLocal(&value), + ); + ctx.builder.free_local(value); + } + else { + codegen::gen_safe_read32(ctx, &address_local); + ctx.builder.free_local(address_local); + let value = ctx.builder.set_new_local(); + gen_cmp32( + ctx, + &ctx.reg(regs::EAX), + &LocalOrImmediate::WasmLocal(&value), + ); + ctx.builder.free_local(value); + } + + codegen::gen_get_reg32(ctx, regs::EDI); + get_direction(ctx, size); + ctx.builder.add_i32(); + if ctx.cpu.asize_32() { + codegen::gen_set_reg32(ctx, regs::EDI); + } + else { + codegen::gen_set_reg16(ctx, regs::EDI); + } + return; + }, + String::STOS => { + if ctx.cpu.asize_32() { + codegen::gen_get_reg32(ctx, regs::EDI); + } + else { + codegen::gen_get_reg16(ctx, regs::EDI); + } + jit_add_seg_offset_no_override(ctx, regs::ES); + let address_local = ctx.builder.set_new_local(); + if size == 8 { + codegen::gen_safe_write8(ctx, &address_local, &ctx.reg(regs::AL)); + ctx.builder.free_local(address_local); + } + else if size == 16 { + codegen::gen_safe_write16(ctx, &address_local, &ctx.reg(regs::AX)); + ctx.builder.free_local(address_local); + } + else { + codegen::gen_safe_write32(ctx, &address_local, &ctx.reg(regs::EAX)); + ctx.builder.free_local(address_local); + } + + codegen::gen_get_reg32(ctx, regs::EDI); + get_direction(ctx, size); + ctx.builder.add_i32(); + if ctx.cpu.asize_32() { + codegen::gen_set_reg32(ctx, regs::EDI); + } + else { + codegen::gen_set_reg16(ctx, regs::EDI); + } + return; + }, + String::MOVS => { + if ctx.cpu.asize_32() { + codegen::gen_get_reg32(ctx, regs::EDI); + } + else { + codegen::gen_get_reg16(ctx, regs::EDI); + } + jit_add_seg_offset_no_override(ctx, regs::ES); + let dest_address = ctx.builder.set_new_local(); + + if ctx.cpu.asize_32() { + codegen::gen_get_reg32(ctx, regs::ESI); + } + else { + codegen::gen_get_reg16(ctx, regs::ESI); + } + jit_add_seg_offset(ctx, regs::DS); + let source_address = ctx.builder.set_new_local(); + + if size == 8 { + codegen::gen_safe_read8(ctx, &source_address); + ctx.builder.free_local(source_address); + let value = ctx.builder.set_new_local(); + codegen::gen_safe_write8(ctx, &dest_address, &value); + ctx.builder.free_local(value); + } + else if size == 16 { + codegen::gen_safe_read16(ctx, &source_address); + ctx.builder.free_local(source_address); + let value = ctx.builder.set_new_local(); + codegen::gen_safe_write16(ctx, &dest_address, &value); + ctx.builder.free_local(value); + } + else { + codegen::gen_safe_read32(ctx, &source_address); + ctx.builder.free_local(source_address); + let value = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &dest_address, &value); + ctx.builder.free_local(value); + } + + ctx.builder.free_local(dest_address); + + codegen::gen_get_reg32(ctx, regs::EDI); + get_direction(ctx, size); + ctx.builder.add_i32(); + if ctx.cpu.asize_32() { + codegen::gen_set_reg32(ctx, regs::EDI); + } + else { + codegen::gen_set_reg16(ctx, regs::EDI); + } + + codegen::gen_get_reg32(ctx, regs::ESI); + get_direction(ctx, size); + ctx.builder.add_i32(); + if ctx.cpu.asize_32() { + codegen::gen_set_reg32(ctx, regs::ESI); + } + else { + codegen::gen_set_reg16(ctx, regs::ESI); + } + return; + }, + _ => {}, + } + } + + let mut args = 0; + args += 1; + ctx.builder.const_i32(ctx.cpu.asize_32() as i32); + + if ins == String::OUTS || ins == String::CMPS || ins == String::LODS || ins == String::MOVS { + args += 1; + ctx.builder.const_i32(0); + jit_add_seg_offset(ctx, regs::DS); + } + + let name = format!( + "{}{}{}", + match ins { + String::INS => "ins", + String::OUTS => "outs", + String::MOVS => "movs", + String::CMPS => "cmps", + String::STOS => "stos", + String::LODS => "lods", + String::SCAS => "scas", + }, + if size == 8 { + "b" + } + else if size == 16 { + "w" + } + else { + "d" + }, + if prefix == 0xF2 || prefix == 0xF3 { + match ins { + String::CMPS | String::SCAS => { + if prefix == 0xF2 { + "_repnz" + } + else { + "_repz" + } + }, + _ => "_rep", + } + } + else { + "_no_rep" + } + ); + + codegen::gen_move_registers_from_locals_to_memory(ctx); + if args == 1 { + ctx.builder.call_fn1(&name) + } + else if args == 2 { + ctx.builder.call_fn2(&name) + } + else { + dbg_assert!(false); + } + codegen::gen_move_registers_from_memory_to_locals(ctx); +} + +pub fn instr_6C_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::INS, 8, 0) } +pub fn instr_F26C_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::INS, 8, 0xF2) } +pub fn instr_F36C_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::INS, 8, 0xF3) } +pub fn instr16_6D_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::INS, 16, 0) } +pub fn instr16_F26D_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::INS, 16, 0xF2) } +pub fn instr16_F36D_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::INS, 16, 0xF3) } +pub fn instr32_6D_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::INS, 32, 0) } +pub fn instr32_F26D_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::INS, 32, 0xF2) } +pub fn instr32_F36D_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::INS, 32, 0xF3) } +pub fn instr_6E_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::OUTS, 8, 0) } +pub fn instr_F26E_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::OUTS, 8, 0xF2) } +pub fn instr_F36E_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::OUTS, 8, 0xF3) } +pub fn instr16_6F_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::OUTS, 16, 0) } +pub fn instr16_F26F_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::OUTS, 16, 0xF2) } +pub fn instr16_F36F_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::OUTS, 16, 0xF3) } +pub fn instr32_6F_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::OUTS, 32, 0) } +pub fn instr32_F26F_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::OUTS, 32, 0xF2) } +pub fn instr32_F36F_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::OUTS, 32, 0xF3) } +pub fn instr_A4_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::MOVS, 8, 0) } +pub fn instr_F2A4_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::MOVS, 8, 0xF2) } +pub fn instr_F3A4_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::MOVS, 8, 0xF3) } +pub fn instr16_A5_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::MOVS, 16, 0) } +pub fn instr16_F2A5_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::MOVS, 16, 0xF2) } +pub fn instr16_F3A5_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::MOVS, 16, 0xF3) } +pub fn instr32_A5_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::MOVS, 32, 0) } +pub fn instr32_F2A5_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::MOVS, 32, 0xF2) } +pub fn instr32_F3A5_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::MOVS, 32, 0xF3) } +pub fn instr_A6_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::CMPS, 8, 0) } +pub fn instr_F2A6_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::CMPS, 8, 0xF2) } +pub fn instr_F3A6_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::CMPS, 8, 0xF3) } +pub fn instr16_A7_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::CMPS, 16, 0) } +pub fn instr16_F2A7_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::CMPS, 16, 0xF2) } +pub fn instr16_F3A7_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::CMPS, 16, 0xF3) } +pub fn instr32_A7_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::CMPS, 32, 0) } +pub fn instr32_F2A7_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::CMPS, 32, 0xF2) } +pub fn instr32_F3A7_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::CMPS, 32, 0xF3) } +pub fn instr_AA_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::STOS, 8, 0) } +pub fn instr_F2AA_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::STOS, 8, 0xF2) } +pub fn instr_F3AA_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::STOS, 8, 0xF3) } +pub fn instr16_AB_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::STOS, 16, 0) } +pub fn instr16_F2AB_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::STOS, 16, 0xF2) } +pub fn instr16_F3AB_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::STOS, 16, 0xF3) } +pub fn instr32_AB_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::STOS, 32, 0) } +pub fn instr32_F2AB_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::STOS, 32, 0xF2) } +pub fn instr32_F3AB_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::STOS, 32, 0xF3) } +pub fn instr_AC_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::LODS, 8, 0) } +pub fn instr_F2AC_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::LODS, 8, 0xF2) } +pub fn instr_F3AC_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::LODS, 8, 0xF3) } +pub fn instr16_AD_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::LODS, 16, 0) } +pub fn instr16_F2AD_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::LODS, 16, 0xF2) } +pub fn instr16_F3AD_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::LODS, 16, 0xF3) } +pub fn instr32_AD_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::LODS, 32, 0) } +pub fn instr32_F2AD_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::LODS, 32, 0xF2) } +pub fn instr32_F3AD_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::LODS, 32, 0xF3) } +pub fn instr_AE_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::SCAS, 8, 0) } +pub fn instr_F2AE_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::SCAS, 8, 0xF2) } +pub fn instr_F3AE_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::SCAS, 8, 0xF3) } +pub fn instr16_AF_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::SCAS, 16, 0) } +pub fn instr16_F2AF_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::SCAS, 16, 0xF2) } +pub fn instr16_F3AF_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::SCAS, 16, 0xF3) } +pub fn instr32_AF_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::SCAS, 32, 0) } +pub fn instr32_F2AF_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::SCAS, 32, 0xF2) } +pub fn instr32_F3AF_jit(ctx: &mut JitContext) { gen_string_ins(ctx, String::SCAS, 32, 0xF3) } + +pub fn instr_0F31_jit(ctx: &mut JitContext) { + ctx.builder.load_fixed_u8(global_pointers::cpl as u32); + ctx.builder.eqz_i32(); + + dbg_assert!(regs::CR4_TSD < 0x100); + ctx.builder + .load_fixed_u8(global_pointers::get_creg_offset(4)); + ctx.builder.const_i32(regs::CR4_TSD as i32); + ctx.builder.and_i32(); + ctx.builder.eqz_i32(); + + ctx.builder.or_i32(); + ctx.builder.if_void(); + ctx.builder.call_fn0_ret_i64("read_tsc"); + + let tsc = ctx.builder.tee_new_local_i64(); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EAX); + + ctx.builder.get_local_i64(&tsc); + ctx.builder.const_i64(32); + ctx.builder.shr_u_i64(); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EDX); + + ctx.builder.free_local_i64(tsc); + ctx.builder.else_(); + codegen::gen_trigger_gp(ctx, 0); + ctx.builder.block_end(); +} + +pub fn instr_0F0B_jit(ctx: &mut JitContext) { codegen::gen_trigger_ud(ctx) } + +pub fn instr_0F18_mem_jit(_ctx: &mut JitContext, _modrm_byte: ModrmByte, _reg: u32) {} +pub fn instr_0F18_reg_jit(_ctx: &mut JitContext, _r1: u32, _r2: u32) {} + +pub fn instr_0F19_mem_jit(_ctx: &mut JitContext, _modrm_byte: ModrmByte, _reg: u32) {} +pub fn instr_0F19_reg_jit(_ctx: &mut JitContext, _r1: u32, _r2: u32) {} + +pub fn instr_0F1C_mem_jit(_ctx: &mut JitContext, _modrm_byte: ModrmByte, _reg: u32) {} +pub fn instr_0F1C_reg_jit(_ctx: &mut JitContext, _r1: u32, _r2: u32) {} +pub fn instr_0F1D_mem_jit(_ctx: &mut JitContext, _modrm_byte: ModrmByte, _reg: u32) {} +pub fn instr_0F1D_reg_jit(_ctx: &mut JitContext, _r1: u32, _r2: u32) {} +pub fn instr_0F1E_mem_jit(_ctx: &mut JitContext, _modrm_byte: ModrmByte, _reg: u32) {} +pub fn instr_0F1E_reg_jit(_ctx: &mut JitContext, _r1: u32, _r2: u32) {} +pub fn instr_0F1F_mem_jit(_ctx: &mut JitContext, _modrm_byte: ModrmByte, _reg: u32) {} +pub fn instr_0F1F_reg_jit(_ctx: &mut JitContext, _r1: u32, _r2: u32) {} + +define_instruction_read_write_mem16!( + "shld16", + instr16_0FA4_mem_jit, + instr16_0FA4_reg_jit, + reg, + imm8_5bits +); +define_instruction_read_write_mem32!( + "shld32", + instr32_0FA4_mem_jit, + instr32_0FA4_reg_jit, + reg, + imm8_5bits +); +define_instruction_read_write_mem16!( + "shld16", + instr16_0FA5_mem_jit, + instr16_0FA5_reg_jit, + reg, + cl +); +define_instruction_read_write_mem32!( + "shld32", + instr32_0FA5_mem_jit, + instr32_0FA5_reg_jit, + reg, + cl +); + +define_instruction_read_write_mem16!( + "shrd16", + instr16_0FAC_mem_jit, + instr16_0FAC_reg_jit, + reg, + imm8_5bits +); +define_instruction_read_write_mem32!( + "shrd32", + instr32_0FAC_mem_jit, + instr32_0FAC_reg_jit, + reg, + imm8_5bits +); +define_instruction_read_write_mem16!( + "shrd16", + instr16_0FAD_mem_jit, + instr16_0FAD_reg_jit, + reg, + cl +); +define_instruction_read_write_mem32!( + "shrd32", + instr32_0FAD_mem_jit, + instr32_0FAD_reg_jit, + reg, + cl +); + +pub fn instr16_0FB1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r1); + ctx.builder.const_i32(r2 as i32); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn2_ret("cmpxchg16"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + codegen::gen_set_reg16(ctx, r1); +} +pub fn instr16_0FB1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read_write(ctx, BitSize::WORD, &address_local, &|ref mut ctx| { + ctx.builder.const_i32(r as i32); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn2_ret("cmpxchg16"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + }); + ctx.builder.free_local(address_local); +} + +pub fn instr32_0FB1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg32(ctx, r1); + gen_cmpxchg32(ctx, r2); + codegen::gen_set_reg32(ctx, r1); +} +pub fn instr32_0FB1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &address_local, &|ref mut ctx| { + gen_cmpxchg32(ctx, r); + }); + ctx.builder.free_local(address_local); +} + +pub fn instr16_0FB6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg8(ctx, r1); + codegen::gen_set_reg16_unmasked(ctx, r2); +} +pub fn instr16_0FB6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read8(ctx, modrm_byte); + codegen::gen_set_reg16_unmasked(ctx, r); +} + +pub fn instr32_0FB6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg8(ctx, r1); + codegen::gen_set_reg32(ctx, r2); +} +pub fn instr32_0FB6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read8(ctx, modrm_byte); + codegen::gen_set_reg32(ctx, r); +} + +pub fn instr16_0FB7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::gen_set_reg16(ctx, r); +} +pub fn instr16_0FB7_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r1); + codegen::gen_set_reg16(ctx, r2); +} +pub fn instr32_0FB7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::gen_set_reg32(ctx, r); +} +pub fn instr32_0FB7_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r1); + codegen::gen_set_reg32(ctx, r2); +} + +pub fn instr16_F30FB8_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + ctx.builder.call_fn1_ret("popcnt"); + codegen::gen_set_reg16(ctx, r); +} +pub fn instr16_F30FB8_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r1); + ctx.builder.call_fn1_ret("popcnt"); + codegen::gen_set_reg16(ctx, r2); +} +pub fn instr32_F30FB8_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.call_fn1_ret("popcnt"); + codegen::gen_set_reg32(ctx, r); +} +pub fn instr32_F30FB8_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg32(ctx, r1); + ctx.builder.call_fn1_ret("popcnt"); + codegen::gen_set_reg32(ctx, r2); +} + +define_instruction_write_reg16!("bsf16", instr16_0FBC_mem_jit, instr16_0FBC_reg_jit); +define_instruction_write_reg32!(gen_bsf32, instr32_0FBC_mem_jit, instr32_0FBC_reg_jit); +define_instruction_write_reg16!("bsr16", instr16_0FBD_mem_jit, instr16_0FBD_reg_jit); +define_instruction_write_reg32!(gen_bsr32, instr32_0FBD_mem_jit, instr32_0FBD_reg_jit); + +pub fn instr16_0FBE_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg8(ctx, r1); + codegen::sign_extend_i8(ctx.builder); + codegen::gen_set_reg16(ctx, r2); +} +pub fn instr16_0FBE_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read8(ctx, modrm_byte); // TODO: Could use sign-extended read + codegen::sign_extend_i8(ctx.builder); + codegen::gen_set_reg16(ctx, r); +} + +pub fn instr32_0FBE_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + match r1 { + regs::AL | regs::CL | regs::DL | regs::BL => { + ctx.builder.get_local(&ctx.register_locals[r1 as usize]); + ctx.builder.const_i32(24); + ctx.builder.shl_i32(); + }, + regs::AH | regs::CH | regs::DH | regs::BH => { + ctx.builder + .get_local(&ctx.register_locals[(r1 - 4) as usize]); + ctx.builder.const_i32(16); + ctx.builder.shl_i32(); + }, + _ => assert!(false), + } + ctx.builder.const_i32(24); + ctx.builder.shr_s_i32(); + codegen::gen_set_reg32(ctx, r2); +} +pub fn instr32_0FBE_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read8(ctx, modrm_byte); // TODO: Could use sign-extended read + codegen::sign_extend_i8(ctx.builder); + codegen::gen_set_reg32(ctx, r); +} + +pub fn instr16_0FBF_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r1); + codegen::gen_set_reg16_unmasked(ctx, r2); +} +pub fn instr16_0FBF_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + codegen::gen_set_reg16_unmasked(ctx, r); +} + +pub fn instr32_0FBF_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg32(ctx, r1); + codegen::sign_extend_i16(ctx.builder); + codegen::gen_set_reg32(ctx, r2); +} +pub fn instr32_0FBF_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); // TODO: Could use sign-extended read + codegen::sign_extend_i16(ctx.builder); + codegen::gen_set_reg32(ctx, r); +} + +pub fn instr16_0FC1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read_write(ctx, BitSize::WORD, &address_local, &|ref mut ctx| { + ctx.builder.const_i32(r as i32); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn2_ret("xadd16"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + }); + ctx.builder.free_local(address_local); +} +pub fn instr16_0FC1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg16(ctx, r1); + ctx.builder.const_i32(r2 as i32); + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.call_fn2_ret("xadd16"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + codegen::gen_set_reg16(ctx, r1); +} + +pub fn instr32_0FC1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read_write(ctx, BitSize::DWORD, &address_local, &|ref mut ctx| { + let dest_operand = ctx.builder.set_new_local(); + gen_xadd32(ctx, &dest_operand, r); + ctx.builder.get_local(&dest_operand); + ctx.builder.free_local(dest_operand); + }); + ctx.builder.free_local(address_local); +} +pub fn instr32_0FC1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg32(ctx, r1); + let dest_operand = ctx.builder.set_new_local(); + gen_xadd32(ctx, &dest_operand, r2); + ctx.builder.get_local(&dest_operand); + codegen::gen_set_reg32(ctx, r1); + ctx.builder.free_local(dest_operand); +} + +pub fn instr_0FC3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &address_local, &ctx.reg(r)); + ctx.builder.free_local(address_local); +} +pub fn instr_0FC3_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { codegen::gen_trigger_ud(ctx) } + +pub fn instr_0FC4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read16(ctx, &address_local); + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn3("instr_0FC4"); + ctx.builder.free_local(address_local); +} +pub fn instr_0FC4_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + codegen::gen_get_reg32(ctx, r1); + ctx.builder.const_i32(r2 as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn3("instr_0FC4"); +} + +pub fn instr_660FC4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + ctx.builder.const_i32(0); + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read16(ctx, &address_local); + ctx.builder + .store_aligned_u16(global_pointers::get_reg_xmm_offset(r) + ((imm8 & 7) << 1)); + ctx.builder.free_local(address_local); +} +pub fn instr_660FC4_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + ctx.builder.const_i32(0); + codegen::gen_get_reg32(ctx, r1); + ctx.builder + .store_aligned_u16(global_pointers::get_reg_xmm_offset(r2) + ((imm8 & 7) << 1)); +} + +pub fn instr_0FC5_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _r: u32, _imm8: u32) { + codegen::gen_trigger_ud(ctx) +} +pub fn instr_0FC5_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.const_i32(r1 as i32); + ctx.builder.const_i32(r2 as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn3("instr_0FC5_reg"); + codegen::gen_move_registers_from_memory_to_locals(ctx); +} + +pub fn instr_660FC5_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _r: u32, _imm8: u32) { + codegen::gen_trigger_ud(ctx) +} +pub fn instr_660FC5_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + ctx.builder + .load_fixed_u16(global_pointers::get_reg_xmm_offset(r1) + ((imm8 & 7) << 1)); + codegen::gen_set_reg32(ctx, r2); +} + +pub fn instr16_0FC7_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + // cmpxchg8b + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read_write(ctx, BitSize::QWORD, &address_local, &|ref mut ctx| { + let dest_operand = ctx.builder.tee_new_local_i64(); + codegen::gen_get_reg32(ctx, regs::EDX); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder.const_i64(32); + ctx.builder.shl_i64(); + codegen::gen_get_reg32(ctx, regs::EAX); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder.or_i64(); + ctx.builder.eq_i64(); + ctx.builder.if_i64(); + { + codegen::gen_set_flags_bits(ctx.builder, FLAG_ZERO); + codegen::gen_get_reg32(ctx, regs::ECX); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder.const_i64(32); + ctx.builder.shl_i64(); + codegen::gen_get_reg32(ctx, regs::EBX); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder.or_i64(); + } + ctx.builder.else_(); + { + codegen::gen_clear_flags_bits(ctx.builder, FLAG_ZERO); + ctx.builder.get_local_i64(&dest_operand); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EAX); + ctx.builder.get_local_i64(&dest_operand); + ctx.builder.const_i64(32); + ctx.builder.shr_u_i64(); + ctx.builder.wrap_i64_to_i32(); + codegen::gen_set_reg32(ctx, regs::EDX); + ctx.builder.get_local_i64(&dest_operand); + } + ctx.builder.block_end(); + codegen::gen_clear_flags_changed_bits(ctx.builder, FLAG_ZERO); + ctx.builder.free_local_i64(dest_operand); + }); + ctx.builder.free_local(address_local); +} +pub fn instr16_0FC7_1_reg_jit(ctx: &mut JitContext, _r: u32) { codegen::gen_trigger_ud(ctx); } +pub fn instr32_0FC7_1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte) { + instr16_0FC7_1_mem_jit(ctx, modrm_byte); +} +pub fn instr32_0FC7_1_reg_jit(ctx: &mut JitContext, _r: u32) { codegen::gen_trigger_ud(ctx); } + +pub fn instr_0FC2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + sse_read128_xmm_xmm_imm(ctx, "instr_0FC2", r1, r2, imm8) +} +pub fn instr_0FC2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + sse_read128_xmm_mem_imm(ctx, "instr_0FC2", modrm_byte, r, imm8) +} +pub fn instr_660FC2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + sse_read128_xmm_xmm_imm(ctx, "instr_660FC2", r1, r2, imm8) +} +pub fn instr_660FC2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + sse_read128_xmm_mem_imm(ctx, "instr_660FC2", modrm_byte, r, imm8) +} +pub fn instr_F20FC2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32); + ctx.builder.load_aligned_i64(0); + ctx.builder.const_i32(r2 as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn3_i64_i32_i32("instr_F20FC2"); +} +pub fn instr_F20FC2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn3_i64_i32_i32("instr_F20FC2"); +} +pub fn instr_F30FC2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32); + ctx.builder.load_aligned_i32(0); + ctx.builder.const_i32(r2 as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn3("instr_F30FC2"); +} +pub fn instr_F30FC2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn3("instr_F30FC2"); +} + +pub fn instr_0FC6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + sse_read128_xmm_xmm_imm(ctx, "instr_0FC6", r1, r2, imm8) +} +pub fn instr_0FC6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + sse_read128_xmm_mem_imm(ctx, "instr_0FC6", modrm_byte, r, imm8) +} +pub fn instr_660FC6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + sse_read128_xmm_xmm_imm(ctx, "instr_660FC6", r1, r2, imm8) +} +pub fn instr_660FC6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + sse_read128_xmm_mem_imm(ctx, "instr_660FC6", modrm_byte, r, imm8) +} + +pub fn instr_C6_0_reg_jit(ctx: &mut JitContext, r: u32, imm: u32) { + // reg8[r] = imm; + ctx.builder.const_i32(imm as i32); + codegen::gen_set_reg8_unmasked(ctx, r); +} + +pub fn instr_C6_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + ctx.builder.const_i32(imm as i32); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write8(ctx, &addr, &value_local); + ctx.builder.free_local(value_local); + }); +} + +pub fn instr16_C7_0_reg_jit(ctx: &mut JitContext, r: u32, imm: u32) { + // reg16[r] = imm; + ctx.builder.const_i32(imm as i32); + codegen::gen_set_reg16_unmasked(ctx, r); +} + +pub fn instr16_C7_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + ctx.builder.const_i32(imm as i32); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write16(ctx, &addr, &value_local); + ctx.builder.free_local(value_local); + }); +} + +pub fn instr32_C7_0_reg_jit(ctx: &mut JitContext, r: u32, imm: u32) { + // reg32[r] = imm; + ctx.builder.const_i32(imm as i32); + codegen::gen_set_reg32(ctx, r); +} + +pub fn instr32_C7_0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + ctx.builder.const_i32(imm as i32); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &addr, &value_local); + ctx.builder.free_local(value_local); + }); +} + +pub fn instr_0FC8_jit(ctx: &mut JitContext) { gen_bswap(ctx, 0) } +pub fn instr_0FC9_jit(ctx: &mut JitContext) { gen_bswap(ctx, 1) } +pub fn instr_0FCA_jit(ctx: &mut JitContext) { gen_bswap(ctx, 2) } +pub fn instr_0FCB_jit(ctx: &mut JitContext) { gen_bswap(ctx, 3) } +pub fn instr_0FCC_jit(ctx: &mut JitContext) { gen_bswap(ctx, 4) } +pub fn instr_0FCD_jit(ctx: &mut JitContext) { gen_bswap(ctx, 5) } +pub fn instr_0FCE_jit(ctx: &mut JitContext) { gen_bswap(ctx, 6) } +pub fn instr_0FCF_jit(ctx: &mut JitContext) { gen_bswap(ctx, 7) } + +define_instruction_write_reg16!("imul_reg16", instr16_0FAF_mem_jit, instr16_0FAF_reg_jit); +define_instruction_write_reg32!(gen_imul_reg32, instr32_0FAF_mem_jit, instr32_0FAF_reg_jit); + +macro_rules! define_cmovcc16( + ($cond:expr, $name_mem:ident, $name_reg:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read16(ctx, modrm_byte); + let value = ctx.builder.set_new_local(); + codegen::gen_condition_fn(ctx, $cond); + ctx.builder.if_void(); + ctx.builder.get_local(&value); + codegen::gen_set_reg16(ctx, r); + ctx.builder.block_end(); + ctx.builder.free_local(value); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_condition_fn(ctx, $cond); + ctx.builder.if_void(); + codegen::gen_get_reg16(ctx, r1); + codegen::gen_set_reg16(ctx, r2); + ctx.builder.block_end(); + } + ); +); + +macro_rules! define_cmovcc32( + ($cond:expr, $name_mem:ident, $name_reg:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + let value = ctx.builder.set_new_local(); + codegen::gen_condition_fn(ctx, $cond); + ctx.builder.if_void(); + ctx.builder.get_local(&value); + codegen::gen_set_reg32(ctx, r); + ctx.builder.block_end(); + ctx.builder.free_local(value); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_condition_fn(ctx, $cond); + ctx.builder.if_void(); + codegen::gen_get_reg32(ctx, r1); + codegen::gen_set_reg32(ctx, r2); + ctx.builder.block_end(); + } + ); +); + +define_cmovcc16!(0x0, instr16_0F40_mem_jit, instr16_0F40_reg_jit); +define_cmovcc16!(0x1, instr16_0F41_mem_jit, instr16_0F41_reg_jit); +define_cmovcc16!(0x2, instr16_0F42_mem_jit, instr16_0F42_reg_jit); +define_cmovcc16!(0x3, instr16_0F43_mem_jit, instr16_0F43_reg_jit); +define_cmovcc16!(0x4, instr16_0F44_mem_jit, instr16_0F44_reg_jit); +define_cmovcc16!(0x5, instr16_0F45_mem_jit, instr16_0F45_reg_jit); +define_cmovcc16!(0x6, instr16_0F46_mem_jit, instr16_0F46_reg_jit); +define_cmovcc16!(0x7, instr16_0F47_mem_jit, instr16_0F47_reg_jit); + +define_cmovcc16!(0x8, instr16_0F48_mem_jit, instr16_0F48_reg_jit); +define_cmovcc16!(0x9, instr16_0F49_mem_jit, instr16_0F49_reg_jit); +define_cmovcc16!(0xA, instr16_0F4A_mem_jit, instr16_0F4A_reg_jit); +define_cmovcc16!(0xB, instr16_0F4B_mem_jit, instr16_0F4B_reg_jit); +define_cmovcc16!(0xC, instr16_0F4C_mem_jit, instr16_0F4C_reg_jit); +define_cmovcc16!(0xD, instr16_0F4D_mem_jit, instr16_0F4D_reg_jit); +define_cmovcc16!(0xE, instr16_0F4E_mem_jit, instr16_0F4E_reg_jit); +define_cmovcc16!(0xF, instr16_0F4F_mem_jit, instr16_0F4F_reg_jit); + +define_cmovcc32!(0x0, instr32_0F40_mem_jit, instr32_0F40_reg_jit); +define_cmovcc32!(0x1, instr32_0F41_mem_jit, instr32_0F41_reg_jit); +define_cmovcc32!(0x2, instr32_0F42_mem_jit, instr32_0F42_reg_jit); +define_cmovcc32!(0x3, instr32_0F43_mem_jit, instr32_0F43_reg_jit); +define_cmovcc32!(0x4, instr32_0F44_mem_jit, instr32_0F44_reg_jit); +define_cmovcc32!(0x5, instr32_0F45_mem_jit, instr32_0F45_reg_jit); +define_cmovcc32!(0x6, instr32_0F46_mem_jit, instr32_0F46_reg_jit); +define_cmovcc32!(0x7, instr32_0F47_mem_jit, instr32_0F47_reg_jit); + +define_cmovcc32!(0x8, instr32_0F48_mem_jit, instr32_0F48_reg_jit); +define_cmovcc32!(0x9, instr32_0F49_mem_jit, instr32_0F49_reg_jit); +define_cmovcc32!(0xA, instr32_0F4A_mem_jit, instr32_0F4A_reg_jit); +define_cmovcc32!(0xB, instr32_0F4B_mem_jit, instr32_0F4B_reg_jit); +define_cmovcc32!(0xC, instr32_0F4C_mem_jit, instr32_0F4C_reg_jit); +define_cmovcc32!(0xD, instr32_0F4D_mem_jit, instr32_0F4D_reg_jit); +define_cmovcc32!(0xE, instr32_0F4E_mem_jit, instr32_0F4E_reg_jit); +define_cmovcc32!(0xF, instr32_0F4F_mem_jit, instr32_0F4F_reg_jit); + +macro_rules! define_setcc( + ($cond:expr, $name_mem:ident, $name_reg:ident) => ( + pub fn $name_mem(ctx: &mut JitContext, modrm_byte: ModrmByte, _r: u32) { + codegen::gen_modrm_resolve_with_local(ctx, modrm_byte, &|ctx, addr| { + codegen::gen_condition_fn(ctx, $cond); + ctx.builder.const_i32(0); + ctx.builder.ne_i32(); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write8(ctx, &addr, &value_local); + ctx.builder.free_local(value_local); + }); + } + + pub fn $name_reg(ctx: &mut JitContext, r1: u32, _r2: u32) { + codegen::gen_condition_fn(ctx, $cond); + ctx.builder.const_i32(0); + ctx.builder.ne_i32(); + codegen::gen_set_reg8_unmasked(ctx, r1); + } + ); +); + +define_setcc!(0x0, instr_0F90_mem_jit, instr_0F90_reg_jit); +define_setcc!(0x1, instr_0F91_mem_jit, instr_0F91_reg_jit); +define_setcc!(0x2, instr_0F92_mem_jit, instr_0F92_reg_jit); +define_setcc!(0x3, instr_0F93_mem_jit, instr_0F93_reg_jit); +define_setcc!(0x4, instr_0F94_mem_jit, instr_0F94_reg_jit); +define_setcc!(0x5, instr_0F95_mem_jit, instr_0F95_reg_jit); +define_setcc!(0x6, instr_0F96_mem_jit, instr_0F96_reg_jit); +define_setcc!(0x7, instr_0F97_mem_jit, instr_0F97_reg_jit); + +define_setcc!(0x8, instr_0F98_mem_jit, instr_0F98_reg_jit); +define_setcc!(0x9, instr_0F99_mem_jit, instr_0F99_reg_jit); +define_setcc!(0xA, instr_0F9A_mem_jit, instr_0F9A_reg_jit); +define_setcc!(0xB, instr_0F9B_mem_jit, instr_0F9B_reg_jit); +define_setcc!(0xC, instr_0F9C_mem_jit, instr_0F9C_reg_jit); +define_setcc!(0xD, instr_0F9D_mem_jit, instr_0F9D_reg_jit); +define_setcc!(0xE, instr_0F9E_mem_jit, instr_0F9E_reg_jit); +define_setcc!(0xF, instr_0F9F_mem_jit, instr_0F9F_reg_jit); + +pub fn instr_0F10_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + let dest = global_pointers::get_reg_xmm_offset(r); + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, dest); +} +pub fn instr_0F10_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r1, r2) } +pub fn instr_660F10_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + let dest = global_pointers::get_reg_xmm_offset(r); + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, dest); +} +pub fn instr_660F10_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r1, r2) } +pub fn instr_F20F10_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_F30F7E_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_F20F10_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(0); + ctx.builder + .load_fixed_i64(global_pointers::get_reg_xmm_offset(r1)); + ctx.builder + .store_aligned_i64(global_pointers::get_reg_xmm_offset(r2)); +} +pub fn instr_F30F10_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_660F6E_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_F30F10_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(0); + ctx.builder + .load_fixed_i32(global_pointers::get_reg_xmm_offset(r1)); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r2)); +} + +pub fn instr_0F11_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_0F29_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_0F11_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r2, r1) } +pub fn instr_660F11_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_660F29_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_660F11_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r2, r1) } +pub fn instr_F20F11_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_660FD6_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_F20F11_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(0); + ctx.builder + .load_fixed_i64(global_pointers::get_reg_xmm_offset(r2)); + ctx.builder + .store_aligned_i64(global_pointers::get_reg_xmm_offset(r1)); +} +pub fn instr_F30F11_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_660F7E_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_F30F11_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(0); + ctx.builder + .load_fixed_i32(global_pointers::get_reg_xmm_offset(r2)); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r1)); +} + +pub fn instr_0F12_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r) as i32); + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.store_aligned_i64(0); +} +pub fn instr_0F12_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r2) as i32); + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32 + 8); + ctx.builder.load_aligned_i64(0); + ctx.builder.store_aligned_i64(0); +} +pub fn instr_660F12_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r) as i32); + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.store_aligned_i64(0); +} +pub fn instr_660F12_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} + +pub fn instr_0F13_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_660FD6_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_0F13_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F13_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_660FD6_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_660F13_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} + +pub fn instr_0F14_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_0F14", modrm_byte, r); +} +pub fn instr_0F14_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_0F14", r1, r2); +} +pub fn instr_660F14_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_660F14", modrm_byte, r); +} +pub fn instr_660F14_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_660F14", r1, r2); +} + +pub fn instr_0F15_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F15", modrm_byte, r); +} +pub fn instr_0F15_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F15", r1, r2); +} +pub fn instr_660F15_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F15", modrm_byte, r); +} +pub fn instr_660F15_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F15", r1, r2); +} + +pub fn instr_0F16_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_0F16", modrm_byte, r); +} +pub fn instr_0F16_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_0F16", r1, r2); +} +pub fn instr_660F16_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_0F16", modrm_byte, r); +} +pub fn instr_660F16_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} + +pub fn instr_0F17_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r) as i32); + ctx.builder.load_aligned_i64(8); + let value_local = ctx.builder.set_new_local_i64(); + codegen::gen_safe_write64(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local_i64(value_local); +} +pub fn instr_0F17_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F17_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_0F17_mem_jit(ctx, modrm_byte, r); +} +pub fn instr_660F17_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} + +pub fn instr_0F28_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + let dest = global_pointers::get_reg_xmm_offset(r); + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, dest); +} +pub fn instr_0F28_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r1, r2) } +pub fn instr_660F28_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + let dest = global_pointers::get_reg_xmm_offset(r); + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, dest); +} +pub fn instr_660F28_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r1, r2) } + +pub fn instr_0F29_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + // XXX: Aligned write or #gp + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r) as i32); + ctx.builder.load_aligned_i64(0); + let value_local_low = ctx.builder.set_new_local_i64(); + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r) as i32 + 8); + ctx.builder.load_aligned_i64(0); + let value_local_high = ctx.builder.set_new_local_i64(); + codegen::gen_safe_write128(ctx, &address_local, &value_local_low, &value_local_high); + ctx.builder.free_local(address_local); + ctx.builder.free_local_i64(value_local_low); + ctx.builder.free_local_i64(value_local_high); +} +pub fn instr_0F29_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r2, r1) } + +pub fn instr_660F29_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_0F29_mem_jit(ctx, modrm_byte, r); +} +pub fn instr_660F29_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r2, r1) } + +pub fn instr_0F2A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F2A", modrm_byte, r); +} +pub fn instr_0F2A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F2A", r1, r2); +} +pub fn instr_660F2A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_660F2A", modrm_byte, r); +} +pub fn instr_660F2A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_660F2A", r1, r2); +} +pub fn instr_F20F2A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn2("instr_F20F2A") +} +pub fn instr_F20F2A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg32(ctx, r1); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2("instr_F20F2A") +} +pub fn instr_F30F2A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn2("instr_F30F2A") +} +pub fn instr_F30F2A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg32(ctx, r1); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2("instr_F30F2A") +} + +pub fn instr_0F2B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_0F29_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_0F2B_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F2B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_0F29_mem_jit(ctx, modrm_byte, r) +} +pub fn instr_660F2B_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} + +pub fn instr_F20F2C_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.reinterpret_i64_as_f64(); + ctx.builder + .call_fn1_f64_ret("sse_convert_with_truncation_f64_to_i32"); + codegen::gen_set_reg32(ctx, r); +} +pub fn instr_F20F2C_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32); + ctx.builder.load_aligned_f64(0); + ctx.builder + .call_fn1_f64_ret("sse_convert_with_truncation_f64_to_i32"); + codegen::gen_set_reg32(ctx, r2); +} +pub fn instr_F30F2C_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.reinterpret_i32_as_f32(); + ctx.builder + .call_fn1_f32_ret("sse_convert_with_truncation_f32_to_i32"); + codegen::gen_set_reg32(ctx, r); +} +pub fn instr_F30F2C_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32); + ctx.builder.load_aligned_f32(0); + ctx.builder + .call_fn1_f32_ret("sse_convert_with_truncation_f32_to_i32"); + codegen::gen_set_reg32(ctx, r2); +} + +pub fn instr_F20F2D_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.reinterpret_i64_as_f64(); + ctx.builder.call_fn1_f64_ret("sse_convert_f64_to_i32"); + codegen::gen_set_reg32(ctx, r); +} +pub fn instr_F20F2D_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32); + ctx.builder.load_aligned_f64(0); + ctx.builder.call_fn1_f64_ret("sse_convert_f64_to_i32"); + codegen::gen_set_reg32(ctx, r2); +} +pub fn instr_F30F2D_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.reinterpret_i32_as_f32(); + ctx.builder.call_fn1_f32_ret("sse_convert_f32_to_i32"); + codegen::gen_set_reg32(ctx, r); +} +pub fn instr_F30F2D_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r1) as i32); + ctx.builder.load_aligned_f32(0); + ctx.builder.call_fn1_f32_ret("sse_convert_f32_to_i32"); + codegen::gen_set_reg32(ctx, r2); +} + +pub fn instr_0F2E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_0F2E", modrm_byte, r); +} +pub fn instr_0F2E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_0F2E", r1, r2); +} +pub fn instr_660F2E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_660F2E", modrm_byte, r); +} +pub fn instr_660F2E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_660F2E", r1, r2); +} + +pub fn instr_0F2F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_0F2F", modrm_byte, r); +} +pub fn instr_0F2F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_0F2F", r1, r2); +} +pub fn instr_660F2F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_660F2F", modrm_byte, r); +} +pub fn instr_660F2F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_660F2F", r1, r2); +} + +pub fn instr_0F51_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F51", modrm_byte, r); +} +pub fn instr_0F51_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F51", r1, r2); +} +pub fn instr_660F51_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F51", modrm_byte, r); +} +pub fn instr_660F51_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F51", r1, r2); +} +pub fn instr_F20F51_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_F20F51", modrm_byte, r); +} +pub fn instr_F20F51_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_F20F51", r1, r2); +} +pub fn instr_F30F51_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F51", modrm_byte, r); +} +pub fn instr_F30F51_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F51", r1, r2); +} + +pub fn instr_0F52_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F52", modrm_byte, r); +} +pub fn instr_0F52_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F52", r1, r2); +} +pub fn instr_F30F52_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F52", modrm_byte, r); +} +pub fn instr_F30F52_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F52", r1, r2); +} + +pub fn instr_0F53_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F53", modrm_byte, r); +} +pub fn instr_0F53_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F53", r1, r2); +} +pub fn instr_F30F53_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F53", modrm_byte, r); +} +pub fn instr_F30F53_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F53", r1, r2); +} + +pub fn instr_0F54_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F54", modrm_byte, r); +} +pub fn instr_0F54_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F54", r1, r2); +} +pub fn instr_660F54_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F54", modrm_byte, r); +} +pub fn instr_660F54_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F54", r1, r2); +} + +pub fn instr_0F55_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F55", modrm_byte, r); +} +pub fn instr_0F55_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F55", r1, r2); +} +pub fn instr_660F55_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F55", modrm_byte, r); +} +pub fn instr_660F55_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F55", r1, r2); +} + +pub fn instr_0F56_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F56", modrm_byte, r); +} +pub fn instr_0F56_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F56", r1, r2); +} +pub fn instr_660F56_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F56", modrm_byte, r); +} +pub fn instr_660F56_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F56", r1, r2); +} + +pub fn instr_0F57_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F57", modrm_byte, r); +} +pub fn instr_0F57_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F57", r1, r2); +} +pub fn instr_660F57_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F57", modrm_byte, r); +} +pub fn instr_660F57_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F57", r1, r2); +} + +pub fn instr_0F58_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F58", modrm_byte, r); +} +pub fn instr_0F58_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F58", r1, r2); +} +pub fn instr_660F58_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F58", modrm_byte, r); +} +pub fn instr_660F58_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F58", r1, r2); +} +pub fn instr_F20F58_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_F20F58", modrm_byte, r); +} +pub fn instr_F20F58_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_F20F58", r1, r2); +} +pub fn instr_F30F58_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F58", modrm_byte, r); +} +pub fn instr_F30F58_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F58", r1, r2); +} + +pub fn instr_0F59_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F59", modrm_byte, r); +} +pub fn instr_0F59_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F59", r1, r2); +} +pub fn instr_660F59_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F59", modrm_byte, r); +} +pub fn instr_660F59_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F59", r1, r2); +} +pub fn instr_F20F59_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_F20F59", modrm_byte, r); +} +pub fn instr_F20F59_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_F20F59", r1, r2); +} +pub fn instr_F30F59_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F59", modrm_byte, r); +} +pub fn instr_F30F59_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F59", r1, r2); +} + +pub fn instr_0F5A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_0F5A", modrm_byte, r); +} +pub fn instr_0F5A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_0F5A", r1, r2); +} +pub fn instr_660F5A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F5A", modrm_byte, r); +} +pub fn instr_660F5A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F5A", r1, r2); +} +pub fn instr_F20F5A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_F20F5A", modrm_byte, r); +} +pub fn instr_F20F5A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_F20F5A", r1, r2); +} +pub fn instr_F30F5A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F5A", modrm_byte, r); +} +pub fn instr_F30F5A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F5A", r1, r2); +} + +pub fn instr_0F5B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F5B", modrm_byte, r); +} +pub fn instr_0F5B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F5B", r1, r2); +} +pub fn instr_660F5B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F5B", modrm_byte, r); +} +pub fn instr_660F5B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F5B", r1, r2); +} +pub fn instr_F30F5B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_F30F5B", modrm_byte, r); +} +pub fn instr_F30F5B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_F30F5B", r1, r2); +} + +pub fn instr_0F5C_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F5C", modrm_byte, r); +} +pub fn instr_0F5C_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F5C", r1, r2); +} +pub fn instr_660F5C_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F5C", modrm_byte, r); +} +pub fn instr_660F5C_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F5C", r1, r2); +} +pub fn instr_F20F5C_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_F20F5C", modrm_byte, r); +} +pub fn instr_F20F5C_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_F20F5C", r1, r2); +} +pub fn instr_F30F5C_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F5C", modrm_byte, r); +} +pub fn instr_F30F5C_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F5C", r1, r2); +} + +pub fn instr_0F5D_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F5D", modrm_byte, r); +} +pub fn instr_0F5D_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F5D", r1, r2); +} +pub fn instr_660F5D_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F5D", modrm_byte, r); +} +pub fn instr_660F5D_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F5D", r1, r2); +} +pub fn instr_F20F5D_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_F20F5D", modrm_byte, r); +} +pub fn instr_F20F5D_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_F20F5D", r1, r2); +} +pub fn instr_F30F5D_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F5D", modrm_byte, r); +} +pub fn instr_F30F5D_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F5D", r1, r2); +} + +pub fn instr_0F5E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F5E", modrm_byte, r); +} +pub fn instr_0F5E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F5E", r1, r2); +} +pub fn instr_660F5E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F5E", modrm_byte, r); +} +pub fn instr_660F5E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F5E", r1, r2); +} +pub fn instr_F20F5E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_F20F5E", modrm_byte, r); +} +pub fn instr_F20F5E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_F20F5E", r1, r2); +} +pub fn instr_F30F5E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F5E", modrm_byte, r); +} +pub fn instr_F30F5E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F5E", r1, r2); +} + +pub fn instr_0F5F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_0F5F", modrm_byte, r); +} +pub fn instr_0F5F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_0F5F", r1, r2); +} +pub fn instr_660F5F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F5F", modrm_byte, r); +} +pub fn instr_660F5F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F5F", r1, r2); +} +pub fn instr_F20F5F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_F20F5F", modrm_byte, r); +} +pub fn instr_F20F5F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_F20F5F", r1, r2); +} +pub fn instr_F30F5F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read_f32_xmm_mem(ctx, "instr_F30F5F", modrm_byte, r); +} +pub fn instr_F30F5F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read_f32_xmm_xmm(ctx, "instr_F30F5F", r1, r2); +} + +pub fn instr_0F60_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem32(ctx, "instr_0F60", modrm_byte, r); +} +pub fn instr_0F60_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm32(ctx, "instr_0F60", r1, r2); +} +pub fn instr_0F61_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem32(ctx, "instr_0F61", modrm_byte, r); +} +pub fn instr_0F61_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm32(ctx, "instr_0F61", r1, r2); +} +pub fn instr_0F62_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem32(ctx, "instr_0F62", modrm_byte, r); +} +pub fn instr_0F62_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm32(ctx, "instr_0F62", r1, r2); +} + +pub fn instr_0F63_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F63", modrm_byte, r); +} +pub fn instr_0F63_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F63", r1, r2); +} +pub fn instr_0F64_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F64", modrm_byte, r); +} +pub fn instr_0F64_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F64", r1, r2); +} +pub fn instr_0F65_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F65", modrm_byte, r); +} +pub fn instr_0F65_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F65", r1, r2); +} +pub fn instr_0F66_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F66", modrm_byte, r); +} +pub fn instr_0F66_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F66", r1, r2); +} +pub fn instr_0F67_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F67", modrm_byte, r); +} +pub fn instr_0F67_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F67", r1, r2); +} +pub fn instr_0F68_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F68", modrm_byte, r); +} +pub fn instr_0F68_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F68", r1, r2); +} +pub fn instr_0F69_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F69", modrm_byte, r); +} +pub fn instr_0F69_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F69", r1, r2); +} +pub fn instr_0F6A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F6A", modrm_byte, r); +} +pub fn instr_0F6A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F6A", r1, r2); +} +pub fn instr_0F6B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F6B", modrm_byte, r); +} +pub fn instr_0F6B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F6B", r1, r2); +} + +pub fn instr_660F60_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + // Note: Only requires 64-bit read, but is allowed to do 128-bit read + sse_read128_xmm_mem(ctx, "instr_660F60", modrm_byte, r); +} +pub fn instr_660F60_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F60", r1, r2); +} +pub fn instr_660F61_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + // Note: Only requires 64-bit read, but is allowed to do 128-bit read + sse_read128_xmm_mem(ctx, "instr_660F61", modrm_byte, r); +} +pub fn instr_660F61_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F61", r1, r2); +} +pub fn instr_660F62_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + let src = global_pointers::sse_scratch_register as u32; + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, src); + ctx.builder.const_i32(0); + ctx.builder.load_fixed_i32(src + 4); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r) + 12); + + ctx.builder.const_i32(0); + ctx.builder + .load_fixed_i32(global_pointers::get_reg_xmm_offset(r) + 4); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r) + 8); + + ctx.builder.const_i32(0); + ctx.builder.load_fixed_i32(src + 0); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r) + 4); +} +pub fn instr_660F62_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(0); + ctx.builder + .load_fixed_i32(global_pointers::get_reg_xmm_offset(r1) + 4); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r2) + 12); + + ctx.builder.const_i32(0); + ctx.builder + .load_fixed_i32(global_pointers::get_reg_xmm_offset(r2) + 4); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r2) + 8); + + ctx.builder.const_i32(0); + ctx.builder + .load_fixed_i32(global_pointers::get_reg_xmm_offset(r1) + 0); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r2) + 4); +} +pub fn instr_660F63_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F63", modrm_byte, r); +} +pub fn instr_660F63_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F63", r1, r2); +} +pub fn instr_660F64_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F64", modrm_byte, r); +} +pub fn instr_660F64_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F64", r1, r2); +} +pub fn instr_660F65_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F65", modrm_byte, r); +} +pub fn instr_660F65_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F65", r1, r2); +} +pub fn instr_660F66_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F66", modrm_byte, r); +} +pub fn instr_660F66_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F66", r1, r2); +} +pub fn instr_660F67_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F67", modrm_byte, r); +} +pub fn instr_660F67_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F67", r1, r2); +} +pub fn instr_660F68_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F68", modrm_byte, r); +} +pub fn instr_660F68_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F68", r1, r2); +} +pub fn instr_660F69_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F69", modrm_byte, r); +} +pub fn instr_660F69_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F69", r1, r2); +} +pub fn instr_660F6A_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F6A", modrm_byte, r); +} +pub fn instr_660F6A_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F6A", r1, r2); +} +pub fn instr_660F6B_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F6B", modrm_byte, r); +} +pub fn instr_660F6B_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F6B", r1, r2); +} +pub fn instr_660F6C_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F6C", modrm_byte, r); +} +pub fn instr_660F6C_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F6C", r1, r2); +} +pub fn instr_660F6D_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F6D", modrm_byte, r); +} +pub fn instr_660F6D_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F6D", r1, r2); +} + +pub fn instr_0F6E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn2("instr_0F6E") +} +pub fn instr_0F6E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_get_reg32(ctx, r1); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2("instr_0F6E") +} + +pub fn instr_660F6E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + ctx.builder.const_i32(0); + codegen::gen_modrm_resolve_safe_read32(ctx, modrm_byte); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder + .store_aligned_i64(global_pointers::get_reg_xmm_offset(r)); + ctx.builder.const_i32(0); + ctx.builder.const_i64(0); + ctx.builder + .store_aligned_i64(global_pointers::get_reg_xmm_offset(r) + 8); +} +pub fn instr_660F6E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(0); + codegen::gen_get_reg32(ctx, r1); + ctx.builder.extend_unsigned_i32_to_i64(); + ctx.builder + .store_aligned_i64(global_pointers::get_reg_xmm_offset(r2)); + ctx.builder.const_i32(0); + ctx.builder.const_i64(0); + ctx.builder + .store_aligned_i64(global_pointers::get_reg_xmm_offset(r2) + 8); +} + +pub fn instr_0F6F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + // XXX: Aligned read or #gp + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn2_i64_i32("instr_0F6F") +} +pub fn instr_0F6F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(r1 as i32); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2("instr_0F6F_reg") +} + +pub fn instr_660F6F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + // XXX: Aligned read or #gp + let dest = global_pointers::get_reg_xmm_offset(r); + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, dest); +} +pub fn instr_660F6F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r1, r2) } +pub fn instr_F30F6F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + let dest = global_pointers::get_reg_xmm_offset(r); + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, dest); +} +pub fn instr_F30F6F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r1, r2) } + +pub fn instr_0F70_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn3_i64_i32_i32("instr_0F70"); +} +pub fn instr_0F70_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_mmx_offset(r1) as i32); + ctx.builder.load_aligned_i64(0); + ctx.builder.const_i32(r2 as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn3_i64_i32_i32("instr_0F70"); +} +pub fn instr_660F70_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + let src = global_pointers::sse_scratch_register as u32; + codegen::gen_modrm_resolve_safe_read128(ctx, modrm_byte, src); + for i in 0..4 { + ctx.builder.const_i32(0); + ctx.builder.load_fixed_i32(src + 4 * (imm8 >> 2 * i & 3)); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r) + 4 * i); + } +} +pub fn instr_660F70_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + codegen::gen_read_reg_xmm128_into_scratch(ctx, r1); + // TODO: perf: copy less (handle aliased src/dst), use 64-bit loads/stores if possible + let src = global_pointers::sse_scratch_register as u32; + for i in 0..4 { + ctx.builder.const_i32(0); + ctx.builder.load_fixed_i32(src + 4 * (imm8 >> 2 * i & 3)); + ctx.builder + .store_aligned_i32(global_pointers::get_reg_xmm_offset(r2) + 4 * i); + } +} +pub fn instr_F20F70_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + sse_read128_xmm_mem_imm(ctx, "instr_F20F70", modrm_byte, r, imm8) +} +pub fn instr_F20F70_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + sse_read128_xmm_xmm_imm(ctx, "instr_F20F70", r1, r2, imm8) +} +pub fn instr_F30F70_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32, imm8: u32) { + sse_read128_xmm_mem_imm(ctx, "instr_F30F70", modrm_byte, r, imm8) +} +pub fn instr_F30F70_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32, imm8: u32) { + sse_read128_xmm_xmm_imm(ctx, "instr_F30F70", r1, r2, imm8) +} + +pub fn instr_0F71_2_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_0F71_2_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_0F71_2_reg"); +} +pub fn instr_0F71_4_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_0F71_4_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_0F71_4_reg"); +} +pub fn instr_0F71_6_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_0F71_6_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_0F71_6_reg"); +} + +pub fn instr_0F72_2_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_0F72_2_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_0F72_2_reg"); +} +pub fn instr_0F72_4_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_0F72_4_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_0F72_4_reg"); +} +pub fn instr_0F72_6_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_0F72_6_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_0F72_6_reg"); +} + +pub fn instr_0F73_2_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_0F73_2_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_0F73_2_reg"); +} +pub fn instr_0F73_6_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_0F73_6_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_0F73_6_reg"); +} + +pub fn instr_660F71_2_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F71_2_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F71_2_reg"); +} +pub fn instr_660F71_4_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F71_4_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F71_4_reg"); +} +pub fn instr_660F71_6_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F71_6_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F71_6_reg"); +} + +pub fn instr_660F72_2_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F72_2_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F72_2_reg"); +} +pub fn instr_660F72_4_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F72_4_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F72_4_reg"); +} +pub fn instr_660F72_6_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F72_6_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F72_6_reg"); +} + +pub fn instr_660F73_2_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F73_2_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F73_2_reg"); +} +pub fn instr_660F73_3_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F73_3_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F73_3_reg"); +} +pub fn instr_660F73_6_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F73_6_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F73_6_reg"); +} +pub fn instr_660F73_7_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _imm: u32) { + codegen::gen_trigger_ud(ctx); +} +pub fn instr_660F73_7_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + ctx.builder.const_i32(r as i32); + ctx.builder.const_i32(imm8 as i32); + ctx.builder.call_fn2("instr_660F73_7_reg"); +} + +pub fn instr_0F74_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F74", modrm_byte, r); +} +pub fn instr_0F74_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F74", r1, r2); +} +pub fn instr_0F75_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F75", modrm_byte, r); +} +pub fn instr_0F75_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F75", r1, r2); +} +pub fn instr_0F76_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0F76", modrm_byte, r); +} +pub fn instr_0F76_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0F76", r1, r2); +} + +pub fn instr_660F74_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F74", modrm_byte, r); +} +pub fn instr_660F74_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F74", r1, r2); +} +pub fn instr_660F75_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F75", modrm_byte, r); +} +pub fn instr_660F75_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F75", r1, r2); +} +pub fn instr_660F76_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660F76", modrm_byte, r); +} +pub fn instr_660F76_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660F76", r1, r2); +} + +pub fn instr_0F7E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn1_ret("instr_0F7E"); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); +} +pub fn instr_0F7E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn1_ret("instr_0F7E"); + codegen::gen_set_reg32(ctx, r1); +} + +pub fn instr_660F7E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + ctx.builder + .load_fixed_i32(global_pointers::get_reg_xmm_offset(r)); + let value_local = ctx.builder.set_new_local(); + codegen::gen_safe_write32(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local(value_local); +} +pub fn instr_660F7E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder + .load_fixed_i32(global_pointers::get_reg_xmm_offset(r2)); + codegen::gen_set_reg32(ctx, r1); +} + +pub fn instr_0F7F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + ctx.builder.const_i32(r as i32); + ctx.builder.call_fn1_ret_i64("instr_0F7F"); + let value_local = ctx.builder.set_new_local_i64(); + codegen::gen_safe_write64(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local_i64(value_local); +} +pub fn instr_0F7F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(r1 as i32); + ctx.builder.const_i32(r2 as i32); + ctx.builder.call_fn2("instr_0F7F_reg") +} + +pub fn instr_F30F7E_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r) as i32); + codegen::gen_modrm_resolve_safe_read64(ctx, modrm_byte); + ctx.builder.store_aligned_i64(0); + + ctx.builder + .const_i32(global_pointers::get_reg_xmm_offset(r) as i32 + 8); + ctx.builder.const_i64(0); + ctx.builder.store_aligned_i64(0); +} +pub fn instr_F30F7E_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + instr_660FD6_reg_jit(ctx, r2, r1) +} + +pub fn instr_660F7F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_0F29_mem_jit(ctx, modrm_byte, r); +} +pub fn instr_660F7F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r2, r1) } +pub fn instr_F30F7F_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_0F29_mem_jit(ctx, modrm_byte, r); +} +pub fn instr_F30F7F_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { sse_mov_xmm_xmm(ctx, r2, r1) } + +pub fn instr16_0FA0_jit(ctx: &mut JitContext) { + codegen::gen_get_sreg(ctx, regs::FS); + let sreg = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &sreg); + ctx.builder.free_local(sreg); +} +pub fn instr32_0FA0_jit(ctx: &mut JitContext) { codegen::gen_push32_sreg(ctx, regs::FS) } +pub fn instr16_0FA8_jit(ctx: &mut JitContext) { + codegen::gen_get_sreg(ctx, regs::GS); + let sreg = ctx.builder.set_new_local(); + codegen::gen_push16(ctx, &sreg); + ctx.builder.free_local(sreg); +} +pub fn instr32_0FA8_jit(ctx: &mut JitContext) { codegen::gen_push32_sreg(ctx, regs::GS) } + +pub fn instr16_0FA3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_bt( + &mut ctx.builder, + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r2 as usize]), + 15, + ) +} +pub fn instr16_0FA3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + codegen::gen_get_reg16(ctx, r); + codegen::sign_extend_i16(ctx.builder); + ctx.builder.const_i32(3); + ctx.builder.shr_s_i32(); + ctx.builder.add_i32(); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read8(ctx, &address_local); + ctx.builder.free_local(address_local); + let value = ctx.builder.set_new_local(); + gen_bt( + &mut ctx.builder, + &value, + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r as usize]), + 7, + ); + ctx.builder.free_local(value); +} +pub fn instr32_0FA3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_bt( + &mut ctx.builder, + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r2 as usize]), + 31, + ) +} +pub fn instr32_0FA3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + codegen::gen_get_reg32(ctx, r); + ctx.builder.const_i32(3); + ctx.builder.shr_s_i32(); + ctx.builder.add_i32(); + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read8(ctx, &address_local); + ctx.builder.free_local(address_local); + let value = ctx.builder.set_new_local(); + gen_bt( + &mut ctx.builder, + &value, + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r as usize]), + 7, + ); + ctx.builder.free_local(value); +} + +pub fn instr16_0FAB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_bts( + &mut ctx.builder, + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r2 as usize]), + 15, + ) +} +pub fn instr16_0FAB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_bts, + &LocalOrImmediate::WasmLocal(&ctx.reg(r)), + 16, + ); +} +pub fn instr32_0FAB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_bts( + &mut ctx.builder, + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r2 as usize]), + 31, + ) +} +pub fn instr32_0FAB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_bts, + &LocalOrImmediate::WasmLocal(&ctx.reg(r)), + 32, + ); +} + +pub fn instr16_0FB3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_btr( + &mut ctx.builder, + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r2 as usize]), + 15, + ) +} +pub fn instr16_0FB3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_btr, + &LocalOrImmediate::WasmLocal(&ctx.reg(r)), + 16, + ); +} +pub fn instr32_0FB3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_btr( + &mut ctx.builder, + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r2 as usize]), + 31, + ) +} +pub fn instr32_0FB3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_btr, + &LocalOrImmediate::WasmLocal(&ctx.reg(r)), + 32, + ); +} + +pub fn instr16_0FBB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_btc( + &mut ctx.builder, + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r2 as usize]), + 15, + ) +} +pub fn instr16_0FBB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_btc, + &LocalOrImmediate::WasmLocal(&ctx.reg(r)), + 16, + ); +} +pub fn instr32_0FBB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + gen_btc( + &mut ctx.builder, + &ctx.register_locals[r1 as usize], + &LocalOrImmediate::WasmLocal(&ctx.register_locals[r2 as usize]), + 31, + ) +} +pub fn instr32_0FBB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_btc, + &LocalOrImmediate::WasmLocal(&ctx.reg(r)), + 32, + ); +} + +pub fn instr16_0FBA_4_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + gen_bt( + &mut ctx.builder, + &ctx.register_locals[r as usize], + &LocalOrImmediate::Immediate(imm8 as i32), + 15, + ) +} +pub fn instr16_0FBA_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm8: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let offset = (imm8 as i32 & 15) >> 3; + if offset != 0 { + ctx.builder.const_i32(offset); + ctx.builder.add_i32(); + } + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read8(ctx, &address_local); + ctx.builder.free_local(address_local); + let value = ctx.builder.set_new_local(); + gen_bt( + &mut ctx.builder, + &value, + &LocalOrImmediate::Immediate(imm8 as i32), + 7, + ); + ctx.builder.free_local(value); +} +pub fn instr32_0FBA_4_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + gen_bt( + &mut ctx.builder, + &ctx.register_locals[r as usize], + &LocalOrImmediate::Immediate(imm8 as i32), + 31, + ) +} +pub fn instr32_0FBA_4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm8: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let offset = (imm8 as i32 & 31) >> 3; + if offset != 0 { + ctx.builder.const_i32(offset); + ctx.builder.add_i32(); + } + let address_local = ctx.builder.set_new_local(); + codegen::gen_safe_read8(ctx, &address_local); + ctx.builder.free_local(address_local); + let value = ctx.builder.set_new_local(); + gen_bt( + &mut ctx.builder, + &value, + &LocalOrImmediate::Immediate(imm8 as i32), + 7, + ); + ctx.builder.free_local(value); +} + +pub fn instr16_0FBA_5_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + gen_bts( + &mut ctx.builder, + &ctx.register_locals[r as usize], + &LocalOrImmediate::Immediate(imm8 as i32), + 15, + ) +} +pub fn instr16_0FBA_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm8: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_bts, + &LocalOrImmediate::Immediate(imm8 as i32), + 16, + ); +} +pub fn instr32_0FBA_5_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + gen_bts( + &mut ctx.builder, + &ctx.register_locals[r as usize], + &LocalOrImmediate::Immediate(imm8 as i32), + 31, + ) +} +pub fn instr32_0FBA_5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm8: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_bts, + &LocalOrImmediate::Immediate(imm8 as i32), + 32, + ); +} + +pub fn instr16_0FBA_6_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + gen_btr( + &mut ctx.builder, + &ctx.register_locals[r as usize], + &LocalOrImmediate::Immediate(imm8 as i32), + 15, + ) +} +pub fn instr16_0FBA_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm8: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_btr, + &LocalOrImmediate::Immediate(imm8 as i32), + 16, + ); +} +pub fn instr32_0FBA_6_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + gen_btr( + &mut ctx.builder, + &ctx.register_locals[r as usize], + &LocalOrImmediate::Immediate(imm8 as i32), + 31, + ) +} +pub fn instr32_0FBA_6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm8: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_btr, + &LocalOrImmediate::Immediate(imm8 as i32), + 32, + ); +} + +pub fn instr16_0FBA_7_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + gen_btc( + &mut ctx.builder, + &ctx.register_locals[r as usize], + &LocalOrImmediate::Immediate(imm8 as i32), + 15, + ) +} +pub fn instr16_0FBA_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm8: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_btc, + &LocalOrImmediate::Immediate(imm8 as i32), + 16, + ); +} +pub fn instr32_0FBA_7_reg_jit(ctx: &mut JitContext, r: u32, imm8: u32) { + gen_btc( + &mut ctx.builder, + &ctx.register_locals[r as usize], + &LocalOrImmediate::Immediate(imm8 as i32), + 31, + ) +} +pub fn instr32_0FBA_7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, imm8: u32) { + gen_bit_rmw( + ctx, + modrm_byte, + &gen_btc, + &LocalOrImmediate::Immediate(imm8 as i32), + 32, + ); +} + +pub fn instr_0FAE_5_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte) { + dbg_log!("Generating #ud for unimplemented instruction: instr_0FAE_5_mem_jit"); + codegen::gen_trigger_ud(ctx); +} +pub fn instr_0FAE_5_reg_jit(_ctx: &mut JitContext, _r: u32) { + // For this instruction, the processor ignores the r/m field of the ModR/M byte. +} + +pub fn instr_0FD1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FD1", modrm_byte, r); +} +pub fn instr_0FD1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FD1", r1, r2); +} +pub fn instr_0FD2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FD2", modrm_byte, r); +} +pub fn instr_0FD2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FD2", r1, r2); +} +pub fn instr_0FD3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FD3", modrm_byte, r); +} +pub fn instr_0FD3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FD3", r1, r2); +} +pub fn instr_0FD4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FD4", modrm_byte, r); +} +pub fn instr_0FD4_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FD4", r1, r2); +} +pub fn instr_0FD5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FD5", modrm_byte, r); +} +pub fn instr_0FD5_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FD5", r1, r2); +} + +pub fn instr_0FD7_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _r: u32) { + codegen::gen_trigger_ud(ctx) +} +pub fn instr_0FD7_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(r1 as i32); + ctx.builder.call_fn1_ret("instr_0FD7"); + codegen::gen_set_reg32(ctx, r2); +} + +pub fn instr_0FD8_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FD8", modrm_byte, r); +} +pub fn instr_0FD8_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FD8", r1, r2); +} +pub fn instr_0FD9_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FD9", modrm_byte, r); +} +pub fn instr_0FD9_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FD9", r1, r2); +} +pub fn instr_0FDA_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FDA", modrm_byte, r); +} +pub fn instr_0FDA_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FDA", r1, r2); +} +pub fn instr_0FDB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FDB", modrm_byte, r); +} +pub fn instr_0FDB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FDB", r1, r2); +} +pub fn instr_0FDC_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FDC", modrm_byte, r); +} +pub fn instr_0FDC_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FDC", r1, r2); +} +pub fn instr_0FDD_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FDD", modrm_byte, r); +} +pub fn instr_0FDD_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FDD", r1, r2); +} +pub fn instr_0FDE_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FDE", modrm_byte, r); +} +pub fn instr_0FDE_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FDE", r1, r2); +} +pub fn instr_0FDF_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FDF", modrm_byte, r); +} +pub fn instr_0FDF_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FDF", r1, r2); +} + +pub fn instr_660FD1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FD1", modrm_byte, r); +} +pub fn instr_660FD1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FD1", r1, r2); +} +pub fn instr_660FD2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FD2", modrm_byte, r); +} +pub fn instr_660FD2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FD2", r1, r2); +} +pub fn instr_660FD3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FD3", modrm_byte, r); +} +pub fn instr_660FD3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FD3", r1, r2); +} +pub fn instr_660FD4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FD4", modrm_byte, r); +} +pub fn instr_660FD4_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FD4", r1, r2); +} +pub fn instr_660FD5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FD5", modrm_byte, r); +} +pub fn instr_660FD5_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FD5", r1, r2); +} + +pub fn instr_660FD6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + codegen::gen_modrm_resolve(ctx, modrm_byte); + let address_local = ctx.builder.set_new_local(); + ctx.builder + .load_fixed_i64(global_pointers::get_reg_xmm_offset(r)); + let value_local = ctx.builder.set_new_local_i64(); + codegen::gen_safe_write64(ctx, &address_local, &value_local); + ctx.builder.free_local(address_local); + ctx.builder.free_local_i64(value_local); +} +pub fn instr_660FD6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(0); + ctx.builder + .load_fixed_i64(global_pointers::get_reg_xmm_offset(r2)); + ctx.builder + .store_aligned_i64(global_pointers::get_reg_xmm_offset(r1)); + ctx.builder.const_i32(0); + ctx.builder.const_i64(0); + ctx.builder + .store_aligned_i64(global_pointers::get_reg_xmm_offset(r1) + 8); +} + +pub fn instr_660FD7_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _r: u32) { + codegen::gen_trigger_ud(ctx) +} +pub fn instr_660FD7_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + ctx.builder.const_i32(r1 as i32); + ctx.builder.call_fn1_ret("instr_660FD7"); + codegen::gen_set_reg32(ctx, r2); +} + +pub fn instr_660FD8_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FD8", modrm_byte, r); +} +pub fn instr_660FD8_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FD8", r1, r2); +} +pub fn instr_660FD9_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FD9", modrm_byte, r); +} +pub fn instr_660FD9_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FD9", r1, r2); +} +pub fn instr_660FDA_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FDA", modrm_byte, r); +} +pub fn instr_660FDA_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FDA", r1, r2); +} +pub fn instr_660FDB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FDB", modrm_byte, r); +} +pub fn instr_660FDB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FDB", r1, r2); +} +pub fn instr_660FDC_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FDC", modrm_byte, r); +} +pub fn instr_660FDC_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FDC", r1, r2); +} +pub fn instr_660FDD_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FDD", modrm_byte, r); +} +pub fn instr_660FDD_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FDD", r1, r2); +} +pub fn instr_660FDE_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FDE", modrm_byte, r); +} +pub fn instr_660FDE_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FDE", r1, r2); +} +pub fn instr_660FDF_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FDF", modrm_byte, r); +} +pub fn instr_660FDF_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FDF", r1, r2); +} + +pub fn instr_0FE0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FE0", modrm_byte, r); +} +pub fn instr_0FE0_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FE0", r1, r2); +} +pub fn instr_0FE1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FE1", modrm_byte, r); +} +pub fn instr_0FE1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FE1", r1, r2); +} +pub fn instr_0FE2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FE2", modrm_byte, r); +} +pub fn instr_0FE2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FE2", r1, r2); +} +pub fn instr_0FE3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FE3", modrm_byte, r); +} +pub fn instr_0FE3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FE3", r1, r2); +} +pub fn instr_0FE4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FE4", modrm_byte, r); +} +pub fn instr_0FE4_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FE4", r1, r2); +} +pub fn instr_0FE5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FE5", modrm_byte, r); +} +pub fn instr_0FE5_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FE5", r1, r2); +} + +pub fn instr_0FE8_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FE8", modrm_byte, r); +} +pub fn instr_0FE8_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FE8", r1, r2); +} +pub fn instr_0FE9_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FE9", modrm_byte, r); +} +pub fn instr_0FE9_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FE9", r1, r2); +} +pub fn instr_0FEA_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FEA", modrm_byte, r); +} +pub fn instr_0FEA_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FEA", r1, r2); +} +pub fn instr_0FEB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FEB", modrm_byte, r); +} +pub fn instr_0FEB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FEB", r1, r2); +} +pub fn instr_0FEC_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FEC", modrm_byte, r); +} +pub fn instr_0FEC_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FEC", r1, r2); +} +pub fn instr_0FED_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FED", modrm_byte, r); +} +pub fn instr_0FED_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FED", r1, r2); +} +pub fn instr_0FEE_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FEE", modrm_byte, r); +} +pub fn instr_0FEE_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FEE", r1, r2); +} +pub fn instr_0FEF_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FEF", modrm_byte, r); +} +pub fn instr_0FEF_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FEF", r1, r2); +} + +pub fn instr_660FE0_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FE0", modrm_byte, r); +} +pub fn instr_660FE0_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FE0", r1, r2); +} +pub fn instr_660FE1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FE1", modrm_byte, r); +} +pub fn instr_660FE1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FE1", r1, r2); +} +pub fn instr_660FE2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FE2", modrm_byte, r); +} +pub fn instr_660FE2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FE2", r1, r2); +} +pub fn instr_660FE3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FE3", modrm_byte, r); +} +pub fn instr_660FE3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FE3", r1, r2); +} +pub fn instr_660FE4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FE4", modrm_byte, r); +} +pub fn instr_660FE4_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FE4", r1, r2); +} +pub fn instr_660FE5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FE5", modrm_byte, r); +} +pub fn instr_660FE5_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FE5", r1, r2); +} + +pub fn instr_660FE6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FE6", modrm_byte, r); +} +pub fn instr_660FE6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FE6", r1, r2); +} +pub fn instr_F20FE6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_F20FE6", modrm_byte, r); +} +pub fn instr_F20FE6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_F20FE6", r1, r2); +} +pub fn instr_F30FE6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read64_xmm_mem(ctx, "instr_F30FE6", modrm_byte, r); +} +pub fn instr_F30FE6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read64_xmm_xmm(ctx, "instr_F30FE6", r1, r2); +} + +pub fn instr_660FE7_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + instr_0F29_mem_jit(ctx, modrm_byte, r); +} +pub fn instr_660FE7_reg_jit(ctx: &mut JitContext, _r1: u32, _r2: u32) { + codegen::gen_trigger_ud(ctx); +} + +pub fn instr_660FE8_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FE8", modrm_byte, r); +} +pub fn instr_660FE8_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FE8", r1, r2); +} +pub fn instr_660FE9_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FE9", modrm_byte, r); +} +pub fn instr_660FE9_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FE9", r1, r2); +} +pub fn instr_660FEA_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FEA", modrm_byte, r); +} +pub fn instr_660FEA_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FEA", r1, r2); +} +pub fn instr_660FEB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FEB", modrm_byte, r); +} +pub fn instr_660FEB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FEB", r1, r2); +} +pub fn instr_660FEC_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FEC", modrm_byte, r); +} +pub fn instr_660FEC_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FEC", r1, r2); +} +pub fn instr_660FED_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FED", modrm_byte, r); +} +pub fn instr_660FED_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FED", r1, r2); +} +pub fn instr_660FEE_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FEE", modrm_byte, r); +} +pub fn instr_660FEE_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FEE", r1, r2); +} +pub fn instr_660FEF_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FEF", modrm_byte, r); +} +pub fn instr_660FEF_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FEF", r1, r2); +} + +pub fn instr_0FF1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FF1", modrm_byte, r); +} +pub fn instr_0FF1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FF1", r1, r2); +} +pub fn instr_0FF2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FF2", modrm_byte, r); +} +pub fn instr_0FF2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FF2", r1, r2); +} +pub fn instr_0FF3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FF3", modrm_byte, r); +} +pub fn instr_0FF3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FF3", r1, r2); +} +pub fn instr_0FF4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FF4", modrm_byte, r); +} +pub fn instr_0FF4_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FF4", r1, r2); +} +pub fn instr_0FF5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FF5", modrm_byte, r); +} +pub fn instr_0FF5_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FF5", r1, r2); +} +pub fn instr_0FF6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FF6", modrm_byte, r); +} +pub fn instr_0FF6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FF6", r1, r2); +} + +pub fn instr_0FF7_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _r: u32) { + codegen::gen_trigger_ud(ctx) +} +pub fn instr_0FF7_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_set_previous_eip_offset_from_eip_with_low_bits( + ctx.builder, + ctx.start_of_current_instruction as i32 & 0xFFF, + ); + + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.const_i32(r1 as i32); + ctx.builder.const_i32(r2 as i32); + if ctx.cpu.asize_32() { + codegen::gen_get_reg32(ctx, regs::EDI); + } + else { + codegen::gen_get_reg16(ctx, regs::DI); + } + jit_add_seg_offset(ctx, regs::DS); + ctx.builder.call_fn3("maskmovq"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + + codegen::gen_get_page_fault(ctx.builder); + ctx.builder.if_void(); + codegen::gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.br(ctx.exit_label); + ctx.builder.block_end(); +} + +pub fn instr_0FF8_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FF8", modrm_byte, r); +} +pub fn instr_0FF8_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FF8", r1, r2); +} +pub fn instr_0FF9_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FF9", modrm_byte, r); +} +pub fn instr_0FF9_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FF9", r1, r2); +} +pub fn instr_0FFA_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FFA", modrm_byte, r); +} +pub fn instr_0FFA_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FFA", r1, r2); +} +pub fn instr_0FFB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FFB", modrm_byte, r); +} +pub fn instr_0FFB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FFB", r1, r2); +} +pub fn instr_0FFC_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FFC", modrm_byte, r); +} +pub fn instr_0FFC_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FFC", r1, r2); +} +pub fn instr_0FFD_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FFD", modrm_byte, r); +} +pub fn instr_0FFD_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FFD", r1, r2); +} +pub fn instr_0FFE_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + mmx_read64_mm_mem(ctx, "instr_0FFE", modrm_byte, r); +} +pub fn instr_0FFE_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + mmx_read64_mm_mm(ctx, "instr_0FFE", r1, r2); +} + +pub fn instr_660FF1_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FF1", modrm_byte, r); +} +pub fn instr_660FF1_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FF1", r1, r2); +} +pub fn instr_660FF2_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FF2", modrm_byte, r); +} +pub fn instr_660FF2_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FF2", r1, r2); +} +pub fn instr_660FF3_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FF3", modrm_byte, r); +} +pub fn instr_660FF3_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FF3", r1, r2); +} +pub fn instr_660FF4_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FF4", modrm_byte, r); +} +pub fn instr_660FF4_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FF4", r1, r2); +} +pub fn instr_660FF5_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FF5", modrm_byte, r); +} +pub fn instr_660FF5_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FF5", r1, r2); +} +pub fn instr_660FF6_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FF6", modrm_byte, r); +} +pub fn instr_660FF6_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FF6", r1, r2); +} + +pub fn instr_660FF7_mem_jit(ctx: &mut JitContext, _modrm_byte: ModrmByte, _r: u32) { + codegen::gen_trigger_ud(ctx) +} +pub fn instr_660FF7_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + codegen::gen_set_previous_eip_offset_from_eip_with_low_bits( + ctx.builder, + ctx.start_of_current_instruction as i32 & 0xFFF, + ); + + codegen::gen_move_registers_from_locals_to_memory(ctx); + ctx.builder.const_i32(r1 as i32); + ctx.builder.const_i32(r2 as i32); + if ctx.cpu.asize_32() { + codegen::gen_get_reg32(ctx, regs::EDI); + } + else { + codegen::gen_get_reg16(ctx, regs::DI); + } + jit_add_seg_offset(ctx, regs::DS); + ctx.builder.call_fn3("maskmovdqu"); + codegen::gen_move_registers_from_memory_to_locals(ctx); + + codegen::gen_get_page_fault(ctx.builder); + ctx.builder.if_void(); + codegen::gen_debug_track_jit_exit(ctx.builder, ctx.start_of_current_instruction); + ctx.builder.br(ctx.exit_label); + ctx.builder.block_end(); +} + +pub fn instr_660FF8_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FF8", modrm_byte, r); +} +pub fn instr_660FF8_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FF8", r1, r2); +} +pub fn instr_660FF9_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FF9", modrm_byte, r); +} +pub fn instr_660FF9_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FF9", r1, r2); +} +pub fn instr_660FFA_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FFA", modrm_byte, r); +} +pub fn instr_660FFA_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FFA", r1, r2); +} +pub fn instr_660FFB_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FFB", modrm_byte, r); +} +pub fn instr_660FFB_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FFB", r1, r2); +} +pub fn instr_660FFC_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FFC", modrm_byte, r); +} +pub fn instr_660FFC_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FFC", r1, r2); +} +pub fn instr_660FFD_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FFD", modrm_byte, r); +} +pub fn instr_660FFD_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FFD", r1, r2); +} +pub fn instr_660FFE_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) { + sse_read128_xmm_mem(ctx, "instr_660FFE", modrm_byte, r); +} +pub fn instr_660FFE_reg_jit(ctx: &mut JitContext, r1: u32, r2: u32) { + sse_read128_xmm_xmm(ctx, "instr_660FFE", r1, r2); +} diff --git a/src/rust/js_api.rs b/src/rust/js_api.rs new file mode 100644 index 0000000..d218fa0 --- /dev/null +++ b/src/rust/js_api.rs @@ -0,0 +1,6 @@ +use cpu::cpu::translate_address_system_read; + +#[no_mangle] +pub unsafe fn translate_address_system_read_js(addr: i32) -> u32 { + translate_address_system_read(addr).unwrap() +} diff --git a/src/rust/leb.rs b/src/rust/leb.rs new file mode 100644 index 0000000..d74601e --- /dev/null +++ b/src/rust/leb.rs @@ -0,0 +1,46 @@ +pub fn write_leb_i32(buf: &mut Vec, v: i32) { write_leb_i64(buf, v as i64); } + +pub fn write_leb_i64(buf: &mut Vec, mut v: i64) { + // https://en.wikipedia.org/wiki/LEB128#Encode_signed_integer + loop { + let mut byte = v as u8 & 0b0111_1111; + v >>= 7; + let sign = byte & (1 << 6); + let done = v == 0 && sign == 0 || v == -1 && sign != 0; + if !done { + byte |= 0b1000_0000; + } + buf.push(byte); + if done { + break; + } + } +} + +pub fn write_leb_u32(buf: &mut Vec, mut v: u32) { + loop { + let mut byte = v as u8 & 0b0111_1111; + v >>= 7; + if v != 0 { + byte |= 0b1000_0000; + } + buf.push(byte); + if v == 0 { + break; + } + } +} + +pub fn write_fixed_leb16_at_idx(vec: &mut Vec, idx: usize, x: u16) { + dbg_assert!(x < (1 << 14)); // we have 14 bits of available space in 2 bytes for leb + vec[idx] = ((x & 0b1111111) | 0b10000000) as u8; + vec[idx + 1] = (x >> 7) as u8; +} + +pub fn write_fixed_leb32_at_idx(vec: &mut Vec, idx: usize, x: u32) { + dbg_assert!(x < (1 << 28)); // we have 28 bits of available space in 4 bytes for leb + vec[idx] = (x & 0b1111111) as u8 | 0b10000000; + vec[idx + 1] = (x >> 7 & 0b1111111) as u8 | 0b10000000; + vec[idx + 2] = (x >> 14 & 0b1111111) as u8 | 0b10000000; + vec[idx + 3] = (x >> 21 & 0b1111111) as u8; +} diff --git a/src/rust/lib.rs b/src/rust/lib.rs new file mode 100644 index 0000000..ebd3b89 --- /dev/null +++ b/src/rust/lib.rs @@ -0,0 +1,32 @@ +#![allow(const_item_mutation)] + +#[macro_use] +mod dbg; + +#[macro_use] +mod paging; + +pub mod cpu; + +pub mod js_api; +pub mod profiler; + +mod analysis; +mod codegen; +mod config; +mod control_flow; +mod cpu_context; +mod gen; +mod jit; +mod jit_instructions; +mod leb; +mod modrm; +mod opstats; +mod page; +mod prefix; +mod regs; +mod softfloat; +mod state_flags; +mod util; +mod wasmgen; +mod zstd; diff --git a/src/rust/modrm.rs b/src/rust/modrm.rs new file mode 100644 index 0000000..8fabb9f --- /dev/null +++ b/src/rust/modrm.rs @@ -0,0 +1,320 @@ +use codegen; +use cpu::global_pointers; +use cpu_context::CpuContext; +use jit::JitContext; +use prefix::{PREFIX_MASK_SEGMENT, SEG_PREFIX_ZERO}; +use profiler; +use regs::{BP, BX, DI, SI}; +use regs::{CS, DS, ES, FS, GS, SS}; +use regs::{EAX, EBP, EBX, ECX, EDI, EDX, ESI, ESP}; + +pub struct ModrmByte { + segment: u32, + first_reg: Option, + second_reg: Option, + shift: u8, + immediate: i32, + is_16: bool, +} +impl ModrmByte { + pub fn is_nop(&self, reg: u32) -> bool { + self.first_reg == Some(reg) + && self.second_reg.is_none() + && self.shift == 0 + && self.immediate == 0 + && !self.is_16 + } +} + +pub fn decode(ctx: &mut CpuContext, modrm_byte: u8) -> ModrmByte { + if ctx.asize_32() { decode32(ctx, modrm_byte) } else { decode16(ctx, modrm_byte) } +} + +fn decode16(ctx: &mut CpuContext, modrm_byte: u8) -> ModrmByte { + fn mk16( + segment: u32, + first_reg: Option, + second_reg: Option, + immediate: i32, + ) -> ModrmByte { + ModrmByte { + segment, + first_reg, + second_reg, + shift: 0, + immediate, + is_16: true, + } + } + + match modrm_byte & !0o070 { + 0o000 => mk16(DS, Some(BX), Some(SI), 0), + 0o001 => mk16(DS, Some(BX), Some(DI), 0), + 0o002 => mk16(SS, Some(BP), Some(SI), 0), + 0o003 => mk16(SS, Some(BP), Some(DI), 0), + 0o004 => mk16(DS, Some(SI), None, 0), + 0o005 => mk16(DS, Some(DI), None, 0), + 0o006 => mk16(DS, None, None, ctx.read_imm16() as i32), + 0o007 => mk16(DS, Some(BX), None, 0), + + 0o100 => mk16(DS, Some(BX), Some(SI), ctx.read_imm8s() as i32), + 0o101 => mk16(DS, Some(BX), Some(DI), ctx.read_imm8s() as i32), + 0o102 => mk16(SS, Some(BP), Some(SI), ctx.read_imm8s() as i32), + 0o103 => mk16(SS, Some(BP), Some(DI), ctx.read_imm8s() as i32), + 0o104 => mk16(DS, Some(SI), None, ctx.read_imm8s() as i32), + 0o105 => mk16(DS, Some(DI), None, ctx.read_imm8s() as i32), + 0o106 => mk16(SS, Some(BP), None, ctx.read_imm8s() as i32), + 0o107 => mk16(DS, Some(BX), None, ctx.read_imm8s() as i32), + + 0o200 => mk16(DS, Some(BX), Some(SI), ctx.read_imm16() as i32), + 0o201 => mk16(DS, Some(BX), Some(DI), ctx.read_imm16() as i32), + 0o202 => mk16(SS, Some(BP), Some(SI), ctx.read_imm16() as i32), + 0o203 => mk16(SS, Some(BP), Some(DI), ctx.read_imm16() as i32), + 0o204 => mk16(DS, Some(SI), None, ctx.read_imm16() as i32), + 0o205 => mk16(DS, Some(DI), None, ctx.read_imm16() as i32), + 0o206 => mk16(SS, Some(BP), None, ctx.read_imm16() as i32), + 0o207 => mk16(DS, Some(BX), None, ctx.read_imm16() as i32), + + _ => panic!("modrm byte >= 0xC0"), + } +} + +fn decode32(ctx: &mut CpuContext, modrm_byte: u8) -> ModrmByte { + fn mk32(segment: u32, first_reg: Option, immediate: i32) -> ModrmByte { + ModrmByte { + segment, + first_reg, + second_reg: None, + shift: 0, + immediate, + is_16: false, + } + } + + match modrm_byte & !0o070 { + 0o000 => mk32(DS, Some(EAX), 0), + 0o001 => mk32(DS, Some(ECX), 0), + 0o002 => mk32(DS, Some(EDX), 0), + 0o003 => mk32(DS, Some(EBX), 0), + 0o004 => decode_sib(ctx, Imm32::None), + 0o005 => mk32(DS, None, ctx.read_imm32() as i32), + 0o006 => mk32(DS, Some(ESI), 0), + 0o007 => mk32(DS, Some(EDI), 0), + + 0o100 => mk32(DS, Some(EAX), ctx.read_imm8s() as i32), + 0o101 => mk32(DS, Some(ECX), ctx.read_imm8s() as i32), + 0o102 => mk32(DS, Some(EDX), ctx.read_imm8s() as i32), + 0o103 => mk32(DS, Some(EBX), ctx.read_imm8s() as i32), + 0o104 => decode_sib(ctx, Imm32::Imm8), + 0o105 => mk32(SS, Some(EBP), ctx.read_imm8s() as i32), + 0o106 => mk32(DS, Some(ESI), ctx.read_imm8s() as i32), + 0o107 => mk32(DS, Some(EDI), ctx.read_imm8s() as i32), + + 0o200 => mk32(DS, Some(EAX), ctx.read_imm32() as i32), + 0o201 => mk32(DS, Some(ECX), ctx.read_imm32() as i32), + 0o202 => mk32(DS, Some(EDX), ctx.read_imm32() as i32), + 0o203 => mk32(DS, Some(EBX), ctx.read_imm32() as i32), + 0o204 => decode_sib(ctx, Imm32::Imm32), + 0o205 => mk32(SS, Some(EBP), ctx.read_imm32() as i32), + 0o206 => mk32(DS, Some(ESI), ctx.read_imm32() as i32), + 0o207 => mk32(DS, Some(EDI), ctx.read_imm32() as i32), + + _ => panic!("modrm byte >= 0xC0"), + } +} + +fn decode_sib(ctx: &mut CpuContext, immediate: Imm32) -> ModrmByte { + let sib_byte = ctx.read_imm8(); + let r = sib_byte & 7; + let m = sib_byte >> 3 & 7; + let shift = sib_byte >> 6 & 3; + + let second_reg = if m == 4 { None } else { Some(m as u32) }; + + let segment; + let reg; + + if r == 4 { + segment = SS; + reg = ESP; + } + else if r == 5 { + if immediate == Imm32::None { + return ModrmByte { + segment: DS, + first_reg: None, + second_reg, + shift, + immediate: ctx.read_imm32() as i32, + is_16: false, + }; + } + else { + segment = SS; + reg = EBP; + } + } + else { + segment = DS; + reg = r as u32; + } + + let immediate = match immediate { + Imm32::None => 0, + Imm32::Imm8 => ctx.read_imm8s() as i32, + Imm32::Imm32 => ctx.read_imm32() as i32, + }; + + ModrmByte { + segment, + first_reg: Some(reg), + second_reg, + shift, + immediate, + is_16: false, + } +} + +pub fn gen(ctx: &mut JitContext, modrm_byte: ModrmByte) { + codegen::gen_profiler_stat_increment( + ctx.builder, + match modrm_byte { + ModrmByte { + first_reg: None, + second_reg: None, + .. + } => profiler::stat::MODRM_SIMPLE_CONST_OFFSET, + ModrmByte { + first_reg: Some(_), + second_reg: None, + .. + } + | ModrmByte { + first_reg: None, + second_reg: Some(_), + shift: 0, + .. + } => { + if modrm_byte.immediate == 0 { + profiler::stat::MODRM_SIMPLE_REG + } + else { + profiler::stat::MODRM_SIMPLE_REG_WITH_OFFSET + } + }, + _ => profiler::stat::MODRM_COMPLEX, + }, + ); + + let mut have_something_on_stack = false; + + if let Some(reg) = modrm_byte.first_reg { + codegen::gen_get_reg32(ctx, reg); + have_something_on_stack = true; + } + + if let Some(reg) = modrm_byte.second_reg { + codegen::gen_get_reg32(ctx, reg); + if modrm_byte.shift != 0 { + ctx.builder.const_i32(modrm_byte.shift.into()); + ctx.builder.shl_i32(); + } + if have_something_on_stack { + ctx.builder.add_i32(); + } + have_something_on_stack = true; + } + + if modrm_byte.immediate != 0 || !have_something_on_stack { + ctx.builder.const_i32(modrm_byte.immediate); + if have_something_on_stack { + ctx.builder.add_i32(); + } + } + + if modrm_byte.is_16 { + ctx.builder.const_i32(0xFFFF); + ctx.builder.and_i32(); + } + jit_add_seg_offset(ctx, modrm_byte.segment); +} + +pub fn get_as_reg_index_if_possible(ctx: &mut JitContext, modrm_byte: &ModrmByte) -> Option { + let prefix = ctx.cpu.prefixes & PREFIX_MASK_SEGMENT; + let seg = if prefix != 0 { prefix - 1 } else { modrm_byte.segment }; + if can_optimize_get_seg(ctx, seg) + && modrm_byte.second_reg.is_none() + && modrm_byte.immediate == 0 + && !modrm_byte.is_16 + && modrm_byte.shift == 0 + { + modrm_byte.first_reg + } + else { + None + } +} + +pub fn skip(ctx: &mut CpuContext, modrm_byte: u8) { let _ = decode(ctx, modrm_byte); } + +#[derive(PartialEq)] +enum Imm32 { + None, + Imm8, + Imm32, +} + +fn can_optimize_get_seg(ctx: &mut JitContext, segment: u32) -> bool { + (segment == DS || segment == SS || segment == CS) && ctx.cpu.has_flat_segmentation() +} + +pub fn jit_add_seg_offset(ctx: &mut JitContext, default_segment: u32) { + let prefix = ctx.cpu.prefixes & PREFIX_MASK_SEGMENT; + + if prefix == SEG_PREFIX_ZERO { + return; + } + + let seg = if prefix != 0 { prefix - 1 } else { default_segment }; + jit_add_seg_offset_no_override(ctx, seg); +} + +pub fn jit_add_seg_offset_no_override(ctx: &mut JitContext, seg: u32) { + if can_optimize_get_seg(ctx, seg) { + codegen::gen_profiler_stat_increment(ctx.builder, profiler::stat::SEG_OFFSET_OPTIMISED); + return; + } + codegen::gen_profiler_stat_increment(ctx.builder, profiler::stat::SEG_OFFSET_NOT_OPTIMISED); + codegen::gen_profiler_stat_increment( + ctx.builder, + if seg == ES { + profiler::stat::SEG_OFFSET_NOT_OPTIMISED_ES + } + else if seg == FS { + profiler::stat::SEG_OFFSET_NOT_OPTIMISED_FS + } + else if seg == GS { + profiler::stat::SEG_OFFSET_NOT_OPTIMISED_GS + } + else { + profiler::stat::SEG_OFFSET_NOT_OPTIMISED_NOT_FLAT + }, + ); + + if seg != CS && seg != SS { + if cfg!(feature = "profiler") { + ctx.builder.const_i32(seg as i32); + ctx.builder.call_fn1("log_segment_null"); + } + + ctx.builder + .load_fixed_u8(global_pointers::get_segment_is_null_offset(seg)); + ctx.builder.if_void(); + codegen::gen_trigger_gp(ctx, 0); + ctx.builder.block_end(); + } + + ctx.builder + .load_fixed_i32(global_pointers::get_seg_offset(seg)); + ctx.builder.add_i32(); +} diff --git a/src/rust/opstats.rs b/src/rust/opstats.rs new file mode 100644 index 0000000..3b091e9 --- /dev/null +++ b/src/rust/opstats.rs @@ -0,0 +1,249 @@ +use wasmgen::wasm_builder::WasmBuilder; + +const SIZE: usize = if cfg!(feature = "profiler") { 8192 } else { 0 }; + +#[allow(non_upper_case_globals)] +pub static mut opstats_buffer: [u64; SIZE] = [0; SIZE]; +#[allow(non_upper_case_globals)] +pub static mut opstats_compiled_buffer: [u64; SIZE] = [0; SIZE]; +#[allow(non_upper_case_globals)] +pub static mut opstats_jit_exit_buffer: [u64; SIZE] = [0; SIZE]; +#[allow(non_upper_case_globals)] +pub static mut opstats_unguarded_register_buffer: [u64; SIZE] = [0; SIZE]; +#[allow(non_upper_case_globals)] +pub static mut opstats_wasm_size: [u64; SIZE] = [0; SIZE]; + +pub struct Instruction { + pub prefixes: Vec, + pub opcode: u8, + pub fixed_g: u8, + pub is_mem: bool, + pub is_0f: bool, +} + +pub fn decode(mut instruction: u32) -> Instruction { + let mut is_0f = false; + let mut prefixes = vec![]; + let mut final_opcode = 0; + + for _ in 0..4 { + let opcode = (instruction & 0xFF) as u8; + instruction >>= 8; + + // TODO: + // - If the instruction uses 4 or more prefixes, only the prefixes will be counted + + if is_0f { + final_opcode = opcode; + break; + } + else { + if opcode == 0x0F { + is_0f = true; + } + else if opcode == 0x26 + || opcode == 0x2E + || opcode == 0x36 + || opcode == 0x3E + || opcode == 0x64 + || opcode == 0x65 + || opcode == 0x66 + || opcode == 0x67 + || opcode == 0xF0 + || opcode == 0xF2 + || opcode == 0xF3 + { + prefixes.push(opcode); + } + else { + final_opcode = opcode; + break; + } + } + } + + let has_modrm_byte = if is_0f { + match final_opcode { + 0x0 | 0x1 | 0x2 | 0x3 | 0x10 | 0x11 | 0x12 | 0x13 | 0x14 | 0x15 | 0x16 | 0x17 + | 0x18 | 0x19 | 0x20 | 0x21 | 0x22 | 0x23 | 0x28 | 0x29 | 0x40 | 0x41 | 0x42 | 0x43 + | 0x44 | 0x45 | 0x46 | 0x47 | 0x48 | 0x49 | 0x50 | 0x51 | 0x52 | 0x53 | 0x54 | 0x55 + | 0x56 | 0x57 | 0x58 | 0x59 | 0x60 | 0x61 | 0x62 | 0x63 | 0x64 | 0x65 | 0x66 | 0x67 + | 0x68 | 0x69 | 0x70 | 0x71 | 0x72 | 0x73 | 0x74 | 0x75 | 0x76 | 0x90 | 0x91 | 0x92 + | 0x93 | 0x94 | 0x95 | 0x96 | 0x97 | 0x98 | 0x99 | 0x1c | 0x1d | 0x1e | 0x1f | 0x2a + | 0x2b | 0x2c | 0x2d | 0x2e | 0x2f | 0x4a | 0x4b | 0x4c | 0x4d | 0x4e | 0x4f | 0x5a + | 0x5b | 0x5c | 0x5d | 0x5e | 0x5f | 0x6a | 0x6b | 0x6c | 0x6d | 0x6e | 0x6f | 0x7e + | 0x7f | 0x9a | 0x9b | 0x9c | 0x9d | 0x9e | 0x9f | 0xa3 | 0xa4 | 0xa5 | 0xab | 0xac + | 0xad | 0xae | 0xaf | 0xb0 | 0xb1 | 0xb2 | 0xb3 | 0xb4 | 0xb5 | 0xb6 | 0xb7 | 0xb8 + | 0xba | 0xbb | 0xbc | 0xbd | 0xbe | 0xbf | 0xc0 | 0xc1 | 0xc2 | 0xc3 | 0xc4 | 0xc5 + | 0xc6 | 0xc7 | 0xd1 | 0xd2 | 0xd3 | 0xd4 | 0xd5 | 0xd6 | 0xd7 | 0xd8 | 0xd9 | 0xda + | 0xdb | 0xdc | 0xdd | 0xde | 0xdf | 0xe0 | 0xe1 | 0xe2 | 0xe3 | 0xe4 | 0xe5 | 0xe6 + | 0xe7 | 0xe8 | 0xe9 | 0xea | 0xeb | 0xec | 0xed | 0xee | 0xef | 0xf1 | 0xf2 | 0xf3 + | 0xf4 | 0xf5 | 0xf6 | 0xf7 | 0xf8 | 0xf9 | 0xfa | 0xfb | 0xfc | 0xfd | 0xfe => true, + _ => false, + } + } + else { + match final_opcode { + 0x0 | 0x1 | 0x2 | 0x3 | 0x8 | 0x9 | 0x10 | 0x11 | 0x12 | 0x13 | 0x18 | 0x19 | 0x20 + | 0x21 | 0x22 | 0x23 | 0x28 | 0x29 | 0x30 | 0x31 | 0x32 | 0x33 | 0x38 | 0x39 | 0x62 + | 0x63 | 0x69 | 0x80 | 0x81 | 0x82 | 0x83 | 0x84 | 0x85 | 0x86 | 0x87 | 0x88 | 0x89 + | 0xa | 0xb | 0x1a | 0x1b | 0x2a | 0x2b | 0x3a | 0x3b | 0x6b | 0x8a | 0x8b | 0x8c + | 0x8d | 0x8e | 0x8f | 0xc0 | 0xc1 | 0xc4 | 0xc5 | 0xc6 | 0xc7 | 0xd0 | 0xd1 | 0xd2 + | 0xd3 | 0xd8 | 0xd9 | 0xda | 0xdb | 0xdc | 0xdd | 0xde | 0xdf | 0xf6 | 0xf7 | 0xfe + | 0xff => true, + _ => false, + } + }; + + let has_fixed_g = if is_0f { + final_opcode == 0x71 + || final_opcode == 0x72 + || final_opcode == 0x73 + || final_opcode == 0xAE + || final_opcode == 0xBA + || final_opcode == 0xC7 + } + else { + final_opcode >= 0x80 && final_opcode < 0x84 + || final_opcode >= 0xC0 && final_opcode < 0xC2 + || final_opcode >= 0xD0 && final_opcode < 0xD4 + || final_opcode >= 0xD8 && final_opcode < 0xE0 + || final_opcode >= 0xF6 && final_opcode < 0xF8 + || final_opcode == 0xFE + || final_opcode == 0xFF + }; + + let mut is_mem = false; + let mut fixed_g = 0; + + if has_fixed_g { + dbg_assert!(has_modrm_byte); + let modrm_byte = (instruction & 0xFF) as u8; + fixed_g = modrm_byte >> 3 & 7; + is_mem = modrm_byte < 0xC0 + } + if has_modrm_byte { + let modrm_byte = (instruction & 0xFF) as u8; + is_mem = modrm_byte < 0xC0 + } + + Instruction { + prefixes, + opcode: final_opcode, + is_mem, + fixed_g, + is_0f, + } +} + +pub fn gen_opstats(builder: &mut WasmBuilder, opcode: u32) { + if !cfg!(feature = "profiler") { + return; + } + + let instruction = decode(opcode); + + for prefix in instruction.prefixes { + let index = (prefix as u32) << 4; + builder.increment_fixed_i64( + unsafe { &mut opstats_buffer[index as usize] as *mut _ } as u32, + 1, + ); + } + + let index = (instruction.is_0f as u32) << 12 + | (instruction.opcode as u32) << 4 + | (instruction.is_mem as u32) << 3 + | instruction.fixed_g as u32; + + builder.increment_fixed_i64( + unsafe { &mut opstats_buffer[index as usize] as *mut _ } as u32, + 1, + ); +} + +pub fn record_opstat_compiled(opcode: u32) { + if !cfg!(feature = "profiler") { + return; + } + + let instruction = decode(opcode); + + for prefix in instruction.prefixes { + let index = (prefix as u32) << 4; + unsafe { opstats_compiled_buffer[index as usize] += 1 } + } + + let index = (instruction.is_0f as u32) << 12 + | (instruction.opcode as u32) << 4 + | (instruction.is_mem as u32) << 3 + | instruction.fixed_g as u32; + + unsafe { opstats_compiled_buffer[index as usize] += 1 } +} + +pub fn record_opstat_jit_exit(opcode: u32) { + if !cfg!(feature = "profiler") { + return; + } + + let instruction = decode(opcode); + + for prefix in instruction.prefixes { + let index = (prefix as u32) << 4; + unsafe { opstats_jit_exit_buffer[index as usize] += 1 } + } + + let index = (instruction.is_0f as u32) << 12 + | (instruction.opcode as u32) << 4 + | (instruction.is_mem as u32) << 3 + | instruction.fixed_g as u32; + + unsafe { opstats_jit_exit_buffer[index as usize] += 1 } +} + +pub fn gen_opstat_unguarded_register(builder: &mut WasmBuilder, opcode: u32) { + if !cfg!(feature = "profiler") { + return; + } + + let instruction = decode(opcode); + + for prefix in instruction.prefixes { + let index = (prefix as u32) << 4; + builder.increment_fixed_i64( + unsafe { &mut opstats_unguarded_register_buffer[index as usize] as *mut _ } as u32, + 1, + ); + } + + let index = (instruction.is_0f as u32) << 12 + | (instruction.opcode as u32) << 4 + | (instruction.is_mem as u32) << 3 + | instruction.fixed_g as u32; + + builder.increment_fixed_i64( + unsafe { &mut opstats_unguarded_register_buffer[index as usize] as *mut _ } as u32, + 1, + ); +} + +pub fn record_opstat_size_wasm(opcode: u32, size: u64) { + if !cfg!(feature = "profiler") { + return; + } + + let instruction = decode(opcode); + + for prefix in instruction.prefixes { + let index = (prefix as u32) << 4; + unsafe { opstats_wasm_size[index as usize] += size } + } + + let index = (instruction.is_0f as u32) << 12 + | (instruction.opcode as u32) << 4 + | (instruction.is_mem as u32) << 3 + | instruction.fixed_g as u32; + + unsafe { opstats_wasm_size[index as usize] += size } +} diff --git a/src/rust/page.rs b/src/rust/page.rs new file mode 100644 index 0000000..5ecccf3 --- /dev/null +++ b/src/rust/page.rs @@ -0,0 +1,15 @@ +use std::ops::RangeInclusive; + +#[derive(Copy, Clone, Eq, Hash, PartialEq)] +pub struct Page(u32); +impl Page { + pub fn page_of(address: u32) -> Page { Page(address >> 12) } + pub fn to_address(self) -> u32 { self.0 << 12 } + + pub fn to_u32(self) -> u32 { self.0 } + pub fn of_u32(page: u32) -> Page { Page(page) } + + pub fn address_range(self) -> RangeInclusive { + self.to_address()..=self.to_address() + 4095 + } +} diff --git a/src/rust/paging.rs b/src/rust/paging.rs new file mode 100644 index 0000000..22bc66c --- /dev/null +++ b/src/rust/paging.rs @@ -0,0 +1,25 @@ +pub type OrPageFault = Result; + +macro_rules! return_on_pagefault { + ($expr:expr) => { + match $expr { + Ok(v) => v, + Err(()) => return, + } + }; + ($expr:expr, $ret:expr) => { + match $expr { + Ok(v) => v, + Err(()) => return $ret, + } + }; +} + +macro_rules! break_on_pagefault { + ($expr:expr) => { + match $expr { + Ok(v) => v, + Err(()) => break, + } + }; +} diff --git a/src/rust/prefix.rs b/src/rust/prefix.rs new file mode 100644 index 0000000..ba8adaa --- /dev/null +++ b/src/rust/prefix.rs @@ -0,0 +1,14 @@ +pub const PREFIX_REPZ: u32 = 0b01000; +pub const PREFIX_REPNZ: u32 = 0b10000; + +pub const PREFIX_MASK_OPSIZE: u32 = 0b100000; +pub const PREFIX_MASK_ADDRSIZE: u32 = 0b1000000; + +pub const PREFIX_66: u32 = PREFIX_MASK_OPSIZE; +pub const PREFIX_67: u32 = PREFIX_MASK_ADDRSIZE; +pub const PREFIX_F2: u32 = PREFIX_REPNZ; +pub const PREFIX_F3: u32 = PREFIX_REPZ; + +pub const SEG_PREFIX_ZERO: u32 = 7; + +pub const PREFIX_MASK_SEGMENT: u32 = 0b111; diff --git a/src/rust/profiler.rs b/src/rust/profiler.rs new file mode 100644 index 0000000..e494c7f --- /dev/null +++ b/src/rust/profiler.rs @@ -0,0 +1,152 @@ +#[allow(non_camel_case_types)] +pub enum stat { + COMPILE, + COMPILE_SKIPPED_NO_NEW_ENTRY_POINTS, + COMPILE_WRONG_ADDRESS_SPACE, + COMPILE_CUT_OFF_AT_END_OF_PAGE, + COMPILE_WITH_LOOP_SAFETY, + COMPILE_PAGE, + COMPILE_BASIC_BLOCK, + COMPILE_DUPLICATED_BASIC_BLOCK, + COMPILE_WASM_BLOCK, + COMPILE_WASM_LOOP, + COMPILE_DISPATCHER, + COMPILE_ENTRY_POINT, + COMPILE_WASM_TOTAL_BYTES, + + RUN_INTERPRETED, + RUN_INTERPRETED_NEW_PAGE, + RUN_INTERPRETED_PAGE_HAS_CODE, + RUN_INTERPRETED_PAGE_HAS_ENTRY_AFTER_PAGE_WALK, + RUN_INTERPRETED_NEAR_END_OF_PAGE, + RUN_INTERPRETED_DIFFERENT_STATE, + RUN_INTERPRETED_DIFFERENT_STATE_CPL3, + RUN_INTERPRETED_DIFFERENT_STATE_FLAT, + RUN_INTERPRETED_DIFFERENT_STATE_IS32, + RUN_INTERPRETED_DIFFERENT_STATE_SS32, + RUN_INTERPRETED_MISSED_COMPILED_ENTRY_RUN_INTERPRETED, + RUN_INTERPRETED_STEPS, + + RUN_FROM_CACHE, + RUN_FROM_CACHE_STEPS, + + DIRECT_EXIT, + INDIRECT_JUMP, + INDIRECT_JUMP_NO_ENTRY, + NORMAL_PAGE_CHANGE, + NORMAL_FALLTHRU, + NORMAL_FALLTHRU_WITH_TARGET_BLOCK, + NORMAL_BRANCH, + NORMAL_BRANCH_WITH_TARGET_BLOCK, + CONDITIONAL_JUMP, + CONDITIONAL_JUMP_PAGE_CHANGE, + CONDITIONAL_JUMP_EXIT, + CONDITIONAL_JUMP_FALLTHRU, + CONDITIONAL_JUMP_FALLTHRU_WITH_TARGET_BLOCK, + CONDITIONAL_JUMP_BRANCH, + CONDITIONAL_JUMP_BRANCH_WITH_TARGET_BLOCK, + DISPATCHER_SMALL, + DISPATCHER_LARGE, + LOOP, + + LOOP_SAFETY, + + CONDITION_OPTIMISED, + CONDITION_UNOPTIMISED, + CONDITION_UNOPTIMISED_PF, + CONDITION_UNOPTIMISED_UNHANDLED_L, + CONDITION_UNOPTIMISED_UNHANDLED_LE, + + FAILED_PAGE_CHANGE, + + SAFE_READ_FAST, + SAFE_READ_SLOW_PAGE_CROSSED, + SAFE_READ_SLOW_NOT_VALID, + SAFE_READ_SLOW_NOT_USER, + SAFE_READ_SLOW_IN_MAPPED_RANGE, + + SAFE_WRITE_FAST, + SAFE_WRITE_SLOW_PAGE_CROSSED, + SAFE_WRITE_SLOW_NOT_VALID, + SAFE_WRITE_SLOW_NOT_USER, + SAFE_WRITE_SLOW_IN_MAPPED_RANGE, + SAFE_WRITE_SLOW_READ_ONLY, + SAFE_WRITE_SLOW_HAS_CODE, + + SAFE_READ_WRITE_FAST, + SAFE_READ_WRITE_SLOW_PAGE_CROSSED, + SAFE_READ_WRITE_SLOW_NOT_VALID, + SAFE_READ_WRITE_SLOW_NOT_USER, + SAFE_READ_WRITE_SLOW_IN_MAPPED_RANGE, + SAFE_READ_WRITE_SLOW_READ_ONLY, + SAFE_READ_WRITE_SLOW_HAS_CODE, + + PAGE_FAULT, + TLB_MISS, + + DO_MANY_CYCLES, + CYCLE_INTERNAL, + + INVALIDATE_ALL_MODULES_NO_FREE_WASM_INDICES, + INVALIDATE_MODULE_WRITTEN_WHILE_COMPILED, + INVALIDATE_MODULE_UNUSED_AFTER_OVERWRITE, + INVALIDATE_MODULE_DIRTY_PAGE, + + INVALIDATE_PAGE_HAD_CODE, + INVALIDATE_PAGE_HAD_ENTRY_POINTS, + DIRTY_PAGE_DID_NOT_HAVE_CODE, + + RUN_FROM_CACHE_EXIT_SAME_PAGE, + RUN_FROM_CACHE_EXIT_NEAR_END_OF_PAGE, + RUN_FROM_CACHE_EXIT_DIFFERENT_PAGE, + + CLEAR_TLB, + FULL_CLEAR_TLB, + TLB_FULL, + TLB_GLOBAL_FULL, + + MODRM_SIMPLE_REG, + MODRM_SIMPLE_REG_WITH_OFFSET, + MODRM_SIMPLE_CONST_OFFSET, + MODRM_COMPLEX, + + SEG_OFFSET_OPTIMISED, + SEG_OFFSET_NOT_OPTIMISED, + SEG_OFFSET_NOT_OPTIMISED_ES, + SEG_OFFSET_NOT_OPTIMISED_FS, + SEG_OFFSET_NOT_OPTIMISED_GS, + SEG_OFFSET_NOT_OPTIMISED_NOT_FLAT, +} + +#[allow(non_upper_case_globals)] +pub static mut stat_array: [u64; 500] = [0; 500]; + +pub fn stat_increment(stat: stat) { stat_increment_by(stat, 1); } + +pub fn stat_increment_by(stat: stat, by: u64) { + if cfg!(feature = "profiler") { + unsafe { stat_array[stat as usize] += by } + } +} + +#[no_mangle] +pub fn profiler_init() { + unsafe { + for x in stat_array.iter_mut() { + *x = 0 + } + } +} + +#[no_mangle] +pub fn profiler_stat_get(stat: stat) -> f64 { + if cfg!(feature = "profiler") { + unsafe { stat_array[stat as usize] as f64 } + } + else { + 0.0 + } +} + +#[no_mangle] +pub fn profiler_is_enabled() -> bool { cfg!(feature = "profiler") } diff --git a/src/rust/regs.rs b/src/rust/regs.rs new file mode 100644 index 0000000..37af689 --- /dev/null +++ b/src/rust/regs.rs @@ -0,0 +1,38 @@ +pub const ES: u32 = 0; +pub const CS: u32 = 1; +pub const SS: u32 = 2; +pub const DS: u32 = 3; +pub const FS: u32 = 4; +pub const GS: u32 = 5; + +pub const EAX: u32 = 0; +pub const ECX: u32 = 1; +pub const EDX: u32 = 2; +pub const EBX: u32 = 3; +pub const ESP: u32 = 4; +pub const EBP: u32 = 5; +pub const ESI: u32 = 6; +pub const EDI: u32 = 7; + +pub const AX: u32 = 0; +pub const CX: u32 = 1; +pub const DX: u32 = 2; +pub const BX: u32 = 3; +pub const SP: u32 = 4; +pub const BP: u32 = 5; +pub const SI: u32 = 6; +pub const DI: u32 = 7; + +pub const AL: u32 = 0; +pub const CL: u32 = 1; +pub const DL: u32 = 2; +pub const BL: u32 = 3; +pub const AH: u32 = 4; +pub const CH: u32 = 5; +pub const DH: u32 = 6; +pub const BH: u32 = 7; + +pub const CR0_EM: u32 = 1 << 2; +pub const CR0_TS: u32 = 1 << 3; + +pub const CR4_TSD: u32 = 1 << 2; diff --git a/src/rust/softfloat.rs b/src/rust/softfloat.rs new file mode 100644 index 0000000..782146c --- /dev/null +++ b/src/rust/softfloat.rs @@ -0,0 +1,305 @@ +extern "C" { + fn extF80M_add(x: *const F80, y: *const F80, ptr: *mut F80); + fn extF80M_sub(x: *const F80, y: *const F80, ptr: *mut F80); + fn extF80M_mul(x: *const F80, y: *const F80, ptr: *mut F80); + fn extF80M_div(x: *const F80, y: *const F80, ptr: *mut F80); + //fn extF80M_rem(x: *const F80, y: *const F80, ptr: *mut F80); + fn extF80M_sqrt(x: *const F80, ptr: *mut F80); + + fn extF80M_roundToInt(x: *const F80, rounding_mode: u8, raise_inexact: bool, dst: *mut F80); + + fn extF80M_eq(x: *const F80, y: *const F80) -> bool; + //fn extF80M_eq_signaling(x: *const F80, y: *const F80) -> bool; + + //fn extF80M_le(x: *const F80, y: *const F80) -> bool; + //fn extF80M_le_quiet(x: *const F80, y: *const F80) -> bool; + fn extF80M_lt(x: *const F80, y: *const F80) -> bool; + fn extF80M_lt_quiet(x: *const F80, y: *const F80) -> bool; + + fn extF80M_to_i32(src: *const F80, rounding_mode: u8, raise_inexact: bool) -> i32; + fn extF80M_to_i64(src: *const F80, rounding_mode: u8, raise_inexact: bool) -> i64; + fn i32_to_extF80M(src: i32, dst: *mut F80); + fn i64_to_extF80M(src: i64, dst: *mut F80); + + fn f32_to_extF80M(src: i32, dst: *mut F80); + fn f64_to_extF80M(src: u64, dst: *mut F80); + fn extF80M_to_f32(src: *const F80) -> i32; + fn extF80M_to_f64(src: *const F80) -> u64; + + static mut softfloat_roundingMode: u8; + static mut extF80_roundingPrecision: u8; + static mut softfloat_exceptionFlags: u8; +} + +pub enum RoundingMode { + NearEven, + Trunc, + Floor, + Ceil, +} +pub enum Precision { + P80, + P64, + P32, +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct F80 { + pub mantissa: u64, + pub sign_exponent: u16, +} +impl F80 { + pub const ZERO: F80 = F80 { + mantissa: 0, + sign_exponent: 0, + }; + pub const ONE: F80 = F80 { + mantissa: 0x8000000000000000, + sign_exponent: 0x3FFF, + }; + pub const LN_10: F80 = F80 { + mantissa: 0x935D8DDDAAA8B000, + sign_exponent: 0x4000, + }; + pub const LN_2: F80 = F80 { + mantissa: 0xB17217F7D1CF7800, + sign_exponent: 0x3FFE, + }; + pub const PI: F80 = F80 { + mantissa: 0xC90FDAA22168C000, + sign_exponent: 0x4000, + }; + pub const LOG2_E: F80 = F80 { + mantissa: 0xB8AA3B295C17F000, + sign_exponent: 0x3FFF, + }; + pub const INDEFINITE_NAN: F80 = F80 { + mantissa: 0xC000000000000000, + sign_exponent: 0x7FFF, + }; + pub const POS_INFINITY: F80 = F80 { + mantissa: 0x8000000000000000, + sign_exponent: 0x7FFF, + }; + pub const NEG_INFINITY: F80 = F80 { + mantissa: 0x8000000000000000, + sign_exponent: 0xFFFF, + }; + + pub fn sign(&self) -> bool { (self.sign_exponent >> 15) == 1 } + pub fn exponent(&self) -> i16 { (self.sign_exponent as i16 & 0x7FFF) - 0x3FFF } + + pub fn of_i32(src: i32) -> F80 { + let mut x = F80::ZERO; + unsafe { + i32_to_extF80M(src, &mut x) + }; + x + } + pub fn of_i64(src: i64) -> F80 { + let mut x = F80::ZERO; + unsafe { + i64_to_extF80M(src, &mut x) + }; + x + } + + pub fn of_f32(src: i32) -> F80 { + let mut x = F80::ZERO; + unsafe { + f32_to_extF80M(src, &mut x) + }; + x + } + + pub fn of_f64(src: u64) -> F80 { + let mut x = F80::ZERO; + unsafe { + f64_to_extF80M(src, &mut x) + }; + x + } + fn of_f64x(src: f64) -> F80 { F80::of_f64(unsafe { std::mem::transmute(src) }) } + + pub fn to_f32(&self) -> i32 { unsafe { extF80M_to_f32(self) } } + pub fn to_f64(&self) -> u64 { unsafe { extF80M_to_f64(self) } } + fn to_f64x(&self) -> f64 { unsafe { std::mem::transmute(extF80M_to_f64(self)) } } + + pub fn to_i32(&self) -> i32 { unsafe { extF80M_to_i32(self, softfloat_roundingMode, false) } } + pub fn to_i64(&self) -> i64 { unsafe { extF80M_to_i64(self, softfloat_roundingMode, false) } } + + pub fn cos(self) -> F80 { F80::of_f64x(self.to_f64x().cos()) } + pub fn sin(self) -> F80 { F80::of_f64x(self.to_f64x().sin()) } + pub fn tan(self) -> F80 { F80::of_f64x(self.to_f64x().tan()) } + pub fn atan(self) -> F80 { F80::of_f64x(self.to_f64x().atan()) } + pub fn atan2(self, other: F80) -> F80 { F80::of_f64x(self.to_f64x().atan2(other.to_f64x())) } + + pub fn log2(self) -> F80 { F80::of_f64x(self.to_f64x().log2()) } + pub fn ln(self) -> F80 { F80::of_f64x(self.to_f64x().ln()) } + + pub fn abs(self) -> F80 { + F80 { + mantissa: self.mantissa, + sign_exponent: self.sign_exponent & !0x8000, + } + } + pub fn two_pow(self) -> F80 { F80::of_f64x(2.0f64.powf(self.to_f64x())) } + pub fn round(self) -> F80 { + let mut result = F80::ZERO; + unsafe { + extF80M_roundToInt(&self, softfloat_roundingMode, false, &mut result) + }; + result + } + pub fn trunc(self) -> F80 { + let mut result = F80::ZERO; + unsafe { + extF80M_roundToInt(&self, 1, false, &mut result) + }; + result + } + + pub fn sqrt(self) -> F80 { + let mut result = F80::ZERO; + unsafe { + extF80M_sqrt(&self, &mut result) + }; + result + } + + pub fn is_finite(self) -> bool { + // TODO: Can probably be done more efficiently + self != F80::POS_INFINITY && self != F80::NEG_INFINITY + } + pub fn is_nan(self) -> bool { + // TODO: Can probably be done more efficiently + self != self + } + + pub fn set_rounding_mode(mode: RoundingMode) { + unsafe { + softfloat_roundingMode = match mode { + RoundingMode::NearEven => 0, + RoundingMode::Trunc => 1, + RoundingMode::Floor => 2, + RoundingMode::Ceil => 3, + } + }; + } + pub fn set_precision(precision: Precision) { + unsafe { + extF80_roundingPrecision = match precision { + Precision::P80 => 80, + Precision::P64 => 64, + Precision::P32 => 32, + } + }; + } + + pub fn get_exception_flags() -> u8 { + let f = unsafe { softfloat_exceptionFlags }; + // translate softfloat's flags to x87 status flags + f >> 4 & 1 | f >> 1 & 4 | f << 3 & 16 + } + pub fn clear_exception_flags() { unsafe { softfloat_exceptionFlags = 0 } } + + pub fn partial_cmp_quiet(&self, other: &Self) -> Option { + // TODO: Can probably be done more efficiently + if unsafe { extF80M_lt_quiet(self, other) } { + Some(std::cmp::Ordering::Less) + } + else if unsafe { extF80M_lt_quiet(other, self) } { + Some(std::cmp::Ordering::Greater) + } + else if self == other { + Some(std::cmp::Ordering::Equal) + } + else { + None + } + } +} + +impl std::ops::Add for F80 { + type Output = F80; + fn add(self, other: Self) -> Self { + let mut result = F80::ZERO; + unsafe { + extF80M_add(&self, &other, &mut result) + }; + result + } +} +impl std::ops::Sub for F80 { + type Output = F80; + fn sub(self, other: Self) -> Self { + let mut result = F80::ZERO; + unsafe { + extF80M_sub(&self, &other, &mut result) + }; + result + } +} +impl std::ops::Neg for F80 { + type Output = F80; + fn neg(self) -> Self { + let mut result = self; + result.sign_exponent ^= 1 << 15; + result + } +} +impl std::ops::Mul for F80 { + type Output = F80; + fn mul(self, other: Self) -> Self { + let mut result = F80::ZERO; + unsafe { + extF80M_mul(&self, &other, &mut result) + }; + result + } +} +impl std::ops::Div for F80 { + type Output = F80; + fn div(self, other: Self) -> Self { + let mut result = F80::ZERO; + unsafe { + extF80M_div(&self, &other, &mut result) + }; + result + } +} +impl std::ops::Rem for F80 { + type Output = F80; + fn rem(self, other: Self) -> Self { + let quot = (self / other).trunc(); + self - quot * other + // Uses round-to-nearest instead of truncation + //let mut result = F80::ZERO; + //unsafe { + // extF80M_rem(&self, &other, &mut result) + //}; + //result + } +} + +impl PartialEq for F80 { + fn eq(&self, other: &Self) -> bool { unsafe { extF80M_eq(self, other) } } +} +impl PartialOrd for F80 { + fn partial_cmp(&self, other: &Self) -> Option { + // TODO: Can probably be done more efficiently + if unsafe { extF80M_lt(self, other) } { + Some(std::cmp::Ordering::Less) + } + else if unsafe { extF80M_lt(other, self) } { + Some(std::cmp::Ordering::Greater) + } + else if self == other { + Some(std::cmp::Ordering::Equal) + } + else { + None + } + } +} diff --git a/src/rust/state_flags.rs b/src/rust/state_flags.rs new file mode 100644 index 0000000..94142af --- /dev/null +++ b/src/rust/state_flags.rs @@ -0,0 +1,27 @@ +#[derive(Copy, Clone, PartialEq, Eq)] +#[repr(transparent)] +pub struct CachedStateFlags(u8); + +impl CachedStateFlags { + const MASK_IS_32: u8 = 1 << 0; + const MASK_SS32: u8 = 1 << 1; + const MASK_CPL3: u8 = 1 << 2; + const MASK_FLAT_SEGS: u8 = 1 << 3; + + pub const EMPTY: CachedStateFlags = CachedStateFlags(0); + + pub fn of_u32(f: u32) -> CachedStateFlags { + dbg_assert!( + f as u8 + & !(Self::MASK_IS_32 | Self::MASK_SS32 | Self::MASK_CPL3 | Self::MASK_FLAT_SEGS) + == 0 + ); + CachedStateFlags(f as u8) + } + pub fn to_u32(&self) -> u32 { self.0 as u32 } + + pub fn cpl3(&self) -> bool { self.0 & CachedStateFlags::MASK_CPL3 != 0 } + pub fn has_flat_segmentation(&self) -> bool { self.0 & CachedStateFlags::MASK_FLAT_SEGS != 0 } + pub fn is_32(&self) -> bool { self.0 & CachedStateFlags::MASK_IS_32 != 0 } + pub fn ssize_32(&self) -> bool { self.0 & CachedStateFlags::MASK_SS32 != 0 } +} diff --git a/src/rust/util.rs b/src/rust/util.rs new file mode 100644 index 0000000..40d2625 --- /dev/null +++ b/src/rust/util.rs @@ -0,0 +1,115 @@ +pub trait SafeToU8 { + fn safe_to_u8(self) -> u8; +} +pub trait SafeToU16 { + fn safe_to_u16(self) -> u16; +} +pub trait SafeToI32 { + fn safe_to_i32(self) -> i32; +} + +impl SafeToU8 for u16 { + fn safe_to_u8(self) -> u8 { + dbg_assert!(self <= ::std::u8::MAX as u16); + self as u8 + } +} + +impl SafeToU8 for u32 { + fn safe_to_u8(self) -> u8 { + dbg_assert!(self <= ::std::u8::MAX as u32); + self as u8 + } +} + +impl SafeToU8 for i32 { + fn safe_to_u8(self) -> u8 { + dbg_assert!(self >= 0 && self <= ::std::u8::MAX as i32); + self as u8 + } +} + +impl SafeToU8 for usize { + fn safe_to_u8(self) -> u8 { + dbg_assert!(self <= ::std::u8::MAX as usize); + self as u8 + } +} + +impl SafeToU16 for u32 { + fn safe_to_u16(self) -> u16 { + dbg_assert!(self <= ::std::u16::MAX as u32); + self as u16 + } +} + +impl SafeToU16 for i32 { + fn safe_to_u16(self) -> u16 { + dbg_assert!(self >= 0 && self <= ::std::u16::MAX as i32); + self as u16 + } +} + +impl SafeToU16 for usize { + fn safe_to_u16(self) -> u16 { + dbg_assert!(self <= ::std::u16::MAX as usize); + self as u16 + } +} + +impl SafeToI32 for u32 { + fn safe_to_i32(self) -> i32 { + dbg_assert!(self <= ::std::i32::MAX as u32); + self as i32 + } +} + +impl SafeToI32 for usize { + fn safe_to_i32(self) -> i32 { + dbg_assert!(self <= ::std::i32::MAX as usize); + self as i32 + } +} + +#[allow(dead_code)] +pub const DEBUG: bool = cfg!(debug_assertions); + +#[cfg(target_arch = "wasm32")] +extern "C" { + pub fn log_from_wasm(ptr: *const u8, len: usize); + pub fn console_log_from_wasm(ptr: *const u8, len: usize); + pub fn abort(); +} + +extern "C" { + pub fn dbg_trace_from_wasm(); +} + +#[cfg(target_arch = "wasm32")] +use std::string::ToString; + +#[cfg(target_arch = "wasm32")] +pub fn log_to_js_console(s: T) { + let s: String = s.to_string(); + let len = s.len(); + unsafe { + log_from_wasm(s.as_bytes().as_ptr(), len); + } +} + +#[cfg(target_arch = "wasm32")] +pub fn console_log_to_js_console(s: T) { + let s: String = s.to_string(); + let len = s.len(); + unsafe { + console_log_from_wasm(s.as_bytes().as_ptr(), len); + } +} + +pub fn dbg_trace() { + if DEBUG { + unsafe { + dbg_trace_from_wasm(); + } + } +} diff --git a/src/rust/wasmgen/mod.rs b/src/rust/wasmgen/mod.rs new file mode 100644 index 0000000..568314b --- /dev/null +++ b/src/rust/wasmgen/mod.rs @@ -0,0 +1,2 @@ +pub mod wasm_builder; +mod wasm_opcodes; diff --git a/src/rust/wasmgen/wasm_builder.rs b/src/rust/wasmgen/wasm_builder.rs new file mode 100644 index 0000000..50e002d --- /dev/null +++ b/src/rust/wasmgen/wasm_builder.rs @@ -0,0 +1,1029 @@ +use std::collections::HashMap; + +use leb::{ + write_fixed_leb16_at_idx, write_fixed_leb32_at_idx, write_leb_i32, write_leb_i64, write_leb_u32, +}; +use std::mem::transmute; +use util::{SafeToU8, SafeToU16}; +use wasmgen::wasm_opcodes as op; + +#[derive(PartialEq)] +#[allow(non_camel_case_types)] +enum FunctionType { + FN0, + FN1, + FN2, + FN3, + + FN0_RET, + FN0_RET_I64, + FN1_RET, + FN2_RET, + + FN1_RET_I64, + FN1_F32_RET, + FN1_F64_RET, + + FN2_I32_I64, + FN2_I64_I32, + FN2_I64_I32_RET, + FN2_I64_I32_RET_I64, + FN2_F32_I32, + + FN3_RET, + + FN3_I64_I32_I32, + FN3_I32_I64_I32, + FN3_I32_I64_I32_RET, + FN4_I32_I64_I64_I32_RET, + // When adding at the end, update LAST below +} + +impl FunctionType { + pub fn of_u8(x: u8) -> FunctionType { + dbg_assert!(x <= FunctionType::LAST as u8); + unsafe { transmute(x) } + } + pub fn to_u8(self: FunctionType) -> u8 { self as u8 } + pub const LAST: FunctionType = FunctionType::FN4_I32_I64_I64_I32_RET; +} + +pub const WASM_MODULE_ARGUMENT_COUNT: u8 = 1; + +pub struct WasmBuilder { + output: Vec, + instruction_body: Vec, + + idx_import_table_size: usize, // for rewriting once finished + idx_import_count: usize, // for rewriting once finished + idx_import_entries: usize, // for searching the imports + + import_table_size: usize, // the current import table size (to avoid reading 2 byte leb) + import_count: u16, // same as above + + initial_static_size: usize, // size of module after initialization, rest is drained on reset + + // label for referencing block/if/loop constructs directly via branch instructions + next_label: Label, + label_stack: Vec